Created
September 16, 2016 12:36
-
-
Save Istar-Eldritch/4e52cf41b418f61bebd82b6f8b46c224 to your computer and use it in GitHub Desktop.
Slack Messages
This file contains hidden or 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
import * as fetch from 'node-fetch'; | |
import {get} from 'config'; | |
const baseUri = get<string>('slack_base_uri'); | |
const token = get<string>('slack_token'); | |
const defaultOptions = { | |
headers: ['accept: application/json'] | |
} | |
interface MessageParams { | |
channel: string; | |
text: string; | |
parse?: string; | |
link_names?: number; | |
attachments?: {[id: string]: string}[]; | |
unfurl_links?: boolean; | |
unfurl_media?: boolean; | |
username?: string; | |
as_user?: boolean; | |
icon_url?: string; | |
icon_emoji?: string; | |
} | |
function paramsToQuery(params: MessageParams) { | |
return Object.keys(params).map(k => { | |
if (typeof params[k] === 'object') { | |
return `${k}=${JSON.stringify(params[k])}` | |
} | |
else { | |
return `${k}=${params[k]}` | |
} | |
}).join('&'); | |
} | |
export async function postMessage(params: MessageParams) { | |
let query = paramsToQuery(params); | |
let sentResult = await fetch(`${baseUri}/chat.postMessage?as_user=true&token=${token}&${query}`); | |
if (sentResult.ok) { | |
return await sentResult.json(); | |
} | |
else { | |
throw {name: 'MessageError', message: await sentResult.json()}; | |
} | |
} | |
export default postMessage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment