Discord bot不响应命令(Javascript)
我正在从github存储库中执行我的第一个discord bot。它连接到discord,并登录到服务器,但不会响应!帮助命令等。 这不是我的代码,所以我对它不是非常熟悉,但是命令的代码似乎很好Discord bot不响应命令(Javascript),javascript,node.js,discord,discord.js,bots,Javascript,Node.js,Discord,Discord.js,Bots,我正在从github存储库中执行我的第一个discord bot。它连接到discord,并登录到服务器,但不会响应!帮助命令等。 这不是我的代码,所以我对它不是非常熟悉,但是命令的代码似乎很好 if (command.content === '!create' && !game) { createGame(command) } else if (command.content === '!start' && game && !game.sta
if (command.content === '!create' && !game) {
createGame(command)
} else if (command.content === '!start' && game && !game.started) {
command.delete()
game.start()
} else if (command.content === '!help') {
command.channel.send(`!create: Create a new game\n!start: Start the game previously created`)
}if (message.content === 'restartthebot') {
if (message.author.id !== 'Owners ID') return;
message.channel.send('Restarted.').then(() => {
process.exit(1);
})
};
我在终端控制台中收到此错误消息
(node:2611) UnhandledPromiseRejectionWarning: ReferenceError: command is not defined
at Client.<anonymous> (/Applications/werewolf-discord-master 2/src/index.js:63:3)
at Client.emit (events.js:327:22)
at WebSocketManager.triggerClientReady (/Applications/werewolf-discord-master 2/src/node_modules/discord.js/src/client/websocket/WebSocketManager.js:431:17)
at WebSocketManager.checkShardsReady (/Applications/werewolf-discord-master 2/src/node_modules/discord.js/src/client/websocket/WebSocketManager.js:415:10)
at WebSocketShard.<anonymous> (/Applications/werewolf-discord-master 2/src/node_modules/discord.js/src/client/websocket/WebSocketManager.js:197:14)
at WebSocketShard.emit (events.js:315:20)
at WebSocketShard.checkReady (/Applications/werewolf-discord-master 2/src/node_modules/discord.js/src/client/websocket/WebSocketShard.js:475:12)
at WebSocketShard.onPacket (/Applications/werewolf-discord-master 2/src/node_modules/discord.js/src/client/websocket/WebSocketShard.js:447:16)
at WebSocketShard.onMessage (/Applications/werewolf-discord-master 2/src/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/Applications/werewolf-discord-master 2/src/node_modules/ws/lib/event-target.js:132:16)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2611) 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:2611) [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.
任何帮助都将不胜感激,因为我在这里有点时间紧张。我对Javascript一点也不熟悉,所以如果这是一个愚蠢的问题,我很抱歉
///编辑///
这是全部代码
'use strict'
const config = require("./config.json")
const fs = require('fs')
const readline = require('readline')
const Discord = require('discord.js')
const client = new Discord.Client()
const pkg = require('../package.json')
client.on('ready', () => {console.log('ready')});
client.login(config.token)
client.on("message", function(message) {
});
// Initialize the bot
getToken().then((token) => {
console.log('Successfully get token. Connecting...')
client.login(token)
})
/**
* Read the Discord Bot Token from config.json or ask it to the user and save it.
* @returns string
*/
async function getToken () {
// Create an empty structure
let config = {}
// Try to read the token field from the config file
try {
config = require('./config.json')
if (config.token) { return Promise.resolve(config.token) }
console.log('The field "token" is empty or doesn\'t exist.')
} catch (err) {
console.warn("The file config.json doen't exist. Creating one ...")
}
// Ask the token to the user
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
config.token = await new Promise(resolve => {
rl.question('What is your Discord Token ? ', (answer) => {
rl.close()
resolve(answer)
})
})
// Save the token in the config file
fs.writeFileSync('./src/config.json', JSON.stringify(config))
return Promise.resolve(config.token)
}
// ==== Bot events ==== //
let games = []
let generalChannel = {}
// Display a message when the bot comes online
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag} dude!`);
command.channel.send("heck yeah I'm here");
});
client.on('message', command => {
// Allow commands only in general
if (generalChannel.id !== command.channel.id) { return }
// Verify is the author own a game. If he do, he can't create a new one.
// The owner is the only who can start a game
let game = games.find(g => g.owner.id === command.author.id)
if (command.content === '!create' && !game) {
createGame(command)
} else if (command.content === '!start' && game && !game.started) {
command.delete()
game.start()
} else if (command.content === '!help') {
command.channel.send(`!create: Create a new game\n!start: Start the game previously created`)
}if (message.content === 'restartthebot') {
if (message.author.id !== 'Owners ID') return;
message.channel.send('Restarted.').then(() => {
process.exit(1);
})
};
// TODO: Remove this command in prod
if (command.content === '!clear') {
command.channel.fetchMessages().then(messages => {
messages.forEach(m => {
m.delete()
})
})
}
})
client.on('messageReactionAdd', (msgReaction, user) => {
if (user.id === client.user.id) { return } // If it's the bot itself, ignore
// Find the game the message is a attached to
// Only on game creation message
// TODO: Check the reaction type
let game = games.find(g => g.message.id === msgReaction.message.id)
if (game && user.id !== game.owner.id) {
game.addPlayer(user)
}
})
client.on('messageReactionRemove', (msgReaction, user) => {
// Find the game the message is a attached to
let game = games.find(g => g.message.id === msgReaction.message.id)
if (game) {
game.removePlayer(user)
}
})
// ==== Bot functions ==== //
const Game = require('./Game')
/**
* Create a Game object in the games array and send a creation game message
* @param {Discord.Message} command
*/
function createGame (command) {
command.channel.send(
new Discord.RichEmbed()
.setTitle('Create a game')
.setDescription(`Want to join ?\n 1/6`)
.setColor(0xFF0000)
).then(message => {
message.react('You're not supposed to use command
, but instead msg
For example, you wrote command.channel.send("heck yeah I'm here");
Instead, it should be msg.channel.send("heck yeah I'm here");
And instead of:
client.on('message', command => {
//code here
})
“严格使用”
const config=require./config.json
常量fs=需要“fs”
const readline=需要“readline”
const Discord=require'Discord.js'
const client=new Discord.client
const pkg=require'../package.json'
client.on'ready',=>{console.log'ready'};
client.loginconfig.token
client.onmessage,functionmessage{
};
//初始化bot
getToken.thentoken=>{
console.log“已成功获取令牌。正在连接…”
client.logintoken
}
/**
*从config.json中读取Discord Bot令牌,或向用户请求并保存它。
*@返回字符串
*/
异步函数getToken{
//创建一个空结构
让config={}
//尝试从配置文件中读取令牌字段
试一试{
config=require./config.json'
如果config.token{return Promise.resolveconfig.token}
console.log“字段标记为空或不存在。”
}犯错误{
console.Warn文件config.json不存在。正在创建一个。。。
}
//向用户询问令牌
const rl=readline.createInterface{input:process.stdin,output:process.stdout}
config.token=等待新的PromiseSolve=>{
rl.问题“你的不和谐标志是什么?”回答=>{
关闭
解答
}
}
//将令牌保存在配置文件中
fs.writeFileSync'/src/config.json',json.stringifyconfig
返回Promise.resolveconfig.token
}
//===机器人程序事件===//
让游戏=[]
设generalChannel={}
//当bot联机时显示消息
client.onready,=>{
log`以${client.user.tag}dude!的身份登录;
command.channel.sendheck是的,我在这里;
};
client.on'message',command=>{
//仅允许一般命令
如果generalChannel.id!==command.channel.id{return}
//验证是作者拥有一个游戏。如果他拥有,他就不能创建一个新游戏。
//老板是唯一可以开始比赛的人
让game=games.findg=>g.owner.id==command.author.id
如果command.content=='!create'&&!游戏{
createGamecommand
}如果command.content=='!start'&&game&&!game.start{
command.delete
游戏开始
}如果command.content=='!help'{
command.channel.send`!创建:创建新游戏\n!开始:启动以前创建的游戏`
}如果message.content=='重新启动bot'{
如果message.author.id!=='Owners id'返回;
message.channel.send“重新启动”。然后=>{
process.exit1;
}
};
//TODO:在prod中删除此命令
如果command.content=='!清除'{
command.channel.fetchMessages.thenmessages=>{
messages.forEachm=>{
m、 删除
}
}
}
}
client.on'messageReactionAdd',msgReaction,user=>{
如果user.id==client.user.id{return}//如果是bot本身,则忽略
//查找邮件所附加到的游戏
//仅在游戏创建消息上
//TODO:检查反应类型
让game=games.findg=>g.message.id==msgReaction.message.id
如果game&&user.id!==game.owner.id{
game.addPlayeruser
}
}
client.on'messageReactionRemove',msgReaction,user=>{
//查找邮件所附加到的游戏
让game=games.findg=>g.message.id==msgReaction.message.id
如果游戏{
game.removePlayeruser
}
}
//===机器人功能===//
const Game=需要“/游戏”
/**
*在游戏数组中创建游戏对象并发送创建游戏消息
*@param{Discord.Message}命令
*/
函数createGame命令{
command.channel.send
新的不和谐
.setTitle“创建游戏”
.setDescription`要加入吗?\n 1/6`
.setColor0xFF0000
.thenmessage=>{
message.react'您不应该使用命令,而应该使用msg
例如,您编写了command.channel.sendheck是的,我在这里;
相反,它应该是msg.channel.sendheck是的,我在这里
而不是:
client.on('message', msg => {
//code here
})
应该是:
希望这能有所帮助。请尽量避免使用可能被视为冒犯性的语言。我尝试过,但收到了一条非常类似的错误消息:没有定义command,而是没有定义msgdefined@Jackson这很奇怪,你使用的是什么版本的Discord.js?我的终端告诉我v14.15.4最有可能是node.js,而不是Discord.js。在终端中,键入npm view discord.js version。@Jackson有许多类似于此的编码指南:。在查看机器人并对其进行编码之前,了解Javascript的基础知识是至关重要的。
我个人会先快速了解一下该语言的基础知识!快乐编码