Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

node.js - Discord bot not responding to commands (Javascript)

I'm doing my first discord bot from a github repository. It connects to discord, and logs into the server, but won't respond to !help commands etc. It's not my code so I'm not super familiar with it, but the code for the commands seems to be fine.

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
!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);
})
};


I get this error message in my terminal console

(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.

any help would be much appreciated as I'm on a bit of a time crunch here. I'm not at all familiar with Javascript so I'm sorry if this is a stupid question!

///EDIT/// here's the entire code.

'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
!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 ?
 1/6`)
      .setColor(0xFF0000)
  ).then(message => {
    message.react('??')
    games.push(new Game(message, command.author))
    command.delete()
  })
}
question from:https://stackoverflow.com/questions/65680599/discord-bot-not-responding-to-commands-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
})

it should be:

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

Hope this helped.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...