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

修复Twitch聊天机器人JS代码的三分支逻辑错误

问题分析

你的代码逻辑存在结构缺陷:当前第三个分支(两者都不存在)的判断被包裹在if (match && match[1])代码块内部,但能进入这个块的前提是match[1]必然存在,导致else if (match[1])永远为真,第三个分支永远无法触发。

修复后的代码
client.on("chat", async (channel, userstate, message, self) => {
  console.log(`Received message: ${message} from user ${userstate.username}`);
  if (self) return;
  if (userstate.username === "funtoon") {
    const catchRegex = /!catch (.*)/;
    const match = message.match(catchRegex);
    
    // 分支3:消息无!catch指令或指令后无内容
    if (!match || !match[1]) {
      console.log("Neither was present");
    } else {
      const response = await axios.get(
        "https://grynsoft.com/spos-app/?c=Vod_Kanakas&u=Vod_Kanakas"
      );
      const $ = cheerio.load(response.data);

      const textRegex = new RegExp(
        `<b style="color: yellow;">${match[1]}</b>`
      );
      const textMatch = $("html").html().match(textRegex);
      
      // 分支1:页面存在带黄色样式的目标文本
      if (textMatch) {
        console.log("Both style and match[1] are present");
        // 按需求此处可留空不执行操作
      } 
      // 分支2:仅消息存在目标文本,页面无对应黄样式标签
      else {
        console.log("Only match[1] present");
      }
    }
  }
});
逻辑说明
  • 分支3:当消息不匹配!catch (.*),或匹配后捕获组为空时直接触发,输出对应日志。
  • 分支1:确认消息存在有效指令后,检查页面是否有带黄色样式的<b>标签包裹目标文本,存在则输出对应日志(可根据需求删除日志,仅保留空逻辑)。
  • 分支2:页面不存在符合要求的标签时触发,输出对应日志。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 08:20:43