Мой Discord. js бот запущен (онлайн и отображается в консоли), но не отвечает на команды - PullRequest
0 голосов
/ 12 февраля 2020

Итак, однажды я использовал TeamViewer для подключения к своему RPi3 и велел перезагрузиться. Как только он закончился, я подключился к пи, запустил бота, и выглядело так, как будто он запускается правильно.

Когда я отправил команду на разногласия, бот не ответил. Хотя бот все еще работает.

Я пытался изменить часть кода, но ничего не изменилось.

Вот код:

// 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);

В чем может быть проблема?

1 Ответ

3 голосов
/ 12 февраля 2020

Ваша проблема заключается в отсутствии блокировки вашего оператора if.

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. Это должно быть:

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 - никогда не опускать скобки. Получить в эту практику. Хотя это технически допустимо для условных выражений с одним оператором, это вызовет головные боли позже, как вы видели здесь.

...