Search code examples
node.jsslack-apislack

Slack Bot Replying to his own message in Node js


I am trying to make a slack bot in nodejs that replys the user based on their input. But As far now the bot keeps replying to his own messages

this is the code for my bot

let Bot = require('slackbots');

// create a bot
let settings = {
    token: 'xoxb-10584202949',
name: 'BotHelp'};

let bot = new Bot(settings);
bot.on('start', function() {

  bot.postMessageToChannel('general', 'At your service');

    });

bot.on('message',function (data) {
  console.log(data);
    if (data.username != "BotHelp" && data.subtype != 'bot_message'){
     bot.postMessageToChannel('general', 'Yoooo');
    }
});

The Console log for data Prints

{ type: 'hello' }
{ text: 'At your service',
  username: 'BotHelp',
  bot_id: 'B336WGVSM',
  type: 'message',
  subtype: 'bot_message',
  team: 'T2ZAW44P3',
  user_team: 'T2ZAW44P3',
  channel: 'C303W2D4M',
  ts: '1479877794.000266' }
{ type: 'presence_change',
  presence: 'active',
  user: 'U33QS0VEF' }

So why my validation is failing to check that the message has been sent from bot itself or not?

Thank you for your time


Solution

  • I had the same issue. The message event in slackbots fires for every event ie, user_typing, message_marked, desktop_notification. All events can be found here. Now what i did to ensure my bot didn't send a message after receiving its own was:

    bot.on('message',function (data) {
       if (data.user != "Uxxxxxx" && data.message === 'message'){
           bot.postMessageToChannel('general', 'Yoooo');
       }
    

    the data.user gives a unique id, you can get this by console.log(data) and find your user id.

    Also, if you want to specify which message you want to listen to, say direct message. channel id inside data will start with a D. For private channels, the channel id starts with G

    Hope this helps. I know there is much more to do here but this is the basic. And you can grow on this. I know I will be trying to :D