【问题标题】:Specifying which channel to send chat from a discord bot (say-channel command)指定从不和谐机器人发送聊天的频道(say-channel 命令)
【发布时间】:2019-02-04 20:57:00
【问题描述】:

这是GLaDOS 机器人、Connor RK800 机器人和TypicalBot 中的一项功能。

命令通常如下所示:

!say #general heck

文本将通过机器人出现在该频道中。

如果可能,我想将此添加到我自己的机器人中!

我有一个 say-delete 命令的基本代码。我要添加什么,要删除什么?

      if (command === "say") {
  const sayMessage = args.join(" ");

  message.delete().catch(O_o => {
    // Catch error
  });
  message.channel.send(sayMessage);
}

谢谢!我真的很感激。

【问题讨论】:

  • 您使用了标签“discord.js”和“discord.io”。您现在使用哪个库? :)
  • 我正在使用 discord.js。抱歉,如果标签令人困惑——我是这个网站的新手!我会相应地修复它。

标签: node.js bots discord discord.js


【解决方案1】:
// making the say command
const sayCommand = `${prefix}say`
// say command
if (message.content.toLowerCase().startsWith(`${sayCommand}`)) {
        // declaring args variable
        const args = message.content.slice(sayCommand.length).split(/ +/);
        // delcaring sayMessage that clears the say command from the say message
        let sayMessage = args.join(` `);
        // deletes the command message
        message.delete();
        // bot sends the contents of the command without the say command
        message.channel.send(sayMessage)
    }

这对我很有效

【讨论】:

    【解决方案2】:

    首先,您需要将本例中用于定义参数的代码更改为 const channel = args.shift();,这将返回 args[] 数组中的第一项。

    然后您可以使用message.guild.channels[channel].send(sayMessage);(我认为)识别用户想要发送消息的频道。

    总而言之,您的代码将是:

    if(command === "say") {
    
       const channel = args.shift();
       const sayMessage = args.join(" ");
    
       message.delete().catch(O_o=>{});  
    
       message.guild.channels[channel].send(sayMessage);
    
    }
    

    由于我现在无法检查,我不确定这是否可行,但值得一试!如果你愿意,我可以在我能够测试的时候为你测试。

    编辑: 我测试并修复了代码,希望我写的 cmets 足够解释。

    const channel = args.shift().slice(2,-1); // this is due to how channel mentions work in discord (they are sent to clients as <#462650628376625169>, this cuts off the first <# and the finishing >)
    const sayMessage = args.join(` `);
    
    message.delete(); // you may want to add a catch() here, i didn't because my bot requires permissions to be added to a server
    client.channels.get(channel).send(sayMessage); // client here may need to be replaced with bot, or app, or whatever you're using - client.channels returns a collection, which we use get() to find an item in
    

    为了清楚起见,此代码必须放在您的 if (command === "say") 块内。

    【讨论】:

    • 我测试过了,还是不行。起初,我以为是因为 message-delete 行,但后来还是不行。但是非常感谢你,yogsoy!如果可以的话,如果你能测试一下,那将是绝对棒的。再次,非常感谢。
    • 更新了代码,您可能想再次尝试测试它。请注意,如果您通过键入 # 和带有弹出选择器的频道名称来提及它,它现在才有效 - 仅输入“#channel”是行不通的。
    • 现在功能齐全了。谢谢!! :)
    猜你喜欢
    • 2021-08-26
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 2022-11-11
    • 2018-09-18
    • 2020-10-25
    • 2021-08-13
    • 2020-08-25
    相关资源
    最近更新 更多