Discord bot 不响应命令(Javascript)

时间:2021-01-12 08:49:04

标签: javascript node.js discord discord.js bots

我正在从 github 存储库做我的第一个不和谐机器人。它连接到 discord 并登录到服务器,但不会响应 !help 命令等。 这不是我的代码,所以我不是很熟悉,但命令的代码似乎没问题。

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('?')
    games.push(new Game(message, command.author))
    command.delete()
  })
}

1 个答案:

答案 0 :(得分:1)

您不应该使用 command,而应该使用 msg

例如,你写了 command.channel.send("heck yeah I'm here"); 相反,它应该是 msg.channel.send("heck yeah I'm here");

而不是:

client.on('message', command => {
//code here
})

应该是:

client.on('message', msg => {
//code here
})

希望这有帮助。