30 分钟未使用后 Discord.js 机器人错误

编程入门 行业动态 更新时间:2024-10-04 01:15:04

30 分钟未使用后 Discord.js <a href=https://www.elefans.com/category/jswz/34/1771006.html style=机器人错误"/>

30 分钟未使用后 Discord.js 机器人错误

我不知道为什么,但是所有命令、交互和一切都有效。但是,如果我停止使用该机器人并将其留在网上,返回并运行另一个命令,它只会输出此错误并崩溃

/home/yetnt/bots/mJb/node_modules/@discordjs/rest/dist/index.js:640
      throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
            ^

DiscordAPIError[10062]: Unknown interaction
    at handleErrors (/home/yetnt/bots/mJb/node_modules/@discordjs/rest/dist/index.js:640:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async BurstHandler.runRequest (/home/yetnt/bots/mJb/node_modules/@discordjs/rest/dist/index.js:736:23)
    at async REST.request (/home/yetnt/bots/mJb/node_modules/@discordjs/rest/dist/index.js:1387:22)
    at async ChatInputCommandInteraction.deferReply (/home/yetnt/bots/mJb/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:69:5) {
  requestBody: { files: undefined, json: { type: 5, data: { flags: undefined } } },
  rawError: { message: 'Unknown interaction', code: 10062 },
  code: 10062,
  status: 404,
  method: 'POST',
  url: ''
}

Node.js v18.16.0
[nodemon] app crashed - waiting for file changes before starting...

我重新启动机器人,一切正常,所有命令和一切。但在它闲置之前,它不起作用。 我不介意每次都重新启动机器人,但这现在很烦人。

rob.js

const { ApplicationCommandOptionType, Client, Interaction, EmbedBuilder } = require('discord.js')
const User = require('../../models/User')
const rndInt = require('../../utils/rndInt')
const Inventory = require('../../models/Inventory')
const [ comma, coin, shopify ] = require('../../utils/beatify')
const { newCooldown, checkCooldown } = require('../../utils/cooldown')

module.exports = {
    name:"rob",
    description:"Rob people for some quick cash",
    options: [
        {
            name:"victim",
            description:"robbery",
            type: ApplicationCommandOptionType.User,
            required: true
        }
    ],
    blacklist: true,


    /**
    *
    * @param {Client} client
    * @param {Interaction} interaction
    */
    callback: async (client, interaction) => {

        try {
            await interaction.deferReply()
            let victimId = interaction.options.get("victim").value
            const sf = rndInt(1, 2) // 2 = success; 1 = failure

            let victim = await User.findOne({userId: victimId})
            let inventory = await Inventory.findOne({userId: victimId}) // victim's inventory
            const victimDm = await client.users.fetch(victimId).catch(() => null); // to dm the user.
            let author = await User.findOne({userId: interaction.user.id })

            if (victimId == interaction.user.id) {interaction.editReply( { embeds : [ new EmbedBuilder().setDescription("don't rob yourself.")]}); return};
            if (!author) {interaction.editReply( { embeds : [ new EmbedBuilder().setDescription("You cannot rob people when you've got nothing")]}); return}
            if (author.balance < 1000) {interaction.editReply( { embeds : [ new EmbedBuilder().setDescription("You cannot rob people when your balance is lower than 1000.")]}); return}
            if (!victim) {interaction.editReply( { embeds : [ new EmbedBuilder().setDescription("Leave them alone, they've got nothing :sob:")]}); return};
            if (victim.balance < 0) {interaction.editReply( { embeds : [ new EmbedBuilder().setDescription("This user is paying off their debts")]}); return};
            if (victim.balance <= 500) {interaction.editReply( { embeds : [ new EmbedBuilder().setDescription(`It aint worth it, they've only got ${coin(victim.balance)}`)]}); return};

            const cooldownResult = await checkCooldown('rob', interaction, EmbedBuilder);
            if (cooldownResult === 0) {
              return;
            }

            if (inventory) { // check if they have an inventory
                if (inventory.inv.shield.amt > 0 && inventory.inv.shield.hp > 0) {
                    let damage = rndInt(Math.ceil(inventory.inv.shield.hp / 2), inventory.inv.shield.hp)
                    await interaction.editReply( { embeds : [ new EmbedBuilder().setDescription(`You tried to rob them but this user had a shield! You damaged their shield by **${comma(damage)}%**`)]})
                    inventory.inv.shield.hp -= damage

                    await inventory.save()
                    if (inventory.inv.shield.hp == 0) {
                        inventory.inv.shield.amt -= 1
                        await interaction.followUp("You broke this user's shield.")
                        await inventory.save()
                    }
                    return
                }
            }
            
            const max = Math.floor(victim.balance / 2) // doing this so mfs dont get their whole ass robbed. 
            let sRob = rndInt(1, max) // user can only be robbed random amounts from 1 to half their balance
            let fRob = rndInt(Math.floor(author.balance / 2), author.balance) // if robbery failed deduct random amt between author/2 and author

            if (sf === 2) { // Succesful
                victim.balance -= sRob
                author.balance += sRob

                await victimDm.send({
                    embeds: [
                        new EmbedBuilder()
                            .setTitle("You have been robbed from!")
                            .setDescription(`<@${interaction.user.id}> stole ${coin(sRob)} from you!`)
                            .setFooter({text: `Server = ${interaction.member.guild.name}`})
                    ]
                }).catch(() => null);

                await interaction.editReply({
                    embeds : [
                        new EmbedBuilder()
                            .setTitle("Robbery :money_with_wings:")
                            .setDescription(`You stole a grand total of ${coin(sRob)} from <@${victimId}>. Leaving them with ${coin(victim.balance)}`)
                            .setColor("Green")
                            .setFooter({text: "You monster"})
                    ]
                })
            } else { // failed
                author.balance -= fRob
                victim.balance += fRob

                interaction.editReply({
                    embeds : [
                        new EmbedBuilder()
                            .setTitle("Robbery")
                            .setDescription(`You tried robbing <@${victimId}> but they caught you before you could get away. You paid ${coin(fRob)} in fines to <@${victimId}>`)
                            .setColor("Red")
                            .setFooter({text: "I knew this wouldnt work."})
                    ]
                })
            }

            await author.save()
            await victim.save()

            await newCooldown('5min', interaction, 'rob')
        }  catch (error) {
            interaction.editReply('An error occured.')
            client.guilds.cache.get("808701451399725116").channels.cache.get("971098250780241990").send({ embeds : [
                new EmbedBuilder()
                .setTitle(`An error occured. Command name = ${interactionmandName}`)
                .setDescription(`\`${error}\``)
                .setTimestamp()
                .setFooter({text:`Server ID : ${interaction.guild.id} | User ID : ${interaction.user.id} | Error was also logged to console.`})
            ]})
            console.log(error)
        }
    }
}

handleCommands.js

const path = require('path');
const { devs, testServer } = require(path.join(__dirname, '..', '..', '..', 'config.json'));
const getLocalCommands = require(path.join(__dirname, '..', '..', 'utils', 'getLocalCommands'));
const Blacklist = require('../../models/Blacklist')
const { EmbedBuilder } = require('discord.js');

module.exports = async (client, interaction) => {
  if (!interaction.isChatInputCommand()) return;

  const localCommands = getLocalCommands();

  try {
    const commandObject = localCommands.find(
      (cmd) => cmd.name === interactionmandName
    );

    if (!commandObject) return;

    if (commandObject.devOnly) {
      if (!devs.includes(interaction.user.id)) {
        interaction.reply({
          content: 'Only developers are allowed to run this command.',
          ephemeral: true,
        });
        return;
      };
    };
     
    if (commandObject.blacklist) {
      let query = {
        userId: interaction.user.id
      };
      let blacklist = await Blacklist.findOne(query)
      
      if (blacklist) {
        if (blacklist.blacklisted === true) {
          interaction.reply("You've been blacklisted. Reason = " + `${blacklist.reason}`)
          return;
        };
      };
    };

    if (commandObject.testOnly) {
      if (!(interaction.guild.id === testServer)) {
        interaction.reply({
          content: 'This command cannot be ran here.',
          ephemeral: true,
        });
        return;
      }
    }

    if (commandObject.permissionsRequired?.length) {
      for (const permission of commandObject.permissionsRequired) {
        if (!interaction.member.permissions.has(permission)) {
          interaction.reply({
            content: 'Not enough permissions.',
            ephemeral: true,
          });
          return;
        }
      }
    }

    if (commandObject.botPermissions?.length) {
      for (const permission of commandObject.botPermissions) {
        const bot = interaction.guild.members.me;

        if (!bot.permissions.has(permission)) {
          interaction.reply({
            content: "I don't have enough permissions.",
            ephemeral: true,
          });
          return;
        }
      }
    }

    await commandObject.callback(client, interaction);
  } catch (error) {
    console.log(`There was an error running the command: `);
    console.log(error)
  }
};
回答如下:

更多推荐

30 分钟未使用后 Discord.js 机器人错误

本文发布于:2024-05-31 00:58:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771107.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:机器人   错误   Discord   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!