尝试向多个不和谐服务器发送消息
Posted
技术标签:
【中文标题】尝试向多个不和谐服务器发送消息【英文标题】:Trying to send a message to multiple discord servers 【发布时间】:2020-08-20 19:20:09 【问题描述】:这是我的代码。当用户键入命令 !sendall 时,我正在尝试向多个服务器发送消息。例如,当用户键入 !sendall Hello 时,它将向多个不和谐服务器发送“Hello”。感谢您的帮助!
执行此操作时,我收到此错误
(node:14424) UnhandledPromiseRejectionWarning: ReferenceError: guild is not defined
at Client.<anonymous> (C:\Users\16034\Desktop\Bot Monitors\bot.js:52:56)
at Client.emit (events.js:310:20)
at MessageCreateAction.handle (C:\Users\16034\Desktop\Bot Monitors\node_modules\discord.js\src\client\actions\MessageC
// Main
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
var guildList = ["707366229446492208", "704552256007307364"];
// Bootup
client.on("ready", () =>
console.log(`Bot has started, with $client.users.size users, in $client.channels.size channels of $client.guilds.size guilds.`);
client.user.setActivity(`Serving $client.guilds.size servers`);
);
// Guild Logs
client.on("guildCreate", guild =>
console.log(`New guild joined: $guild.name (id: $guild.id). This guild has $guild.memberCount members!`);
client.user.setActivity(`Serving $client.guilds.size servers`);
);
client.on("guildDelete", guild =>
console.log(`I have been removed from: $guild.name (id: $guild.id)`);
client.user.setActivity(`Serving $client.guilds.size servers`);
);
// Required
client.on("message", async message =>
if(message.author.bot) return;
if(message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
// Sendall
if(command === "sendall")
try
guildList.forEach(guild => guild.defaultChannel.send("messageToSend"));
catch (err)
console.log("Could not send message to " + guild.name);
);
client.login(config.token);
【问题讨论】:
【参考方案1】:您不能只使用 ID 向公会发送消息。您需要先使用该 ID 找到公会。
guildList.forEach(guildID => client.guilds.get(guildID).defaultChannel.send('hello'));
【讨论】:
【参考方案2】:guildList
是一个字符串数组(ID),而不是公会本身。您需要先获取公会对象。
另外,您不能像这样使用try
和catch
,因为可能抛出的东西(guild.defaultChannel.send("messageToSend")
)在forEach
函数中,因此不会捕获错误。您收到的错误是因为您试图在 catch
块中引用 guild
。 guild
只存在于forEach
函数中。
试试这个:
if(command === "sendall")
guildList
.map(id => client.guilds.cache.get(id))
.forEach(guild => guild.defaultChannel
.send("messageToSend")
.catch(err => console.log("Could not send message to " + guild.name))
);
【讨论】:
它给了我这个错误,(node:36688) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined @AndrewMarshalldefaultChannel
在 v11 和 removed in v12 中已弃用。这可能就是为什么defaultChannel
是undefined
。以上是关于尝试向多个不和谐服务器发送消息的主要内容,如果未能解决你的问题,请参考以下文章