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

如何用Autocode让Discord机器人每次触发命令时提取Google Sheet随机单元格内容

代码问题梳理

  • 原命令匹配规则仅匹配了无参数的纯指令,没有兼容带@用户的输入场景
  • description行错误调用了Google Sheets的写单元格方法,你不需要修改表格内容,直接从已经拉取到的词库数组随机取值即可
  • 缺少对指令发送人、被@用户的信息提取逻辑
  • 直接取database.distinct.values[0]只会固定返回第一个词条,没有实现随机效果

修复后完整代码

module.exports = async (event, context) => {
  // 匹配带参数的throw/throwing指令
  if (event.content.startsWith(`${process.env.prefix}throw`) || event.content.startsWith(`${process.env.prefix}throwing`)) {
    // 提取被@的用户,没有@的话返回提示
    const mentionedUsers = event.mentions || [];
    if (mentionedUsers.length === 0) {
      await lib.discord.channels['@0.1.1'].messages.create({
        channel_id: event.channel_id,
        content: "请@你要扔东西的目标用户哦"
      });
      return;
    }
    // 拉取throw表A列所有投掷物词条
    const database = await lib.googlesheets.query['@0.3.0'].distinct({
      range: `throw!A:A`,
      bounds: `FIRST_EMPTY_ROW`,
      where: [{}],
      field: `Throw`
    });
    const throwItems = database.distinct.values;
    // 随机选一个词条
    const randomItem = throwItems[Math.floor(Math.random() * throwItems.length)];
    // 获取指令发送人昵称/用户名,被@的第一个用户
    const sender = event.member?.nick || event.author.username;
    const target = `<@${mentionedUsers[0].id}>`;
    // 发送结果消息
    await lib.discord.channels['@0.1.1'].messages.create({
      channel_id: event.channel_id,
      content: ``,
      embed: {
        title: ` `,
        type: 'rich',
        color: 0xff7700,
        description: `${sender}向${target}扔了*${randomItem}*`
      }
    })
  }
}

注意事项

  • 请确保你的Google Sheet throw表A列的表头是Throw,和你field参数里的取值一致,否则会拉取不到内容
  • 如果不需要用embed,也可以直接把内容填到content字段,不用走embed配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:45:03