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

如何将Twitch骰子命令的多段输出合并为单条消息?

Twitch !roll指令合并单条消息发送解决方案

要实现单条消息发送,核心是将所有要展示的内容拼接成一个完整字符串,仅调用一次client.say,而不是分多次触发发送。以下是修改后的完整代码,同时优化了条件判断逻辑:

if (message == '!roll') {
    const num = rollDice();
    let resultText = '';

    // 根据骰子点数匹配对应剧情
    if (num === 1) {
        resultText = 'You shit yourself and die of dehydration... Wow.';
    } else if (num > 1 && num <= 10) {
        resultText = 'The Goblin destroys you. You died.';
    } else if (num > 10 && num < 20) {
        resultText = 'You fought the goblin bravely and are victorious. You Win!';
    } else if (num === 20) {
        resultText = 'The goblin immediately falls in love with your beauty and you get married! Good Ending! Pog ';
    }

    // 拼接所有内容为单条消息,用换行保持可读性
    const fullMessage = `@${userstate.username} A goblin appears before you, ready to attack. Roll a d20.\nYou rolled ${num}\n${resultText}`;
    client.say(channel, fullMessage);
}

// 掷20面骰子函数
function rollDice() {
    const sides = 20;
    return Math.floor(Math.random() * sides) + 1;
}

关键修改说明:

  • 先执行掷骰子逻辑,避免重复调用生成不同点数
  • 用if-else if链式判断替代独立if,逻辑更严谨且高效
  • 把剧情文本存入变量后再拼接,代码结构更清晰,便于后续扩展
  • 用\n换行分割内容,Twitch聊天支持换行展示,既保证单条消息发送,又保留原有的分段可读性
  • 修正了原代码中1<num && num<11这类边界模糊的判断,改为num>1 && num<=10,避免逻辑漏洞

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 02:20:09