【问题标题】:How to make Slack bot dynamically reply at the same channel using node.js如何使用 node.js 使 Slack 机器人在同一频道动态回复
【发布时间】:2019-03-26 15:37:09
【问题描述】:

我想让我的 slackbot 应用程序在用户提到的频道上回答,而不是在代码中手动写入频道名称。

-示例-
问题:我邀请我的机器人进入频道#hello#hi。我在频道#hello 提到我的机器人写@mybot hi there,但它只回复频道#hi,这是我在我的代码中手动写下的。
我希望我的机器人自动查找消息来自哪个频道,并在用户提到的同一频道上回复。
不像我写的代码bot.postMessageToChannel('everyone', `Chuck Norris: ${joke}`,params);

这是我使用的模块的链接和我的代码
https://github.com/mishk0/slack-bot-api

const SlackBot = require('slackbots');
const axios = require('axios');

const bot = new SlackBot({
    token : "",
    name : ""
});

// Start Handler
bot.on('start', () =>{
    const params = {
        icon_emoji: ':)'
    };

    bot.postMessageToChannel('everyone', 'Feeling tired??? Have some fun with @Joker!'
    , params);
});

// Error Handler
bot.on('error', (err) => console.log(err));

//Message Handler
bot.on('message', (data) => {
    if(data.type !== 'message'){
        return;
    }

    console.log(data);
    handleMessage(data.text);
});


// Responding to Data
function handleMessage(message){
    if(message.includes('chucknorris')){
        chuckJoke();
    }
    else if(message.includes(' yomama')){
        yoMamaJoke();
    }
    else if(message.includes(' random')){
        randomJoke();
    }
    else if(message.includes(' help')){
        runHelp();
    }
}


// Tell a Chuck Norris Joke
function chuckJoke(){
    axios.get('http://api.icndb.com/jokes/random/')
    .then(res =>{
        const joke = res.data.value.joke;

        const params = {
            icon_emoji: ':laughing:'
        };

        bot.postMessageToChannel('everyone', `Chuck Norris: ${joke}`,params);
    });
}

【问题讨论】:

  • 您使用哪种与 Slack 交互的方法? RTM、事件、传出 Webhook?请将该部分添加到您问题中的代码示例中
  • 刚刚添加(https://github.com/mishk0/slack-bot-api)。感谢您的反馈:)

标签: node.js slack-api


【解决方案1】:

here 你会在message 上找到它返回给你channel id 的数据对象

那么 你可以在你使用过的api中使用postMessage()

postMessage(id, text, params) (return: promise) - 向频道发布消息 |集团 |用户 ID,

bot.on('message', (data) => {

    bot.postMessage(data.channel, 'Feeling tired??? Have some fun with @Joker!'
    , params);
    console.log(data);
    handleMessage(data.text);
});

【讨论】:

  • 修复了一些错误,例如将参数放入该代码中它不起作用:(它肯定会使用console.log()将频道ID带到终端,但它在应用程序中不起作用
  • 你能把支票去掉if
  • 哦,我想我可以掌握它。非常感谢它真的给了我很好的提示:)
  • 并非如此。我认为这是我的问题,因为我看到相同的代码 data.channel 其他人使用它似乎工作得很好。不知道为什么:(
猜你喜欢
  • 2016-11-07
  • 2017-03-18
  • 1970-01-01
  • 1970-01-01
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多