提问者:小点点

正在向特定通道发送消息,不工作


在特定信道上发送bot消息时遇到困难。我很简单地想让机器人在激活时向#General发送一条消息,让每个人都知道它又开始工作了。

在bot.on函数中,我尝试了经典的client.channels.get()。send(),但是我得到的错误消息显示它认为client是未定义的。(它说“无法读取未定义的属性'channels'”)

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

bot立即崩溃,说:无法读取未定义的属性“通道


共3个答案

匿名用户

您需要按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");
})

编辑:添加的客户端调用

匿名用户

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");

匿名用户

Ready事件不传递参数。要获得bot的客户端,只需使用您在创建客户端时分配的变量。
从您的代码来看,它类似于bot变量,您在其中执行了const bot=new discord.client();
从那里,使用bot(它是bot的客户端),您可以访问channels属性!