我的Discord.js机器人正在运行(在线并在控制台中显示),但它不会响应命令 [英] My Discord.js bot is running (online and shows in console) but it won't respond to commands

查看:233
本文介绍了我的Discord.js机器人正在运行(在线并在控制台中显示),但它不会响应命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,有一天,我使用TeamViewer连接到我的RPi3,并告诉它重新启动。完成后,我连接到pi,启动了bot,看起来好像正常启动了。

So, one day I was using TeamViewer to connect to my RPi3 and told it to reboot. As soon as it finished, I connected to the pi, started the bot, and it looked like it was starting up properly.

当我去discord发送命令时,该漫游器没有响应。机器人仍然在运行。

When I went to send a command on discord, the bot didn't respond. The bot is still running though.

我尝试更改一些代码,但没有任何改变。

I tried changing some of the code, but nothing changed.

这里代码:

// Load up the discord.js library
const Discord = require("discord.js");

// This is your client. Some people call it `bot`, some people call it `self`, 
// some might call it `cootchie`. Either way, when you see `client.something`, or `bot.something`,
// this is what we're refering to. Your client.
const client = new Discord.Client();

// Here we load the config.json file that contains our token and our prefix values. 
const config = require("./config.json");
// config.token contains the bot's token
// config.prefix contains the message prefix.

const version = ("v2.8")

client.on("ready", () => {
  // This event will run if the bot starts, and logs in, successfully.
  console.log(`I have awoken with ${client.users.size} users, in ${client.channels.size} channels of ${client.guilds.size} servers! :)`); 
  // Example of changing the bot's playing game to something useful. `client.user` is what the
  // docs refer to as the "ClientUser".
  client.user.setActivity(`~help | Running ${version}`);
  console.log(`Running Version: ${version}`)
});



client.on("guildCreate", guild => {
  // This event triggers when the bot joins a guild.
  console.log(`New guild joined: ${guild.name} (id: ${guild.id}). This guild has ${guild.memberCount} members!`);
});

client.on("guildDelete", guild => {
  // this event triggers when the bot is removed from a guild.
  console.log(`I have been removed from: ${guild.name} (id: ${guild.id})`);
});



client.on("message", async message => {
  // This event will run on every single message received, from any channel or DM.

  // It's good practice to ignore other bots. This also makes your bot ignore itself
  // and not get into a spam loop (we call that "botception").
  if(message.author.bot) return

  // Also good practice to ignore any message that does not start with our prefix, 
  // which is set in the configuration file.
  if(message.content.indexOf(config.prefix) !== 0) return

  // Here we separate our "command" name, and our "arguments" for the command. 
  // e.g. if we have the message "+say Is this the real life?" , we'll get the following:
  // command = say
  // args = ["Is", "this", "the", "real", "life?"]
  const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
  const command = args.shift().toLowerCase();

  // Let's go with a few common example commands! Feel free to delete or change those.

  if (message.channel instanceof Discord.DMChannel)
      message.channel.send("``Beep boop! Sorry, I can't respond to direct messages, but you can join the AKAS Gamer's Discord group here: https://discord.gg/QkjQNAr``");
      return


  if(command === "ping") {
    // Calculates ping between sending a message and editing it, giving a nice round-trip latency.
    // The second ping is an average latency between the bot and the websocket server (one-way, not round-trip)
    const m = await message.channel.send("Ping?");
    m.edit(`Pong! Latency is ${m.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(client.ping)}ms`);
    message.delete().catch(O_o=>{});
        return
  }

  if(command === "say") {
    // makes the bot say something and delete the message. As an example, it's open to anyone to use. 
    // To get the "message" itself we join the `args` back into a string with spaces: 
    const sayMessage = args.join(" ");
    // Then we delete the command message (sneaky, right?). The catch just ignores the error with a cute smiley thing.
    message.delete().catch(O_o=>{}); 
    // And we get the bot to say the thing: 
    message.channel.send(sayMessage);
  }

  if(command === "kick") {
    // This command must be limited to mods and admins. In this example we just hardcode the role names.
    // Please read on Array.some() to understand this bit: 
    // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some?
    if(!message.member.roles.some(r=>["Owner", "AKAS Admins", "AKAS Moders"].includes(r.name)) )
      return message.reply("Sorry, you don't have permissions to use this!");

    // Let's first check if we have a member and if we can kick them!
    // message.mentions.members is a collection of people that have been mentioned, as GuildMembers.
    // We can also support getting the member by ID, which would be args[0]
    let member = message.mentions.members.first() || message.guild.members.get(args[0]);
    if(!member)
      return message.reply("Please mention a valid member of this server");
    if(!member.kickable) 
      return message.reply("I cannot kick this user! Do they have a higher role? Do I have kick permissions?");

    // slice(1) removes the first part, which here should be the user mention or ID
    // join(' ') takes all the various parts to make it a single string.
    let reason = args.slice(1).join(' ');
    if(!reason) reason = "No reason provided";

    // Now, time for a swift kick in the nuts!
    await member.kick(reason)
      .catch(error => message.reply(`Sorry ${message.author} I couldn't kick because of : ${error}`));
    message.reply(`${member.user.tag} has been kicked by ${message.author.tag} because: ${reason}`);
    message.delete().catch(O_o=>{});

  }

  if(command === "ban") {
    // Most of this command is identical to kick, except that here we'll only let admins do it.
    // In the real world mods could ban too, but this is just an example, right? ;)
    if(!message.member.roles.some(r=>["AKAS Admins", "AKAS Moders", "Owner"].includes(r.name)) )
      return message.reply("Sorry, you don't have permissions to use this!");

    let member = message.mentions.members.first();
    if(!member)
      return message.reply("Please mention a valid member of this server");
    if(!member.bannable) 
      return message.reply("I cannot ban this user! Do they have a higher role? Do I have ban permissions?");

    let reason = args.slice(1).join(' ');
    if(!reason) reason = "No reason provided";

    await member.ban(reason)
      .catch(error => message.reply(`Sorry ${message.author} I couldn't ban because of : ${error}`));
    message.reply(`${member.user.tag} has been banned by ${message.author.tag} because: ${reason}`);
    message.delete().catch(O_o=>{});
  }

  if(command === "clear") {
    // This command removes all messages from all users in the channel, up to 100.

    // get the delete count, as an actual number.
    const deleteCount = parseInt(args[0], 10);

    // Ooooh nice, combined conditions. <3
    if(!deleteCount || deleteCount < 2 || deleteCount > 100)
      return message.reply("Please provide a number between 2 and 100 for the number of messages to delete");

    // So we get our messages, and delete them. Simple enough, right?
    const fetched = await message.channel.fetchMessages({limit: deleteCount});
    message.channel.bulkDelete(fetched)
      .catch(error => message.reply(`Couldn't delete messages because of: ${error}`));
    message.channel.send(`Successfully deleted ${deleteCount} messages!`)
    message.delete().catch(O_o=>{});    
    return
  }


  if(command === "reboot") {
            console.clear();
               client.destroy()
               client.login(config.token);
             message.channel.send("===REBOOT IN PROGRESS===");
             message.delete().catch(O_o=>{});
         return;
        }


  if(command === "test") {
             message.channel.send("Test Successfully Sent! :)");
             message.delete().catch(O_o=>{});
         return;
        }

  if(command === "kill") {
             message.delete().catch(O_o=>{});
             client.destroy()
         return;
        }


  if(command === "ip") {
             message.channel.send("AKASGaming's Modded Server Current IP is: __**0.tcp.eu.ngrok.io:####**__")
             message.delete().catch(O_o=>{});
         return;
        }

  if(command === "test2") {
             message.channel.send("lol :) ")
             message.delete().catch(O_o=>{});
         return;
        }

  if(command === "botstats") {
             message.channel.send(`This bot is currently running on a RPi3! (I'm now High-Speed and Portable!) (${version})`)
             message.delete().catch(O_o=>{});
         return;
        }

  if (command === "8ball") {
    message.channel.send(doMagic8BallVoodoo())
    return;
  }

  if (command === "flip") {
    message.channel.send(coinToss())
    message.delete().catch(O_o=>{});
    return;
  }

  if (command === "avatar") {
    message.reply(message.author.avatarURL);
    message.delete().catch(O_o=>{});
    return;
  }

  if (command === "help") {
    message.reply('**Chech your DMs!**');
    const embed = new Discord.RichEmbed()
              .setTitle("You Requested HELP! Here are your commands!")
              .setColor(0x00AE86)
              .setTimestamp()
              .addField('**Main Commands**', 'Here are your main commands')
              .addField('~help', 'Brings you this box!')
              .addField('~flip', 'Flips a coin')
              .addField('~8ball <Question>', 'Works just like a normal 8 Ball!')
              .addField('~avatar', 'Shows a larger version of your Discord profile picture')
              .addField('~botstats', 'Shows info about bot')
              .addField('~clear <number between 1-100>', 'Allows you to delete previous messages')
              .addField('~ping', 'Shows how fast your messages travel to the bot!')
              .addField('~mcserver <Server IP>', 'Shows stats on IP address')
              .addField('~mcskin <Minecraft Username>', 'Shows the skin of the username given')
              .addField('~roll', 'Rolls a dice')
              .addField('~joke', 'Tells you a joke')
              .addField('**Music Commands**', 'Music commands soon to come!')

                message.author.send({embed});
    return;
  }

  if (command === "mcserver") {
            let serverip = message.content.split(' ').splice(1).join(' ');
            let serverip_fromfield = serverip.substring(0,serverip.indexOf(":"));
            let serverport_fromfield = serverip.split(':')[1];
            if (!serverip) {

                message.channel.send(message.author + " | No IP entered. :x:");

            } else {

                if (!serverip.includes(":")) {
                    serverip_final = serverip;
                } else {
                    serverip_final = serverip_fromfield;
                }

                if (!serverport_fromfield) {
                    var serverport_final = "25565";
                } else {
                    var serverport_final = serverport_fromfield;
                }

    const embed = new Discord.RichEmbed()
              .setTitle("Minecraft Server Finder")
              .setColor(0x00AE86)
              .setImage("https://mc.myminecraftserver.com/" + "server/" + serverip_final + "/full/text")
              .setTimestamp()
              .addField("Server",
                serverip)

                message.channel.send({embed});

  }
}
  if (command === "mcskin") {
            let serverip = message.content.split(' ').splice(1).join(' ');
            let serverip_fromfield = serverip.substring(0,serverip.indexOf(":"));
            let serverport_fromfield = serverip.split(':')[1];
            if (!serverip) {

                message.channel.send(message.author + " | No Username entered. :x:");

            } else {

                if (!serverip.includes(":")) {
                    serverip_final = serverip;
                } else {
                    serverip_final = serverip_fromfield;
                }

                if (!serverport_fromfield) {
                    var serverport_final = "25565";
                } else {
                    var serverport_final = serverport_fromfield;
                }

                const embed = new Discord.RichEmbed()
              .setTitle("Minecraft Skin Finder")
              .setColor(0x00AE86)
              .setImage("https://minotar.net/armor/body/" + serverip_final + "/100.png")
              .setTimestamp()
              .addField("Player Skin",
                serverip)

              message.channel.send({embed});

            }
  }

  if (command === 'youtube') {
    message.send('Click here to subscribe to AKAS Gaming! => https://www.youtube.com/channel/UCrBICTn98ANnXU64DCRBqjQ?sub_confirmation=1');
  return;
  }

  if (command === 'joke') {
     message.reply(knock());
  return;
  }




});

const prefix = require("./config.json")

client.login(config.token).catch(console.error);
client.on('ready', () => {
  console.log('Commands Now Loaded!');
});


//Profanity Filter

client.on('message', message => {
  if(config.FILTER_LIST.some(word => message.content.toLowerCase().includes(word))){
    message.delete()
    message.reply('Please watch your language!')
  }})

client.on('ready', () => {
  console.log('Now Online, ready to filter profanity!');
});





//Knock Knock

var jokes = [
    { name: 'Dozen', answer: 'anybody want to let me in?' },
    { name: 'Avenue', answer: 'knocked on this door before?' },
    { name: 'Ice Cream', answer: 'if you don\'t let me in!' },
    { name: 'Adore', answer: 'is between us. Open up!' },
    { name: 'Lettuce', answer: 'in. Its cold out here!' },
    { name: 'Bed', answer: 'you can not guess who I am.' },
    { name: 'Al', answer: 'give you a kiss if you open the door.' },
    { name: 'Olive', answer: 'you!' },
    { name: 'Abby', answer: 'birthday to you!' },
    { name: 'Rufus', answer: 'the most important part of your house.' },
    { name: 'Cheese', answer: 'a cute girl.' },
    { name: 'Wanda', answer: 'hang out with me right now?' },
    { name: 'Ho-ho.', answer: 'You know, your Santa impression could use a little work.' },
    { name: 'Mary and Abbey.', answer: 'Mary Christmas and Abbey New Year!' },
    { name: 'Carmen', answer: 'let me in already!' },
    { name: 'Ya', answer: 'I’m excited to see you too!' },
    { name: 'Scold', answer: 'outside—let me in!' },
    { name: 'Robin', answer: 'you! Hand over your cash!' },
    { name: 'Irish', answer: 'you a Merry Christmas!' },
    { name: 'Otto', answer: 'know whats taking you so long!' },
    { name: 'Needle', answer: 'little help gettin in the door.' },
    { name: 'Luke', answer: 'through the keyhole to see!' },
    { name: 'Justin', answer: 'the neighborhood and thought Id come over.' },
    { name: 'Europe', answer: 'No, you are a poo' },
    { name: 'To', answer: 'To Whom.' },
    { name: 'Etch', answer: 'Bless You!' },
    { name: 'Mikey', answer: 'doesnt fit through this keyhole' }
]

//choosing a random joke from the array

var knock = function() {
    var joke = jokes[Math.floor(Math.random() * jokes.length)]
    return formatJoke(joke)
}

