Created
April 29, 2021 01:51
-
-
Save laprasdrum/46cf33db6383b08d0f0fecbcc6128830 to your computer and use it in GitHub Desktop.
send direct messages (including group DMs) from GAS
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
const token = 'xoxb-xxx' | |
function main() { | |
var message = 'Hi :)' | |
// send direct message | |
var userID = 'UX...' | |
sendMessage(userID, message) | |
// send group direct message | |
var userIDs = ['UX...', 'OX...'] | |
var channelID = findOrCreateChannel(userIDs) | |
if (channelID) { | |
sendMessage(channelID, message) | |
} | |
} | |
function findOrCreateChannel(userIDs) { | |
if (userIDs.length == 0) { | |
return null | |
} | |
var params = { | |
'users': userIDs.join(',') | |
} | |
var options = { | |
'headers': { | |
'Authorization': `Bearer ${token}` | |
}, | |
'method': 'post', | |
'contentType': 'application/json', | |
'payload': JSON.stringify(params) | |
} | |
var response = UrlFetchApp.fetch('https://slack.com/api/conversations.open', options) | |
if (response.getResponseCode() >= 400) { | |
return nil | |
} | |
var json = JSON.parse(response.getContentText()) | |
return json.channel.id | |
} | |
function sendMessage(channelID, message) { | |
var params = { | |
'channel': channelID, | |
'text': message | |
} | |
var options = { | |
'headers': { | |
'Authorization': `Bearer ${token}` | |
}, | |
'method': 'post', | |
'contentType': 'application/json', | |
'payload': JSON.stringify(params) | |
} | |
UrlFetchApp.fetch('https://slack.com/api/chat.postMessage', options) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment