You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js开发Twitch聊天机器人:!命令无响应问题求助

解决Twitch聊天机器人!命令无响应问题

你的代码里有两个核心错误导致机器人无法响应命令:

  1. 频道配置键名错误
    tmi.js的配置对象中,频道列表的正确键名是channels(复数形式),但你写的是channel(单数)。这个错误会导致机器人无法成功加入指定的Twitch频道,自然接收不到聊天消息,也就不会响应命令。

  2. 连接配置拼写错误
    connection对象里的reconnct拼写错误,应为reconnect(少了字母e),这可能影响机器人的重连机制。

另外还有两个优化点:

  • 消息事件参数命名修正:message事件的第二个参数是用户标签对象,规范命名为tags而非user,后续使用tags.username才能正确获取发送者的用户名。
  • 消息匹配容错处理:直接用全等于匹配!ping过于严格,建议先去除消息首尾空格,避免用户输入带空格时无法触发命令。

修正后的完整代码:

const tmi = require('tmi.js'),
    { channel, username, password } = require('./settings.json');

const options = {
    options: { debug: true },
    connection: {
        reconnect: true, // 修正拼写错误
        secure: true
    },
    identity: {
        username,
        password
    },
    channels: [channel] // 修正为复数channels
};

const client = new tmi.Client(options);
client.connect().catch(console.error);

client.on('connected', () => {
    client.say(channel, `${username} joined the chat`);
});

client.on('message', (channel, tags, message, self) => {
    if (self) return;

    const trimmedMessage = message.trim();
    if (trimmedMessage === '!ping') {
        client.say(channel, `@${tags.username}, pong`);
    }
});

验证步骤:

  • 确保settings.json里的channel值是带#前缀的频道名(比如#your_channel_name)
  • 运行修正后的代码,查看控制台的debug日志,确认机器人成功加入频道
  • 在Twitch聊天中发送!ping,机器人应该会回复@你的用户名, pong

内容的提问来源于stack exchange,提问作者Abaddon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 14:01:30