//Formatting the output to return in a new line and plug in the output variables
function formatJoke(joke) {
    return [
        'Knock, knock.',
        'Who’s there?',
        joke.name + '.',
        joke.name + ' who?',
        joke.name + ' ' + joke.answer
    ].join('\n')
}

//Dice Game

client.on('message', (message) => {
  const messageWords = message.content.split(' ');
  const rollFlavor = messageWords.slice(2).join(' ');
  if (messageWords[0] === '~roll') {
    if (messageWords.length === 1) {
      // ~roll
      return message.send(
        (Math.floor(Math.random() * 6) + 1) + ' ' + rollFlavor
      );
    }

    let sides = messageWords[1]; // ~roll 20
    let rolls = 1;
    if (!isNaN(messageWords[1][0] / 1) && messageWords[1].includes('d')) {
      // ~roll 4d20
      rolls = messageWords[1].split('d')[0] / 1;
      sides = messageWords[1].split('d')[1];
    } else if (messageWords[1][0] == 'd') {
      // ~roll d20
      sides = sides.slice(1);
    }
    sides = sides / 1; // convert to number
    if (isNaN(sides) || isNaN(rolls)) {
      return;
    }
    if (rolls > 1) {
      const rollResults = [];
      for (let i = 0; i < rolls; i++) {
        rollResults.push(Math.floor(Math.random()*sides)+1);
      }
      const sum = rollResults.reduce((a,b) => a + b);
      return message.send(`[${rollResults.toString()}] ${rollFlavor}`);
    } else {
      return message.send(
        (Math.floor(Math.random() * sides) + 1) + ' ' + rollFlavor
      );
    }
  }
});

//8 Ball Game

function doMagic8BallVoodoo() {
    var rand = [':8ball: Absolutly. :8ball:', ':8ball: Absolutly not. :8ball:', ':8ball: It is true. :8ball:', ':8ball: Impossible. :8ball:', ':8ball: Of course. :8ball:', ':8ball: I do not think so. :8ball:', ':8ball: It is true. :8ball:', ':8ball: It is not true. :8ball:', ':8ball: I am very undoubtful of that. :8ball:', ':8ball: I am very doubtful of that. :8ball:', ':8ball: Sources point to no. :8ball:', ':8ball: Theories prove it. :8ball:', ':8ball: Reply hazy, try again. :8ball:', ':8ball: Ask again later... :8ball:', ':8ball: Better not tell you now... :8ball:', ':8ball: Cannot predict now... :8ball:', ':8ball: Concentrate and ask again... :8ball:'];

    return rand[Math.floor(Math.random()*rand.length)];
}

//Coin Toss Game

function coinToss() {
    var rand = [':moneybag: You flipped the coin, it lands on tails. :moneybag:', ':moneybag: I flipped the coin, it lands on tails. :moneybag:', ':moneybag: You flipped the coin, it lands on heads. :moneybag:', ':moneybag: I flipped the coin, it lands on heads. :moneybag:'];
    return rand[Math.floor(Math.random()*rand.length)];
}

//+++++++++++++++++++++++++++++++++Logging+++++++++++++++++++++++++++++++++

client.on('channelCreate', channel => {
    console.log("Channel ID: " + channel.id + " was just created!");
});

client.on('channelDelete', channel => {
    console.log("Channel ID: " + channel.id + " was just removed!");
});

client.on('message', message => {
    console.log('User: ' + message.author.tag + ' Channel: [#' + message.channel.name + '] Message: ' + message.content);
});

//+++++++++++++++++++++++++++++++++Logging+++++++++++++++++++++++++++++++++


//Music Bot


//Verify


//Giveaway



//Money System


//Live Radio



client.login(config.token);

可能是什么问题?

推荐答案

您的问题是您的if语句缺少阻塞。

Your problem is lack of blocking of your if statement.

if (message.channel instanceof Discord.DMChannel)
    message.channel.send("``Beep boop! Sorry, I can't respond to direct messages, but you can join the AKAS Gamer's Discord group here: https://discord.gg/QkjQNAr``");
    return

由于缺少括号,您的退货将始终执行,因为它不属于if语句的应该是:

With the lack of bracketing, your return will always execute as it is not part of the if statement. It should be:

if (message.channel instanceof Discord.DMChannel) {
    message.channel.send("``Beep boop! Sorry, I can't respond to direct messages, but you can join the AKAS Gamer's Discord group here: https://discord.gg/QkjQNAr``");
    return
}

使用C风格语言的共同建议是永远不要忽略括号。进行练习。尽管从技术上讲,单条语句条件语句是允许的,但是如您在此处看到的那样,稍后将引起头痛。

Common recommendation in C-style languages is to never omit the brackets. Get into that practice. While it is technically allowable for single statement conditionals, it will cause headaches later as you've seen here.

这篇关于我的Discord.js机器人正在运行(在线并在控制台中显示),但它不会响应命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