discord.js将消息发送到特定频道

问题描述 投票:0回答:3

我一直在环顾四周,似乎无法找到我用Typescript制作的不和谐机器人遇到的这个问题的答案。我将所有命令都放在单独的文件夹中,每个命令使用单独的文件。帮助保持事物井井有条。

我见过人们说client.channels.get(`channelID`).send(`Text`)

但是那给了我Object is possibly 'undefined'.Property 'send' does not exist on type 'Channel'.

我实际上是试图在有人运行重新启动命令的每个文本通道(从列表提供)中发送一条bot消息,因为无论出于何种原因,人们都会继续重新启动bot。如果有人需要使用它,我将它实现为一次有趣的事情,一次又一次地作为巨魔来实现。该机器人下线了3分钟,但我不希望有人向它发送垃圾邮件,并且该机器人几乎无法使用。

我正在使用client.channels.get(channels.channelnames[5]).send("This is a message.")Code I entered.Error message

javascript typescript discord.js channels
3个回答
0
投票

根据https://discord.js.org/#/docs/main/stable/class/Collection,似乎没有get方法。

尝试client.channels[channels.channelnames[5]].send("This is a message.")

换句话说,尝试用方括号替换.get。

编辑:抱歉,我有点急,我认为问题是类型转换,如果您知道它是文本通道,请尝试将Channel转换为TextChannel


0
投票

假设您的频道是文本频道,这应该可以工作。

client.on('ready',(e)=>{


    let channel_ids = ['123','456','789'];

    // loop through the list of channel ids.
    for(let i=0, l=channel_ids.length; i<l; i++){
        let channel_id = channel_ids[i];

        let this_channel = client.channels.get( channel_id );

        // if exists, and type in list send message
        if(this_channel && ['dm', 'group', 'text'].indexOf( this_channel.type ) != -1){
            this_channel.send('a cool message')
            .then(message => console.log(`Sent message: ${message.content}`))
            .catch(console.error);
        }

    }

});

0
投票

解决方案:

if(msgObject.member.guild.channels.find(channel => channel.name === channels.channelnames[5]) as Discord.TextChannel) {
    var txtchannel = msgObject.member.guild.channels.find(channel => channel.name === channels.channelnames[5]) as Discord.TextChannel
    txtchannel.send("This is a message in a channel. Don't know why you read this.")
}

所以我基本上是在正确的轨道上。只需要做as Discord.TextChannel,我想这就是Cynthia所说的将变量转换为TextChannel

的原因

此代码有效。感谢您的帮助!

© www.soinside.com 2019 - 2024. All rights reserved.