Created
September 15, 2016 15:44
-
-
Save tai-sho/5aa91c6e3db9d98ea3f71ce9ef9cb155 to your computer and use it in GitHub Desktop.
GoogleAppsScriptとSlackWebhookを利用してteratailの新規質問をSlackに通知する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* main | |
*/ | |
function main() { | |
var tagName = 'php'; | |
var questionUrl = 'https://teratail.com/questions/'; | |
var response = getQuestionByTagName(tagName, {limit: 3}); | |
if(!'questions' in response) { | |
return false; | |
} | |
var payload = getPayload(); | |
payload.text = 'teratailから' + tagName + 'の質問を自動取得しました!\n'; | |
var questions = response.questions; | |
for(var i in questions) { | |
var question = questions[i]; | |
var number = parseInt(i) + 1; | |
payload.text += '【' + number + '】' + question.title + '\n' + questionUrl + question.id + '\n'; | |
} | |
requestSlack(payload); | |
} | |
/** | |
* PAYLOADの雛形を取得します。 | |
* @returns {Object} | |
*/ | |
function getPayload() { | |
return { | |
text: '', | |
channel: null, | |
username: 'teratailQuestionPicker', | |
icon_emoji: ':grey_question:' | |
}; | |
} | |
/** | |
* teratailのタグに関連した質問を取得します。 | |
* @param {String} tagName タグ名 | |
* @param {Object} [params] パラメータ | |
* @returns {Object} | |
*/ | |
function getQuestionByTagName(tagName, params) { | |
var token = '************'; | |
var url = 'https://teratail.com/api/v1/tags/' + tagName + '/questions/'; | |
if(params) { | |
url += '?' + queryString(params); | |
} | |
var result = request(url, { | |
headers: { | |
Authorization: 'Bearer ' + token | |
} | |
}); | |
return JSON.parse(result); | |
} | |
/** | |
* slackへリクエストを行います。 | |
* @param {Object} payload | |
* @returns {String} | |
*/ | |
function requestSlack(payload) { | |
var url = 'https://hooks.slack.com/services/*******************'; | |
var result = request(url, { | |
method : 'POST', | |
payload : JSON.stringify(payload) | |
}); | |
return result; | |
} | |
/** | |
* HTTPリクエストを行い結果を返します。 | |
* @param {String} url リクエストするURL | |
* @param {Object} options オプション | |
* @returns {String} | |
*/ | |
function request(url, options) { | |
var response = UrlFetchApp.fetch(url, options); | |
return response.getContentText('UTF-8'); | |
} | |
/** | |
* オブジェクトからGETパラメータ文字列を生成します。 | |
* @param {Object} オブジェクト | |
* @returns {String} | |
*/ | |
function queryString(obj) { | |
return Object.keys(obj).map(function(key) { | |
return key + '=' + obj[key]; | |
}).join('&'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment