Created
May 16, 2015 08:40
-
-
Save app2641/4396017c3df8c5943610 to your computer and use it in GitHub Desktop.
Post GitHub trends to Chatwork
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
/** | |
* @var int | |
*/ | |
var MAX_REPOS = 4; | |
/** | |
* @return void | |
*/ | |
function postToChatworkGitHubTrends () { | |
var trends = parseGitHubTrends(); | |
var message = createTrendMessage(trends); | |
postToChatWork(message); | |
} | |
/** | |
* Parse github trends | |
* | |
* @return array | |
*/ | |
function parseGitHubTrends () { | |
var results = []; | |
var url = 'https://github.com/trending'; | |
var response = UrlFetchApp.fetch(url).getContentText(); | |
var pattern = /<a href="([^"]*)">/g; | |
var matches = response.match(pattern); | |
for (i in matches) { | |
if (i > MAX_REPOS) break; | |
var product = match[i].replace('<a href=\"', ''); | |
product = product.replace('">', ''); | |
product = product.match(/^\/[^\/]*\/[^\/]*$/); | |
if (product != null) { | |
results.push(product); | |
} | |
} | |
return results; | |
} | |
/** | |
* Create a message to post to chat | |
* | |
* @param array trends | |
* @return string | |
*/ | |
function createTrendMessage (trends) { | |
var message = '[info][title]最新の GitHub トレンド[/title]\n'; | |
if (trends.length === 0) { | |
message += '最新のトレンドはありません'; | |
} else { | |
for (i in trends) { | |
var url = 'https://github.com'+encodeURI(trends[i]); | |
message += url+'\n'; | |
} | |
} | |
message += '\n\nToday\'s trending repositories -- https://github.com/trending[/info]'; | |
return message; | |
} | |
/** | |
* Post to chat | |
* | |
* @param string message | |
* @return void | |
*/ | |
function postToChatWork (message) { | |
var api_key = 'YOUR_API_KEY'; | |
var room_id = 'ROOM_ID'; | |
message = encodeURI(message); | |
try { | |
UrlFetchApp.fetch('https://api.chatwork.com/v1/rooms/'+room+'/messages?body='+message, { | |
method: 'POST', | |
headers: {'X-ChatWorkToken': api_key} | |
}); | |
} catch (e) { | |
Logger.log(e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment