如何使用Discord Bot发送问候消息-NodeJS

时间:2019-04-02 09:30:55

标签: node.js intellij-idea discord discord.js

我正在尝试开发Discord机器人,当有人添加到服务器时,我希望它发送问候消息。 我收到此错误:

/perso-workspace/discordtest/index.js:31
guild.defaultChannel.send(`Bienvenue ${member.user} sur mon serveur Discord !  `).catch(console.error);
                         ^

TypeError: Cannot read property 'send' of undefined
    at Client.bot.on.member (/home/spoisson/Documents/perso-workspace/discordtest/index.js:31:26)
    at Client.emit (events.js:189:13)
    at Guild._addMember (/home/spoisson/Documents/perso-workspace/discordtest/node_modules/discord.js/src/structures/Guild.js:1192:19)
    at GuildMemberAddHandler.handle (/home/spoisson/Documents/perso-workspace/discordtest/node_modules/discord.js/src/client/websocket/packets/handlers/GuildMemberAdd.js:12:13)
    at WebSocketPacketManager.handle (/home/spoisson/Documents/perso-workspace/discordtest/node_modules/discord.js/src/client/websocket/packets/WebSocketPacketManager.js:103:65)
    at WebSocketConnection.onPacket (/home/spoisson/Documents/perso-workspace/discordtest/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:333:35)
    at WebSocketConnection.onMessage (/home/spoisson/Documents/perso-workspace/discordtest/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:296:17)
    at WebSocket.onMessage (/home/spoisson/Documents/perso-workspace/discordtest/node_modules/ws/lib/event-target.js:120:16)
    at WebSocket.emit (events.js:189:13)
    at Receiver._receiver.onmessage (/home/spoisson/Documents/perso-workspace/discordtest/node_modules/ws/lib/websocket.js:137:47)

这是我的代码:

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


bot.on('ready', function(){
    console.log('I am ready to learn !')
})

bot.on('message', function (message){
    if (message.content === '!ping') {
        message.channel.send('Pong !')
    }
})

bot.on("guildMemberAdd", member => {
    let guild = member.guild;
    console.log('Guild is ' + guild + ' and member is ' + member.user)
    guild.defaultChannel.send(`Bienvenue ${member.user} sur mon serveur Discord !  `).catch(console.error);
});

bot.login('i_set_my_token_here')

我已经在YouTube上或其他任何地方尝试过不同的教程,但我不了解与正在观看的人之间的区别。 第一个命令(!ping)运行良好。我设法为我的机器人设置了活动。

我发现defaultChannel已过时,但没有找到任何可以满足我需求的东西。

任何人都可以指导我解决此错误吗?

2 个答案:

答案 0 :(得分:3)

新的不和谐服务器不再具有默认频道,因此Guild#defaultChannel已弃用,并且对于较新的行业协会返回未定义。

如果您希望漫游器仅按名称查找频道,则可以使用:

guild.channels.find(channel => channel.name === 'general-chat');

您还可以遍历可能的通道名称列表以允许更多通道,或者可以进行配置以设置日志通道。

答案 1 :(得分:-1)

由于api的更改,.defaultChannel不再可用。但是,您可以指定名称或ID来选择所需的频道。

带有ID:

guild.channels.find(ch => ch.id === "channel id here".send(`Welcome ${member.user} on my Discord server !`).catch(console.error);

名称:

guild.channels.find(ch => ch.name === "channel name here").send("Welcome ${member.user} on my server Discord !").catch(console.error);