开发者问题收集

发布自定义欢迎信息的 Discord 机器人

2021-05-06
756

我希望我的机器人在“欢迎”文本频道中为每个新成员发布一条简单的欢迎消息。

我在这里和那里阅读了很多帖子,但仍然无法让它按预期工作

这是代码:

console.log('Beep Boop Beep'); //prints 'Beep Boop Beep'

require('dotenv').config(); //load the dotenv node pachage and call a config() func to load thea values from .env

const {Client, MessageEmbed} = require('discord.js');

//EDIT: const client = new Client()
const client = new Client({ ws: { intents: [
    'GUILDS',
    'GUILD_MESSAGES',
    'GUILD_PRESENCES',
    'GUILD_MEMBERS'
] } });

const embed = new MessageEmbed()
    .setTitle("DM thing")
    .setColor(0xFF0000)
    .setDescription("Add describtion here")

client.login(process.env.BOTTOKEN); 

module.exports = {client, embed};

function readyDiscord() {
    console.log('readyDiscord func executed. Discord is ready.'); 
}

client.on('ready', readyDiscord);

const commandHandler = require('./commands'); 

client.on('message', commandHandler);

//EDIT: 'guildMembersAdd'
client.on('guildMemberAdd', async member => { 
    console.log(member)

    const message = `Hey, <@${member.id}>! Welcome. DM me if anytime you want.`
    
    //EDIT: const channel = member.guild.channels.cache.get(WELCOME_CHANNEL_ID)
    const channel = await 

//EDIT: pocess.env
member.guild.channels.resolve(process.env.WELCOME_CHANNEL_ID);
    channel.send(message)
})

PRESENCE INTENT 和 SERVER MEMBERS INTENT 已启用。 每次我尝试添加测试帐户时,机器人都会吐出这些错误:

错误:

(base) admin@MacBook-Pro-11 discord_binder % node bot.js
Beep Boop Beep
readyDiscord func executed. Discord is ready.
GuildMember {
  guild: <ref *1> Guild {
    members: GuildMemberManager {
      cacheType: [class Collection extends Collection],
      cache: [Collection [Map]],
      guild: [Circular *1]
    },
    channels: GuildChannelManager {
      cacheType: [class Collection extends Collection],
      cache: [Collection [Map]],
      guild: [Circular *1]
    },
    roles: RoleManager {
      cacheType: [class Collection extends Collection],
      cache: [Collection [Map]],
      guild: [Circular *1]
    },
    presences: PresenceManager {
      cacheType: [class Collection extends Collection],
      cache: [Collection [Map]]
    },
    voiceStates: VoiceStateManager {
      cacheType: [class Collection extends Collection],
      cache: Collection(0) [Map] {},
      guild: [Circular *1]
    },
    deleted: false,
    available: true,
    id: '779767191012638721',
    shardID: 0,
    name: 'testovoe_nazvaniye',
    icon: '0b54ebc0b473b6571b8157d207392af0',
    splash: null,
    discoverySplash: null,
    region: 'russia',
    memberCount: 5,
    large: false,
    features: [],
    applicationID: null,
    afkTimeout: 300,
    afkChannelID: null,
    systemChannelID: '779768178296750080',
    embedEnabled: undefined,
    premiumTier: 0,
    premiumSubscriptionCount: 0,
    verificationLevel: 'NONE',
    explicitContentFilter: 'DISABLED',
    mfaLevel: 0,
    joinedTimestamp: 1620485504837,
    defaultMessageNotifications: 'ALL',
    systemChannelFlags: SystemChannelFlags { bitfield: 0 },
    maximumMembers: 100000,
    maximumPresences: null,
    approximateMemberCount: null,
    approximatePresenceCount: null,
    vanityURLCode: null,
    vanityURLUses: null,
    description: null,
    banner: null,
    rulesChannelID: null,
    publicUpdatesChannelID: null,
    preferredLocale: 'en-US',
    ownerID: '660217837016842260',
    emojis: GuildEmojiManager {
      cacheType: [class Collection extends Collection],
      cache: Collection(0) [Map] {},
      guild: [Circular *1]
    }
  },
  joinedTimestamp: 1620486298424,
  lastMessageID: null,
  lastMessageChannelID: null,
  premiumSinceTimestamp: 0,
  deleted: false,
  nickname: null,
  _roles: [],
  user: User {
    id: '462330953734291457',
    system: null,
    locale: null,
    flags: UserFlags { bitfield: 0 },
    username: 'Test Account',
    bot: false,
    discriminator: '4317',
    avatar: '343601cdd6da4d03329351def9ffbffb',
    lastMessageID: null,
    lastMessageChannelID: null
  }
}
(node:2459) UnhandledPromiseRejectionWarning: ReferenceError: pocess is not defined
    at Client.<anonymous> (/Users/admin/Desktop/projects/re_bot/discord_binder/bot.js:43:57)
    at Client.emit (events.js:315:20)
    at Object.module.exports [as GUILD_MEMBER_ADD] (/Users/admin/Desktop/projects/re_bot/discord_binder/node_modules/discord.js/src/client/websocket/handlers/GUILD_MEMBER_ADD.js:16:14)
    at WebSocketManager.handlePacket (/Users/admin/Desktop/projects/re_bot/discord_binder/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (/Users/admin/Desktop/projects/re_bot/discord_binder/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (/Users/admin/Desktop/projects/re_bot/discord_binder/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
    at WebSocket.onMessage (/Users/admin/Desktop/projects/re_bot/discord_binder/node_modules/ws/lib/event-target.js:132:16)
    at WebSocket.emit (events.js:315:20)
    at Receiver.receiverOnMessage (/Users/admin/Desktop/projects/re_bot/discord_binder/node_modules/ws/lib/websocket.js:825:20)
    at Receiver.emit (events.js:315:20)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2459) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:2459) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

编辑:

代码的整体思路是正确的,但有很多拼写错误,您可以在 //EDIT: 注释中看到。所以也许你想去检查你的代码是否有相同的拼写错误

3个回答

您能告诉我们 console.log(member) 中记录到控制台的内容吗?

我最好的猜测是 WELCOME_CHANNEL_ID 是错误的,因此返回了一个虚假频道。

如果不是这种情况,那么也许机器人没有缓存频道,因此请使用以下命令:

const channel = await member.guild.channels.resolve(WELCOME_CHANNEL_ID);

如果它不起作用,请告诉我们。

Juan Pablo
2021-05-06

仅在开发者门户中启用 Intents 并不意味着您正在使用 Intents
您必须告诉您的客户端要使用哪些 Intents。

因此,您需要执行

const client = new Client({ ws: { intents: [
    'GUILDS',
    'GUILD_MESSAGES',
    'GUILD_PRESENCES',
    'GUILD_MEMBERS'
] } });

而不是

const client = new Client();

这将告诉客户端加载 GUILD_MEMBERS Intent,以便您可以使用 guildMemberAdd

此后,此代码应该可以正常工作。如果有错误请评论。

编辑:在您的代码中,您将 guildMemberAdd 拼写错误,而 guildMembersAdd 您也应该修复它。

资源:

Akio
2021-05-07

我看到您的代码中有一条注释,指出 WELCOME_CNAHHEL_ID 是一个环境变量。就像您对 BOTTOKEN 所做的那样,您可能希望在该变量前加上 process.env ,因此它应如下所示:

process.env.WELCOME_CHANNEL_ID

您的原始代码中也有一个拼写错误: CNAHHEL 而不是 CHANNEL 。请确保 .env 文件中的名称与您在代码中使用的名称匹配。

Pedro Fracassi
2021-05-07