mishk0 / slack-bot-api Goto Github PK
View Code? Open in Web Editor NEW:rocket: Simple way to control your Slack Bot
License: MIT License
:rocket: Simple way to control your Slack Bot
License: MIT License
Currently if an object is passed in params, e.g.:
{
attachments: {
pretext: "some text",
fields: ...
}
}
It just doesn't work. The reason is that the object needs to be stringified. This module should run JSON.stringify on such (or all non-string) objects automatically, given that all param values must necessarily be strings.
As of right now, I just am taking a message and checking for the indexOf('username'). I would much rather prefer to catch messages sent to that username by @username instead of just username. Am I just looking over the ability to do this, is this possible?
Thanks
I am attempting to write a basic Slack bot the sends new users a spiel when they join the Slack group.
My basic implementation is something like this, plus the boilerplate:
MyBot.prototype._isTeamJoin = function(message) {
return message.type === 'team_join';
};
MyBot.prototype._onMessage = function(message) {
if(this._isTeamJoin(message)) {
var username = message.user.name;
this._greetNewUser(username);
}
};
MyBot.prototype._greetNewUser = function(username) {
var greeting = 'Welcome!';
this.postMessageToUser(username, greeting, { as_user: true });
};
This message is never received by the new user. If you instead hard code it to send the message to a user that existed when the bot was fired up, it works without a hitch. Why is this? I have tried using the .getUsers()
function and setting this.users
to the updated data, but that doesn't seem to work either. What is the correct way to go about this?
Do you have any idea how to enable link unfurling as described here?:
I tried setting params
to this:
var params = {
unfurl_links: true
};
but it didn't have any effect.
I am running a bot that needs to listen user messages, and it works fine in the first days, but for some reason after a few days the bot stop to listening new messages and I need to restart everything.
Anyone is having this problem? How to avoid that? I am thinking about restart every 24h but this is kind of a workaround on the problem...
https://github.com/mishk0/slack-bot-api/blob/master/index.js#L42
fails quite often for me.
https://app.getsentry.com/share/issue/36303035302e313030373835383634/
any ideas?
The attachments feature (https://api.slack.com/docs/attachments) is not working
Okay so it's great what this API allows you to do, but one of the main useful things that doesn't seem to be included is actually having a way to convert channel and user IDs back to actual names...? Using DS935739 as a name is not particularly helpful? Is there a way of actually fixing this so I can get users names when they send a message?
Currently, when an invalid token is used the login()
method fails, which calls assert(false, data.error)
. Because this assert lives in an asynchronous callback function, it is not possible to wrap the constructor in a try/catch block and catch the assert error.
I suggest instead of calling assert(false)
creating a new event called invalid_auth
that is called when the Slack rtm.start
call fails.
Hi,
When slack REST API returns a string as the body, like "You are sending too many requests. Please relax." (btw. looks like it's enough to send 3-5 messages in a row to get this error...) i get a JSON parse error from here
Thanks for this lib!
I'm using your library in a project and one of my users is having an issue. When the code attempts to send a message to Slack it gets an SSL cert issuer error, I cannot reproduce this on other machines.
/usr/local/lib/node_modules/horus/node_modules/vow/lib/vow.js:105
throw e;
^
Error: Error: unable to get local issuer certificate
at Bot.<anonymous> (/usr/local/lib/node_modules/horus/node_modules/slackbots/index.js:42:28)
at Array.<anonymous> (/usr/local/lib/node_modules/horus/node_modules/vow/lib/vow.js:713:56)
at Immediate.callFns (/usr/local/lib/node_modules/horus/node_modules/vow/lib/vow.js:24:35)
at runCallback (timers.js:637:20)
at tryOnImmediate (timers.js:610:5)
at processImmediate [as _immediateCallback] (timers.js:582:5)
This error is occurring on OSX with Node v0.12.0 and v7.1.0. The code looks like:
slack.on('start', function() {
slack.postMessageToGroup(channel, message, null, function(data){ /** ... */ });
});
When bot is already in a channel/group and the channel/group get renamed, the bot message never get delivered.
Steps to reproduce:
Also I'm not 100% sure but I think the same happen if the bot is added to the channel/group after run node.js process.
Are You planning to support posting files?
Currently, you can only post to a user's DM (IM) channel, but not to their slackbot channel. Add functionality that enables posting to another user's slackbot channel.
Fixed in PR #44
Hi, I keep on getting errors (not syntax errors, but the "function/variable/object undefined" type ones) without any stack trace, file name or line numbers, can you help me understanding if there's anything I need to change to enable normal error reporting?
this is an example
[TypeError: Cannot read property 'name' of undefined]
Thanks!
Morena
Great library! Really useful. Was wondering if you knew of any Slack bots that use this library and that are open source? Would love to take a look at some source code to learn more on how to expand this library.
Cheers!
It would be nice if there would be a function to update the last send message.
So if I get an user request the bot send first "Fetching xy" and than change it to "Fetched xy".
Is this already planned?
I was trying to send this event via the RTM API but without any luck.
Bot.prototype.botTyping = function(id, params) {
params = extend({
type: 'user_typing',
channel: id,
user: this.self.id
}, params || {});
return this._api('chat.postMessage', params);
};
@mishk0 can you see an easy way to add this to this package?
Thanks
Hi! I added a listener for the 'close' event in order to handle disconnections. I'm seeing the message in the logs but the bot is offline now. What I'm doing wrong? Thanks!
// handle disconnections
bot.on('close', function(data){
console.log("Connection closed... Reconnecting.")
bot.login();
});
it would be nice to have these features...
I must do for example: bot.ws.close()
now
data
in the following code is printing out undefined and the bot does not send a new message in Slack. Heres the code:
var self = this;
self.postMessageToChannel('bottest', 'hi there', {as_user: true}).always(function(data) {
console.log(' cb = ' + data);
});
Any ideas why? Not sure how to go about debugging it as no errors seem to be thrown.
EDIT: So the 'bottest' channel was private, i made a public channel and made the bot respond there and it seems to work. Does this only work on public channels? Is some sort of specific configuration needed to run on private channels?
What are my options if socket is closed for some reason? I have to have an option to reconnect somehow.
I have a use case for getUserByEmail, some of the other node base slackbot apps have this method, but I like yours better and decided to add my own method and have a fork for the time being. I add lodash so I didn't want to send a PR as it seems your intent is to avoid the overhead.
https://github.com/mikemcguire/slack-bot-api
This is really helpful where an employee of an organisation might be uniquely identified in multiple services by their email rather than their name. For example if someone were to @mention someone on github and you wanted your slackbot to message the same person in your slackteam with the same email.
Hey, I've been using slackbots a bit lately, it's a solid module and I like your coding style. I'd never seen vow before, but I've found it a pleasure to use after bluebird & friends..
Anyhow, I've been using a simple listen
method, I haven't bothered to put it in a PR, because I'm not sure if you'd be interested in incorporating it into your module.. but if it matches your vision for slackbots just let me know and I'll submit a PR, but if this doesn't float your boat that's no drama - I just thought I'd ask.
I think it ticks a few boxes in that it allows you to create listeners which are clean and readable.
The listen method I'm using looks something like this..
bot.listen = function(mask, handler) {
bot.on('message', function(event) {
let match
if (!event.user || event.user == bot.userId) {
return
}
match = _.every(mask, (value, property) => {
if (_.isRegExp(value)) {
return event[property].match(value)
}
return event[property] === value
})
if (!match) {
return
}
handler(event)
})
}
Which allows you to add listeners like so:
bot.listen(
{
type: 'message',
text: /:star:/
},
function(message) {
...
}
)
or ...
bot.listen(
{
type: 'reaction_added',
reaction: 'star'
},
function(event) {
...
}
)
From the readme:
bot.postMessageToUser('user1', 'hi').fail(function(data) { //data = { ok: false, error: 'user_not_found' } })
if you change user1 to a user that exists, the message does get sent
if user1 does not exist, the anonymous function provided to fail never gets called, the failure simply happens silently.
not sure if this is a change on Slack's end that has broken this, or if it's an issue with the slackbots
library, but something likely needs to be updated either way.
I want to write ping/pong code.
bot.on('message', function(data) {
if(data.type !== "message" || data.text !== "ping") return;
bot.postMessageToChannel(data.channel, 'pong'); // but, data.channel is channelID
});
can i do it?
getChannels, getUsers and getGroups always return cached data meaning that said data will, at some point, become outdated.
Solutions:
after postingmessage to user its coming back to my server with as message type and again it posted same message to slack any help to avoid loop
Error: SyntaxError: Unexpected token Y in JSON at position 0
I see this error and I believe it's coming from Bot.prototype.login
which invokes this._api('rtm.start')
. Seems the response body isn't being properly parsed.
At this time, slackbots
will not work if node.js is installed under a copporate proxy. All the outgoing http requests sent by slackbots
will return with the time-out
error. I think it will be nice if slackbots
support this.
I've been using slackbots to (successfully) establish connections to applications/bots for which I have the bot token. However, I just discovered that if the bot is disabled by someone on the team, this causes an error to be thrown by slackbots, and I don't appear to be able to catch it gracefully. It just crashes.
Here is a screenshot of the error message;
I tried to just try/catch the var bot = new Slackbot() part of the code, but that's doesn't work. The error gets thrown anyway and the code crashes.
Is there some clean way of handling this that I'm not seeing? I don't mind finding out that the account is inactive and then just not connecting to it, but I can't figure out how to do that without crashing the code.
The .getUser() .getUserId() functions don't seems work. The first doesn't do anything and the second cannot be found.
Slackbots uses v1.0.1 of ws (websocket library), which has an issue with node versions 6.3.0 and above - websockets/ws#778
ws is currently on v2.0.0, but upgrading to v1.1.1 or above should fix the issue
Hey @mishk0,
Seems that this module doesn't support all the endpoints available on the API api.slack.com/methods.
What about have some methods defined by a configuration file (often a yaml) that defines all the methods from the API with the parameters and have other "custom" methods implemented directly in JavaScript. Like getGroupById, getChannelById, etc...
We could apart of support all the methods from the API, explain how this slack-api-client add extra value of the raw slack API.
Thanks :D
How does the api show errors here and what is the suggested way to handle them?
Hi !
npm install slackbots :
npm WARN EJSONPARSE Failed to parse json
npm WARN EJSONPARSE Unexpected token 'l' at 20:4
npm WARN EJSONPARSE "license": "MIT"
npm WARN EJSONPARSE ^
npm WARN EPACKAGEJSON slacknode No description
npm WARN EPACKAGEJSON slacknode No repository field.
npm WARN EPACKAGEJSON slacknode No README data
npm WARN EPACKAGEJSON slacknode No license field.
npm cache clean do nothing
The method postMessageToChannel
accepts channel name but the events like message
provide only the channel id. It would be great if instead of:
bot.on('message', function ({ channel }) {
bot.getChannelById(channel)
.then(({ name }) => bot.postMessageToChannel(name, 'hi!'))
})
we could simply do:
bot.on('message', function ({ channel }) {
bot.postMessageToChannelId(channel, 'hi!') // new method that receives the channel id!
})
I would be glad to contribute with a PR!
How do we send a message in a channel to a user? A message only the user can see. Is this possible?
When calling super() from my child i get following error:
E:\Downloads\Git\js\aru-slacky.js\node_modules\vow\lib\vow.js:104
throw e;
^
Error: [Slack Bot Error] undefined
at assert (E:\Downloads\Git\js\aru-slacky.js\node_modules\slackbots\libs\utils.js:15:15)
at E:\Downloads\Git\js\aru-slacky.js\node_modules\slackbots\index.js:42:9
at Array.<anonymous> (E:\Downloads\Git\js\aru-slacky.js\node_modules\vow\lib\vow.js:712:56)
at Immediate.callFns [as _onImmediate] (E:\Downloads\Git\js\aru-slacky.js\node_modules\vow\lib\vow.js:23:35)
at tryOnImmediate (timers.js:543:15)
at processImmediate [as _immediateCallback] (timers.js:523:5)
Not sure if Bot can be extended like that but here is my code:
class Aru extends Bot {
constructor(settings = {}) {
var name = settings.name || "Aru";
var token;
if (settings.token) {
token = settings.token;
}
else if (process.env.ARU_SLACK_TOKEN) {
token = process.env.ARU_SLACK_TOKEN;
}
else {
throw new Error("No slack API token available");
}
super({
token: token,
name: name
});
this.master = settings.master || "douman";
}
/**
* Run bot.
*/
launch() {
this.on('start', function() {
bot.postMessageToUser(this.master, 'Good day, master!');
});
}
}
It throws when i call on
Right now I do the following :
bot.on('message', function(data) {
if(data.type === 'message' && data.bot_id === undefined){
bot.getChatId('myusername').then(function(id){
if(id === data.channel){
console.log('Message was sent in private message');
}
}
}
This solution isn't flexible as there isn't a way to get the chatId
from a userId
, only from a userName
.
It would be great if one could get and send messages to the private channels that a bot is a member.
bot.postMessageToChannel('orders', message, {mrkdwn: true});
This doesnt seem to work
Hey there!
I noticed that your repo has a vulnerability introduced via the ws
dependency. You can see information about it here. Also, you could see the test report for this repo.
If you'd like to fix this vulnerability, Snyk lets you generate a pull request that recommends the best upgrade path - there's a link to fix this vulnerability on the test report.
Cheers,
Karen
I invited my bot to a private channel, but no messages are delivered there despite the bot already on the member list. I'm not sure if that is a but in this module or in Slack, but debugging it turned out to be tricky since no error is reported. Here are three variant calls and:
// Variant 1:
try {
bot.postMessageToChannel('background-tasks', 'Hello private channel!', params)
} catch (e) {
console.error('no exception thrown :-/', e)
}
// Variant 2:
bot.postMessageToChannel('background-tasks', 'Hello private channel!', params).then(function (status) {
console.log('why is .then() called even though message failed to send?', status) // status == undefined
}).fail(function (err) {
console.error('no error + why is this called .fail()? Should catch with .catch() :-/', err)
})
// Variant 3:
bot.postMessageToChannel('background-tasks', 'Hello private channel!', params, function (err) {
console.error('FINALLY we get an error', err) // we see "AssertionError: channel not found"
})
Where postMessageToUser(name, message [, params, callback]) (return: promise)
- posts a direct message by user name I need to implement somekind like postMessageToUserId(user_id, message [, params, callback]) (return: promise)
- posts a direct message by user id
But postMessage(id, text, params)
sent as slackbot, not as current bot. Can we have it implemented?
Cannot install it on node 5, due to [email protected] only runs on node v0.12.
I'm a bit new to slack bots, and it seems that I need a better example than what's in the readme. Running this exact code in Nodejs simply starts and immediately stops. It doesn't seem to do anything at all, definitely is not listening for anything.
I am unable to post attachments due to a presumed bug in constructing nested query params.
For example, given the following code:
bot.postMessageToChannel('bottest', 'yo!', {
icon_emoji: ':cat:',
attachments: [{
text: 'some text',
fallback: 'some fallback'
}]
});
A request is performed agains the following path -- note the empty attachments=
:
chat.postMessage?text=yo!&channel=123&username=some_username&icon_emoji=%3Acat%3A&attachments=&token=XXXXXX
I believe this is due to a bug within the querystring
NPM module's stringify
method.
Please correct me if I am mistaken in my expectations -- I did notice that the following appears to work.
bot.postMessageToChannel('bottest', 'yo!', {
icon_emoji: ':cat:',
attachments: JSON.stringify([{
text: 'some text',
fallback: 'some fallback'
}])
});
Thanks!
When answering to users or channels, usually from name comes with #channelName or @userName.
On PostTo function, when searching name on the channel, groups and user list, variable name should be cleaned before, removing @ or # on the received name, voiding unnecessary assert.
Something more elegant of this:
postTo(name, text, params, cb) {
return Vow.all([this.getChannels(), this.getUsers(), this.getGroups()]).then(function(data) {
name = name.replace("#", "");
name = name.replace("@", "");
var all = [].concat(data[0].channels, data[1].members, data[2].groups);
var result = _.find(all, {name: name});
console.assert(result, name, 'wrong name');
if (result['is_channel']) {
return this.postMessageToChannel(name, text, params, cb);
} else if (result['is_group']) {
return this.postMessageToGroup(name, text, params, cb);
} else {
return this.postMessageToUser(name, text, params, cb);
}
}.bind(this));
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.