【问题标题】:Sending message to specific channel, not working向特定频道发送消息,不起作用
【发布时间】:2020-01-28 08:13:21
【问题描述】:

在特定频道上发送机器人消息时遇到问题。我只是想让机器人在激活时向#general 发送一条消息,让每个人都知道它再次工作。

在 bot.on 函数中,我尝试了经典的 client.channels.get().send(),但我收到的错误消息表明它认为客户端未定义。 (它说“无法读取未定义的属性'通道'”)

bot.on('ready', client => {
    console.log("MACsim online")
    client.channels.get('#general').send("@here");
})

机器人立即崩溃,说:Cannot read property 'channels' of undefined

【问题讨论】:

    标签: node.js discord.js


    【解决方案1】:

    ready 事件没有传递任何client 参数。 要按名称获取频道,请使用collection.find()

    client.channels.find(channel => channel.name == "channel name here");
    

    要通过 ID 获取频道,您只需执行 collection.get("ID"),因为频道是通过其 ID 映射的。

    client.channels.get("channel_id");
    

    这是我为您制作的示例:

    const Discord = require("discord.js");
    const Client = new Discord.Client();
    
    Client.on("ready", () => {
       let Channel = Client.channels.find(channel => channel.name == "my_channel");
       Channel.send("The bot is ready!");
    });
    
    Client.login("TOKEN");
    

    【讨论】:

      【解决方案2】:

      您需要通过 ID 获取公会/服务器,然后通过 ID 获取频道,因此您的代码将类似于:

      const discordjs = require("discord.js");
      const client = new discordjs.Client();
      
      bot.on('ready', client => {
      console.log("MACsim online")
          client.guilds.get("1836402401348").channels.get('199993777289').send("@here");
      })
      

      编辑:添加客户端调用

      【讨论】:

      • @NeonEviscerator 你怎么称呼你的不和谐客户?
      • 谢谢,这确实解决了我的问题,我忘记了我将 Doscord clint 分配给了“bot”而不是“client”。我将所有客户端调用更改为 bot,问题现已解决,感谢您的帮助。
      • @NeonEviscerator Np,您能否将我的答案检查为“已接受”答案?
      • 是的,很抱歉没有早点这样做。我是 SO 新手,没有意识到这是你应该做的事情。
      【解决方案3】:

      ready 事件没有传递参数。要获得机器人的客户端,只需使用您在创建客户端时分配的变量即可。
      从您的代码来看,它看起来像 bot 变量,您在其中执行了 const bot = new Discord.Client();
      从那里,使用bot(这是机器人的客户端),您可以访问channels 属性!

      【讨论】:

        猜你喜欢
        • 2021-09-30
        • 2021-02-28
        • 2020-07-02
        • 2021-08-21
        • 2020-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多