【问题标题】:discord bot replying to every prefix discord.js [closed]不和谐机器人回复每个前缀 discord.js [关闭]
【发布时间】:2021-11-04 00:06:53
【问题描述】:

hai 我的机器人正在回复每个前缀,默认前缀是 $,但它会回复 !, >, @, #, $, % ^,&,~ 和更多问题只是命令处理程序我的意思是命令在另一个 js 文件中它甚至回复 mlock,block,klock。我认为这是命令处理程序的问题。这个问题不会发生在 main.js 文件中的命令上,我的意思是使用这样的 if 和 else 语句

if (message.content.startsWith('$kick'))

问题发生在这个命令处理程序上

if(command === 'joke'){
    client.commands.get('joke').execute(message, args);
  }
  if(command === 'lock'){
    client.commands.get('lock').execute(message, args);
  }
  if(command === 'roast'){
    client.commands.get('roast').execute(message, args);
  }
  if(command === 'unlock'){
    client.commands.get('unlock').execute(message, args);
  }
  if(command === 'mute'){
    client.commands.get('mute').execute(message, args);
  }
  if(command === 'unmute'){
    client.commands.get('unmute').execute(message, args);
  }

我是java脚本的新手,请帮助我

这是我的 main.js

const https = require('https');

const url = 'https://www.reddit.com/r/meme/hot/.json?limit=100'

const aurl = 'https://www.reddit.com/r/aww/top/.json?sort=top&t=day&limit=100'





const Discord = require("discord.js");
const client = new Discord.Client();

const fs = require('fs');
client.commands = new Discord.Collection();

const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

const express = require("express")

const app = express()


app.get("/", (req, res) =>{
  console.log("helloe")
})

app.listen(3000, () => {
  console.log("Ready")
})
const disbut = require('discord-buttons');
disbut(client);



client.once('ready', () => {
    console.log('Beast Bot is ready');
    client.user.setActivity('$help || (Made by CaptainBeast#1394)  ', { type:"WATCHING"}).catch(console.error)
    
    client.guilds.cache.forEach(guild => {
      console.log(`${guild.name} | ${guild.id}`);
    })
});




const ownerId = "602113193489203232";
const owner2Id = "725629309854679092";

client.on('clickButton', async(button) => {
  
  })

