是否可以向我的机器人所在的每个公会发送消息?

时间:2020-09-19 08:24:07

标签: javascript node.js discord discord.js

我已经尝试了所有教程,但没有用,这是我当前的代码:

bot.on('message', message => {
    if (message.content.startsWith(`${prefix}globalannounce`)) {
        var msg = message.content.split(" ").slice(1).join(" ")
        var guildList = bot.guilds.array;
        try {
            let messageToSend = new Discord.MessageEmbed()
                .setTitle("Hello, you don't see me messaging in your server often...")
                .setDescription(`I have just flown in to tell you that my developers have something to say: \n ${msg}`)
            guildList.array.forEach(channel => {
                if (channel.type === 'text') channel.send(messageToSend).catch(console.error)
            });
        } catch (err) {
            console.log(err);
        }
    }
});    

它不起作用,错误是TypeError: Cannot read property 'array' of undefined

2 个答案:

答案 0 :(得分:0)

如果您使用的是discord.js v12

您遇到错误TypeError: Cannot read property 'array' of undefined。这意味着bot.guilds等于undefined。所以问题出在这里:

        var guildList = bot.guilds.array;

您必须将其替换为

var guildList = bot.guilds.cache

因此您的整个代码应如下所示:

bot.on('message', message => {
    if (message.content.startsWith(`${prefix}globalannounce`)) {
        var msg = message.content.split(" ").slice(1).join(" ")
        var guildList = bot.guilds.cache
        try {
            let messageToSend = new Discord.MessageEmbed()
                .setTitle("Hello, you don't see me messaging in your server often...")
                .setDescription(`I have just flown in to tell you that my developers have something to say: \n ${msg}`)
            guildList.forEach(guild =>{
guild.channels.cache.find(c => c.type === 'text').send(messageToSend)
            });
        } catch (err) {
            console.log(err);
        }
    }
});    

答案 1 :(得分:0)

animals使用Managers,因此您必须通过cache属性来获取行会列表。有关更多信息,请参见this post

此外,discord.js v12.x将遍历集合中所有 GuildList.forEach() 中的函数,而不是所有通道。您可以使用Channel.type属性和Collection.find()来找到第一个可用的文本通道。

Guilds