Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for direct responses #1

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,11 @@ slack.send('chat.postMessage', message).then(data => {
// respond to webhooks
slack.send('https://hooks.slack.com/services/T0000/B000/XXXX', message);
```
You can also respond to events directly without an API call using the callback method. This is useful if you need the `in_channel` response type to show the users slash command too.
```js
// Example for a command that takes a name eg: /greet Bob
slack.on('/greet', msg => slack.callback({
response_type: 'in_channel',
text: `Hey there ${msg.text}!`
}))
```
9 changes: 7 additions & 2 deletions src/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,12 @@ class Client {
message = Object.assign({ token: this.token, channel: this.channel }, message);

// convert json except when passing in a url
if (!endPoint.match(/^http/i)) message = qs.stringify(message);
if (!endPoint.match(/^http/i)) {
if (message.attachments) {
message.attachments = JSON.stringify(message.attachments).replace(/^'(.*)'$/, '$1');
}
message = qs.stringify(message);
}
return this.api.post(endPoint, message).then(this.getData);
}

Expand Down Expand Up @@ -209,4 +214,4 @@ class Client {
}


module.exports = Client;
module.exports = Client;
17 changes: 13 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,25 @@ class Slack extends EventEmitter {
* @param {Object} context - The Lambda context
* @param {Function} callback - The Lambda callback
*/
handler(event, context, callback) {
handler(event, context, callback) {
this.callbackFn = callback;
switch(event.method) {
case "GET": this.oauth(event, context, callback); break;
case "POST": this.event(event, context, callback); break;
}
}


/**
* Allow event handlers to use the callback early
*
* @param {Object} response A response object or string
*/
callback(response) {
if (this.callbackFn) this.callbackFn(null, JSON.stringify(response));
}


/**
* OAuth Lambda Handler
*
Expand Down Expand Up @@ -88,8 +99,6 @@ class Slack extends EventEmitter {
// Events API challenge
if (payload.challenge)
return callback(null, payload.challenge);
else
callback();

// Ignore Bot Messages
if (!this.ignoreBots || !(payload.event || payload).bot_id) {
Expand Down Expand Up @@ -129,4 +138,4 @@ class Slack extends EventEmitter {

}

module.exports = new Slack();
module.exports = new Slack();