[英]I keep getting this error in my Discord Bot
我是制作 Discord.js 機器人的新手,但我不斷收到此錯誤:機器人現在在線!
HIT
C:\Users\kerix\Desktop\MrMiner\bot\index.js:20
let commandMethod = commands.get(name);
^
ReferenceError: commands is not defined
at Client.<anonymous> (C:\Users\kerix\Desktop\MrMiner\bot\index.js:20:25)
at Client.emit (node:events:527:28)
at InteractionCreateAction.handle (C:\Users\kerix\Desktop\MrMiner\bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:74:12)
at Object.module.exports [as INTERACTION_CREATE] (C:\Users\kerix\Desktop\MrMiner\bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (C:\Users\kerix\Desktop\MrMiner\bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:351:31)
at WebSocketShard.onPacket (C:\Users\kerix\Desktop\MrMiner\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\kerix\Desktop\MrMiner\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\kerix\Desktop\MrMiner\bot\node_modules\ws\lib\event-target.js:199:18)
at WebSocket.emit (node:events:527:28)
at Receiver.receiverOnMessage (C:\Users\kerix\Desktop\MrMiner\bot\node_modules\ws\lib\websocket.js:1137:20)
我的代碼是:
const Discord = require("discord.js");
const { token } = require('./config.js');
const Bot = new Discord.Client({intents: [Discord.Intents.FLAGS.GUILD_MEMBERS, Discord.Intents.FLAGS.GUILDS]})
require("./slash-register")()
Bot.on('ready', () => {
console.log("The Bot Is Online Now!")
let commands = Bot.application.commands;
})
Bot.on('interactionCreate',async interaction => {
console.log("HIT")
if(!interaction.isCommand) return;
let name = interaction.commandName;
let options = interaction.options;
let commandMethod = commands.get(name);
if(!commandMethod) return;
await interaction.deferReply();
commandMethod(Bot, interaction)
})
Bot.login(token)
我該如何解決這個錯誤?
您在ready
處理程序中定義變量commands
,因此它只能在ready
處理程序中訪問。 在外部定義它以便能夠在interactionCreate
處理程序中訪問它:
let commands;
Bot.on('ready', () => {
console.log("The Bot Is Online Now!")
commands = Bot.application.commands;
})
Bot.on('interactionCreate',async interaction => {
console.log("HIT")
if(!interaction.isCommand()) return;
let name = interaction.commandName;
let options = interaction.options;
let commandMethod = commands.get(name);
if(!commandMethod) return;
await interaction.deferReply();
commandMethod(Bot, interaction)
})
Bot.login(token)
這應該可以解決您遇到的特定錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.