向特定频道发送消息,不起作用

Posted

技术标签:

【中文标题】向特定频道发送消息,不起作用【英文标题】: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

【问题讨论】:

【参考方案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 属性!

【讨论】:

以上是关于向特定频道发送消息,不起作用的主要内容,如果未能解决你的问题,请参考以下文章

为啥我的频道消息发送代码不起作用?

Discord react_add 在私信频道中不起作用

如何使用不和谐机器人将消息发送到特定频道?

为啥通过 Apple Watch 向 iPhone 发送消息时 print() 不起作用?

当有人加入或离开其语音频道时,让机器人向文本频道发送消息

向 FCM 服务器发送推送通知不起作用