开发者问题收集

如何在 discord.js 中向特定频道发送消息?

2020-03-13
8216

阅读底部的编辑,更改整个问题。

是的,我知道以前有人问过这个问题。但是,我找不到有效且未被弃用的解决方案。这是我的代码中需要操作我尝试复制的特定功能的部分;

const Discord = require('discord.js');
const bot = new Discord.Client();
const client = bot

const token = 'NunyaBuisness';
const channel = '525723958239852735' // Not a real channel ID
const PREFIX = '.';

bot.on('message', msg=>{
    let args = msg.content.substring(PREFIX.length).split(" ");
    switch(args[0]){
        case 'process':
            if(args[1] === 'test'){
                var testGuild = new Discord.Guild(bot, 'serverID');
                var testTextChannel = new Discord.TextChannel(testGuild, channel);
                testTextChannel.send("Test");
            }
        break;
    }
})

机器人在消息上返回以下内容

.process test

B:\bot\node_modules\discord.js\src\structures\Guild.js:152
    this.large = Boolean('large' in data ? data.large : this.large);
                                 ^

TypeError: Cannot use 'in' operator to search for 'large' in serverID
    at Guild._patch (B:\bot\node_modules\discord.js\src\structures\Guild.js:152:34)
    at new Guild (B:\bot\node_modules\discord.js\src\structures\Guild.js:92:12)
    at Client.<anonymous> (B:\bot\index.js:101:33)
    at Client.emit (events.js:311:20)
    at MessageCreateAction.handle (B:\bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (B:\bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (B:\bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
    at WebSocketShard.onPacket (B:\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:435:22)
    at WebSocketShard.onMessage (B:\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
    at WebSocket.onMessage (B:\bot\node_modules\ws\lib\event-target.js:120:16)

感谢您的帮助!我真的很感激。几天来我一直在尝试使用文档自己解决这个问题,但 不断 失败。

编辑

我认为问题在于方法 CLIENT.channels.get('id') 实际上不存在。这真是太奇怪了,我正在查看 GitHub 看看是否缺少了什么。目前,我发现什么都没有丢失。这太奇怪了。 感谢您迄今为止的帮助。

1个回答

对于 discord v12 更改:

msg.guild.channels.get(myChannel)msg.guild.channels.cache.get(myChannel)

let myChannel = '123213123'

    bot.on('message', msg=>{
        let args = msg.content.substring(PREFIX.length).split(" ");
        switch(args[0]){
            case 'process':
                if(args[1] === 'test'){
                    let targetChannel = msg.guild.channels.get(myChannel)
                    if (targetChannel) targetChannel.send('sssss')
                }
            break;
        }
    })
Cipher
2020-03-13