GASでSlack操作用モジュールを作ったよ
そーす
これで大体やりたいことはできる。はず
ファイル ⇒ プロジェクトのプロパティ ⇒ スクリプトのプロパティで
プロパティ:SLACK_API_TOKEN
値:{SLACK側で取得したTOKEN}
を指定して使ってね。
(function(){
"use strict";
var root = this;
root.SLACKUTILS = root.SLACKUTILS || {};
SLACKUTILS.module = SLACKUTILS.module || {};
const SLACK_API_TOKEN = PropertiesService.getScriptProperties().getProperty( "SLACK_API_TOKEN" );
SLACKUTILS.SUBTYPE_BOT = 'bot_message';
// post Messages.
SLACKUTILS.module.postMessage = function ( channelName, text, username, iconEmoji ) {
var response = UrlFetchApp.fetch(
'https://slack.com/api/chat.postMessage',
{
"method" : "post",
"payload" :
{
token : SLACK_API_TOKEN,
channel : channelName,
text : text,
username : username,
icon_emoji : iconEmoji
}
}
)
return JSON.parse( response.getContentText() );
}
// set Reactions.
SLACKUTILS.module.setReactions = function ( channelId, timestamp, reactions ) {
// reactions send.
reactions && reactions.forEach( function( reaction ){
UrlFetchApp.fetch(
'https://slack.com/api/reactions.add',
{
"method" : "post",
"payload" :
{
token : SLACK_API_TOKEN,
channel : channelId,
timestamp : timestamp,
name : reaction
}
}
);
});
}
// get history of channels / groups.
SLACKUTILS.module.getChannelsHistory = function ( channelId, type, latest, count ) {
// reactions send.
var response = UrlFetchApp.fetch(
'https://slack.com/api/' + type + '.history',
{
"method" : "get",
"payload" :
{
token : SLACK_API_TOKEN,
channel : channelId,
latest : latest,
count : count
}
}
);
return JSON.parse( response.getContentText() );
}
// get channel id by channel name.
SLACKUTILS.module.getChannelIdByName = function( channelName ) {
var findChannelId = function( type ){
var response = UrlFetchApp.fetch(
'https://slack.com/api/' + type + '.list',
{
"method" : "get",
"payload" :
{
token : SLACK_API_TOKEN
}
}
)
var channelsList = JSON.parse( response.getContentText() );
var foundChannelsId = '';
var isFound = channelsList[ type ].some( function( elements ){
if ( elements.name.match( channelName ) ){
foundChannelsId = elements.id;
return true;
}
});
return foundChannelsId;
}
return findChannelId( 'channels' ) || findChannelId( 'groups' );
}
// delete chat.
SLACKUTILS.module.deleteChat = function( channelId, ts ) {
var response = UrlFetchApp.fetch(
'https://slack.com/api/chat.delete',
{
"method" : "post",
"payload" :
{
token : SLACK_API_TOKEN,
channel : channelId,
ts : ts
}
}
);
return JSON.parse( response.getContentText() );
}
}).call( this );
総括・ハマりポイント
GASはなかなか良い開発環境。
SLACKのprivateなchannelは"groups"に所属するらしい。
メッセージにガツっとリアクションをいっぱいつけるのも楽しい。