client.on("message", async message => {
  if (message.channel.type == "dm") return;
  else {  
    
  const args = message.content.slice(prefix.length).trim().split(/ +/);
  const command = args.shift().toLowerCase();

  if(command === 'joke'){
    client.commands.get('joke').execute(message, args);
  }
  if(command === 'lock'){
    client.commands.get('lock').execute(message, args);
  }
  if(command === 'roast'){
    client.commands.get('roast').execute(message, args);
  }
  if(command === 'unlock'){
    client.commands.get('unlock').execute(message, args);
  }
  if(command === 'mute'){
    client.commands.get('mute').execute(message, args);
  }
  if(command === 'unmute'){
    client.commands.get('unmute').execute(message, args);
  }

    
    
    if (message.author.bot) return false;

    if (message.mentions.has(ownerId)) {
       
        message.reply(`Thanks for pinging my owner you will be banned with in 24 hours :))`);
    
    
    };
    if (message.mentions.has(owner2Id)) {
       
      message.reply(`Thanks for pinging my co-owner you will be banned with in 24 hours :))`);

  };



  if(message.content.startsWith(prefix + 'nuke')){
  message.channel.send('Due to some bugs this command has been disabled for 5 days')
  
}
  
  

if (message.content.startsWith("$meme")) {

  https.get(url, (result) => {
    var body = ''
    result.on('data', (chunk) => {
        body += chunk
    })
  
    result.on('end', () => {
        var response = JSON.parse(body)
        var index = response.data.children[Math.floor(Math.random() * 99) + 1].data
  
        if (index.post_hint !== 'image') {
  
            var text = index.selftext
            const textembed = new Discord.MessageEmbed()
                .setTitle(subRedditName)
                .setColor(9384170)
                .setDescription(`[${title}](${link})\n\n${text}`)
                .setURL(`https://reddit.com/${subRedditName}`)
  
            message.channel.send(textembed)
        }
  
        var image = index.preview.images[0].source.url.replace('&', '&')
        var title = index.title
        var link = 'https://reddit.com' + index.permalink
        var subRedditName = index.subreddit_name_prefixed
  
        if (index.post_hint !== 'image') {
            const textembed = new Discord.MessageEmbed()
                .setTitle(subRedditName)
                .setColor(9384170)
                .setDescription(`[${title}](${link})\n\n${text}`)
                .setURL(`https://reddit.com/${subRedditName}`)
  
            message.channel.send(textembed)
        }
        console.log(image);
        const imageembed = new Discord.MessageEmbed()
            .setTitle(subRedditName)
            .setImage(image)
            .setColor(9384170)
            .setDescription(`[${title}](${link})`)
            .setURL(`https://reddit.com/${subRedditName}`)
        message.channel.send(imageembed)
    }).on('error', function (e) {
        console.log('Got an error: ', e)
    })
  })
    }





    if (message.content.startsWith("$cute")) {

      https.get(aurl, (result) => {
        var body = ''
        result.on('data', (chunk) => {
            body += chunk
        })
      
        result.on('end', () => {
            var response = JSON.parse(body)
            var index = response.data.children[Math.floor(Math.random() * 99) + 1].data
      
            if (index.post_hint !== 'image') {
      
                var text = index.selftext
                const textembed = new Discord.MessageEmbed()
                    .setTitle(subRedditName)
                    .setColor(9384170)
                    .setDescription(`[${title}](${link})\n\n${text}`)
                    .setURL(`https://reddit.com/${subRedditName}`)
      
                message.channel.send(textembed)
            }
      
            var image = index.preview.images[0].source.url.replace('&', '&')
            var title = index.title
            var link = 'https://reddit.com' + index.permalink
            var subRedditName = index.subreddit_name_prefixed
      
            if (index.post_hint !== 'image') {
                const textembed = new Discord.MessageEmbed()
                    .setTitle(subRedditName)
                    .setColor(9384170)
                    .setDescription(`[${title}](${link})\n\n${text}`)
                    .setURL(`https://reddit.com/${subRedditName}`)
      
                message.channel.send(textembed)
            }
            console.log(image);
            const imageembed = new Discord.MessageEmbed()
                .setTitle(subRedditName)
                .setImage(image)
                .setColor(9384170)
                .setDescription(`[${title}](${link})`)
                .setURL(`https://reddit.com/${subRedditName}`)
            message.channel.send(imageembed)
        }).on('error', function (e) {
            console.log('Got an error: ', e)
        })
      })
        }



    if(message.content.startsWith("$download")){
    let button = new disbut.MessageButton()
  .setLabel("Download")
  .setURL('http://www.beaststudios.ga')
  .setStyle('url');

message.channel.send("Download Firebones at www.beaststudios.ga", button);
        
        
    }
    
    
  if(message.content.startsWith("~mute")) {
    if(message.member.hasPermission("KICK_MEMBERS"))
    {
      message.reply(`Thanks for pinging my co-owner you will be banned with in 24 hours :))`);

    }
  };


  if (!message.guild) return;

  // if the message content starts with "!ban"
  if (message.content.startsWith('$ban')) {

    if (message.member.hasPermission("BAN_MEMBERS")) {
     // Assuming we mention someone in the message, this will return the user
    // Read more about mentions over at https://discord.js.org/#/docs/main/master/class/MessageMentions
    const user = message.mentions.users.first();
    // If we have a user mentioned
    if (user) {
      // Now we get the member from the user
      const member = message.guild.members.resolve(user);
      // If the member is in the guild
      if (member) {
        /**
         * Ban the member
         * Make sure you run this on a member, not a user!
         * There are big differences between a user and a member
         * Read more about what ban options there are over at
         * https://discord.js.org/#/docs/main/master/class/GuildMember?scrollTo=ban
         */
        member
          .ban({
            reason: 'They were bad!',
          })
          .then(() => {
            // We let the message author know we were able to ban the person
            message.channel.send(`Successfully banned ${user.tag} ????`);
          })
          .catch(err => {
            // An error happened
            // This is generally due to the bot not being able to ban the member,
            // either due to missing permissions or role hierarchy
            message.channel.send('I was unable to ban the member');
            // Log the error
            console.error(err);
          });
      } else {
        // The mentioned user isn't in this guild
        message.channel.send("That user isn't in this guild!");
      }
    } else {
      // Otherwise, if no user was mentioned
      message.channel.send("You didn't mention the user to ban!");
    }
    } else {
      message.channel.send('You dont have permission to ban ????')
    }
    
  }




  if (message.content.startsWith('$kick')) {

    if (message.member.hasPermission("KICK_MEMBERS")) {
     // Assuming we mention someone in the message, this will return the user
    // Read more about mentions over at https://discord.js.org/#/docs/main/master/class/MessageMentions
    const user = message.mentions.users.first();
    // If we have a user mentioned
    if (user) {
      // Now we get the member from the user
      const member = message.guild.members.resolve(user);
      // If the member is in the guild
      if (member) {
        /**
         * Ban the member
         * Make sure you run this on a member, not a user!
         * There are big differences between a user and a member
         * Read more about what ban options there are over at
         * https://discord.js.org/#/docs/main/master/class/GuildMember?scrollTo=ban
         */
        member
          .kick({
            reason: 'They were bad!',
          })
          .then(() => {
            // We let the message author know we were able to ban the person
            message.channel.send(`Successfully kicked ${user.tag}`);
          })
          .catch(err => {
            // An error happened
            // This is generally due to the bot not being able to ban the member,
            // either due to missing permissions or role hierarchy
            message.channel.send('I was unable to kick the member');
            // Log the error
            console.error(err);
          });
      } else {
        // The mentioned user isn't in this guild
        message.channel.send("That user isn't in this guild!");
      }
    } else {
      // Otherwise, if no user was mentioned
      message.channel.send("You didn't mention the user to kick!");
    }
    } else {
      message.channel.send('You dont have permission to kick')
    }
    
  }






  }

});

// empeds here please
// inside a command, event listener, etc.
const help = new Discord.MessageEmbed()
    .setColor('#0099ff')
    .setTitle('Commands')
    .setURL('')
    .setAuthor('CaptainBeast', 'https://i.ibb.co/94KPj7q/ec46ca68e6b77bb5e8a085164b82fee8.png')
    .setDescription('Here are the list of some available commands')
    .setThumbnail('https://i.ibb.co/94KPj7q/ec46ca68e6b77bb5e8a085164b82fee8.png')
    .addFields(
        { name: 'Commands', value: ':) commands' },
        { name: '\u200B', value: '\u200B' },
        { name: '`$help`', value: 'Displays list of available commands', inline: true },
        { name: '`$ping`', value: 'sent pong ', inline: true },
    { name: '`$download`', value: 'sent link to download firebones ', inline: true },
    { name: '`$ban @user`', value: 'Bans a member ???? ', inline: true },
    { name: '`$kick @user`', value: 'Kicks a member  ', inline: true },
    { name: '`$nuke`', value: 'nukes a channel', inline: true },
    { name: '`$meme`', value: 'sent meme', inline: true },
    { name: '`$cute`', value: 'sent cute stuffs', inline: true },
    { name: '`$joke`', value: 'sent sent jokes', inline: true },
    { name: '`$lock`', value: 'locks a channel', inline: true },
    { name: '`$unlock`', value: 'unlocks a channel', inline: true },
    { name: '`$roast @user`', value: 'roast a user', inline: true },
    { name: '`$mute @user <reason>`', value: 'mutes a user', inline: true },
    { name: '`$unmute @user <reason>`', value: 'unmutes a user', inline: true },


    )
    .addField('More stuffs coming soon', 'the bot is still under development', true)
    .setImage('')
    .setTimestamp()
    .setFooter('Made by CaptainBeast#1394', 'https://i.ibb.co/94KPj7q/ec46ca68e6b77bb5e8a085164b82fee8.png');
    
   
  const nuked = new Discord.MessageEmbed()

    .setColor('#34495E')
    .setTitle('Nuked')
    .setURL('')
    .setAuthor('CaptainBeast')
    .setDescription('Succesfully Nuked this channel')
    .setThumbnail('https://thumbs-prod.si-cdn.com/sIkNe_eIDylRJqhqZX7gk2KHtYc=/800x600/filters:no_upscale()/https://public-media.si-cdn.com/filer/dd/44/dd44ce31-4cc3-46c0-9378-0ec0da5a13e0/02_10_2014_romeo_nuke.jpg')
    .setFooter('Boom')
  
 

const prefix = "$";
client.on("message", (message) => {
  // Exit and stop if it's not there
  if (!message.content.startsWith(prefix)) return;

  if (message.content.startsWith(prefix + "help")) {
    message.channel.send(help);
    
  } else
  if (message.content.startsWith(prefix + "foo")) {
    message.channel.send("bar!");
  }
  if (message.content.startsWith(prefix + "ping")) {
    message.channel.send("pong!");
  }
 
});

commandFiles.forEach(file => {
  const command = file.split(/.js$/)[0];
  client.commands.set(command, require(`./commands/${file}`));
});


client.login('Censored')

这是我的 lock.js

const Discord = require('discord.js')


module.exports = {
    name : 'lock',
    description : 'locks a channel',
    
  async execute(message, args){

     
        const lockemped = new Discord.MessageEmbed()
  
        .setColor('#34495E')
        .setTitle('Locked')
        .setDescription('Succesfully locked this channel ????')

    let lockPermErr = new Discord.MessageEmbed()
        .setTitle("**User Permission Error!**")
        .setDescription("**Sorry, you don't have permissions to use this! ❌**")
        
        if(!message.channel.permissionsFor(message.member).has("ADMINISTRATOR") ) return message.channel.send(lockPermErr);

        let channel = message.channel;

        try {
            message.guild.roles.cache.forEach(role => {
                channel.createOverwrite(role, {
                    SEND_MESSAGES: false,
                    ADD_REACTIONS: false
                });
            });
        } catch (e) {
            console.log(e);
        }


        message.channel.send(lockemped);



      

  }
}

它不仅发生在 lock.js 上,它也发生在 joke.js、roast.js.... 等等

提前致谢!!

【问题讨论】:

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


    【解决方案1】:

    您没有检查您的消息是否以代码中任何位置的前缀开头。将此添加到您的消息处理程序:

    if (!message.content.startsWith(prefix)) return;
    

    此代码检查消息是否以前缀开头,如果不是,则返回。

    【讨论】:

      猜你喜欢
      • 2017-10-15
      • 2021-06-19
      • 2021-07-30
      • 2021-04-09
      • 2020-10-11
      • 2020-12-05
      • 2020-10-29
      • 2017-09-13
      • 2020-11-10
      相关资源
      最近更新 更多