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

时间:2021-05-06 23:36:38

标签: javascript discord discord.js

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

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

代码如下:

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 个答案:

答案 0 :(得分:1)

您能否让我们知道从 console.log(member) 记录到控制台的内容?

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

如果不是这种情况,那么机器人可能没有缓存通道,所以使用这个:

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

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

答案 1 :(得分:1)

我看到您的代码中有一条注释说 WELCOME_CNAHHEL_ID 是一个环境变量。就像你对 BOTTOKEN 所做的一样,你可能想用 process.env 作为变量的前缀,所以它应该是这样的:

process.env.WELCOME_CHANNEL_ID

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

答案 2 :(得分:1)

仅在 Developer Portal 中启用 Intent 并不意味着您正在使用 Intent
您必须告诉您的客户要使用哪些意图。

所以,而不是

const client = new Client();

你需要做的

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

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

此代码在此之后应该可以工作。如有错误请评论。

编辑:在您的代码中,您将 guildMemberAdd 拼错了 guildMembersAdd,您也应该解决这个问题。

资源: