TypeError:不知道如何序列化 BigInt

问题描述 投票:0回答:3

我正在用 Javascript 开发一个 Discord 机器人项目。要部署我的命令,我必须将它们注册到我的 index.js 文件中。这是我的项目的结构:

  • index.js
  • 节点模块
  • 其他配置文件...
  • 命令 ∟ 命令文件夹1 ∟ 命令1.js ∟ 命令2.js ∟ 命令文件夹2 ∟ 命令3.js ∟ 命令4.js ∟ 命令文件夹...

类似这样的事情。

但是我有这个错误:

TypeError: Do not know how to serialize a BigInt

这是我的index.js 文件:

const {
  Client,
  Collection,
  Intents,
  GatewayIntentBits,
} = require("discord.js");
const fs = require("fs");
const { token } = require("./config.json");

// Create a new Discord client
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
  ],
});

// Set up a collection to hold your command files
client.commands = new Collection(); // define commands collection here
const commandFolders = fs.readdirSync("./commands");

for (const folder of commandFolders) {
  const commandFiles = fs
    .readdirSync(`./commands/${folder}`)
    .filter((file) => file.endsWith(".js"));

  for (const file of commandFiles) {
    const command = require(`./commands/${folder}/${file}`);
    client.commands.set(command.name, command); // use client.commands instead of commands
  }
}

// Set up event listeners for when the client is ready and when it receives a command interaction
client.once("ready", async () => {
  console.log(`Logged in as ${client.user.tag}!`);

  // Register slash commands
  try {
    const commandData = Array.from(client.commands.values()).map((command) => {
      const data = { ...command };
      if (typeof data.defaultPermission === "boolean") {
        data.defaultPermission = String(data.defaultPermission);
      }
      return data;
    });
    await client.application.commands.set(commandData);
    console.log("Successfully registered application commands.");
  } catch (error) {
    console.error("Failed to register application commands:", error);
  }
});

client.on("interactionCreate", async (interaction) => {
  if (!interaction.isCommand()) return;

  const command = client.commands.get(interaction.commandName); // use client.commands instead of commands

  if (!command) return;

  try {
    await command.execute(interaction);
  } catch (error) {
    console.error(error);
    await interaction.reply({
      content: "There was an error while executing this command!",
      ephemeral: true,
    });
  }
});

// Log in to Discord with your bot token
client.login(token);

这是精确的输出:

Logged in as botname#0000 !
Failed to register application commands: TypeError: Do not know how to serialize a BigInt
    at JSON.stringify (<anonymous>)
    at RequestManager.resolveRequest (path\to\file\node_modules\@discordjs\rest\dist\index.js:1146:26)
    at RequestManager.queueRequest (path\to\file\node_modules\@discordjs\rest\dist\index.js:1056:46)
    at REST.raw (path\to\file\node_modules\@discordjs\rest\dist\index.js:1330:32)
    at REST.request (path\to\file\node_modules\@discordjs\rest\dist\index.js:1321:33)
    at REST.put (path\to\file\node_modules\@discordjs\rest\dist\index.js:1296:17)
    at ApplicationCommandManager.set (path\to\file\node_modules\discord.js\src\managers\ApplicationCommandManager.js:173:41)
    at Client.<anonymous> (path\to\file\index.js:48:39)
    at Object.onceWrapper (node:events:628:26)
    at Client.emit (node:events:513:28)

编辑:

这是造成麻烦的文件:

const { Discord, PermissionFlagsBits } = require("discord.js");
const { MongoClient, ServerApiVersion } = require("mongodb");
const uri =
  "urltoconnectdatabase";

const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  serverApi: ServerApiVersion.v1,
});

module.exports = {
  name: "createcharacter",
  description: "Create your character",
  options: [
    {
      name: "permission",
      description: "Permission level",
      type: "INTEGER",
      required: true,
      choices: [
        {
          name: "Administrator",
          value: PermissionFlagsBits.Administrator,
        },
      ],
    },
  ],

  async execute(interaction) {
    const userId = interaction.user.id;

    await interaction.reply("What's your character's name?");
    const name = await interaction.channel.awaitMessages({
      filter: (m) => m.author.id === interaction.user.id,
      max: 1,
      time: 30000,
    });

    await interaction.reply("What's your character's house?");
    const house = await interaction.channel.awaitMessages({
      filter: (m) => m.author.id === interaction.user.id,
      max: 1,
      time: 30000,
    });

    await interaction.reply("What's your character's wand?");
    const wand = await interaction.channel.awaitMessages({
      filter: (m) => m.author.id === interaction.user.id,
      max: 1,
      time: 30000,
    });

    await interaction.reply("What's your character's patronus?");
    const patronus = await interaction.channel.awaitMessages({
      filter: (m) => m.author.id === interaction.user.id,
      max: 1,
      time: 30000,
    });

    client.connect().then(
      // success
      () => {
        console.log("Connection successful");

        const collection = client.db("WizardryBot").collection("characters");
        let documentToInsert = {
          userId: userId.toString(),
          name: name.first().content,
          house: house.first().content,
          wand: wand.first().content,
          patronus: patronus.first().content,
          experience: 0,
          money: 0,
          quidditchxp: 0,
        };

        function userOwnCharacter(userId) {
          return collection
            .findOne({ userId: userId })
            .then((result) => Promise.resolve(result !== null))
            .catch((err) => {
              console.error(err);
            });
        }

        userOwnCharacter(userId)
          .then((result) => {
            if (result) {
              console.log("User owns a character");
              return Promise.resolve();
            } else {
              console.log("User does not own any character");

              return collection.insertOne(documentToInsert).then(
                (insertedDocument) => {
                  console.log("Data inserted");
                  // console.log(JSON.stringify(insertedDocument, null, 2));

                  const characterEmbed = new Discord.MessageEmbed()
                    .setTitle("Character Information")
                    .addField("Name", name.first().content)
                    .addField("House", house.first().content)
                    .addField("Wand", wand.first().content)
                    .addField("Patronus", patronus.first().content)
                    .setColor("#0099ff");

                  interaction.reply({ embeds: [characterEmbed] });

                  return Promise.resolve();
                },
                (reason) => {
                  console.log("Failed to insert document", reason);
                  return Promise.reject(reason);
                }
              );
            }
          })
          .finally(() => {
            console.log("Closing db connection");
            client.close();
          });
      },
      // failure
      (reason) => {
        // Connection failed with reason
        console.log("Connection failed", reason);
      }
    );
  },
};

这是我的index.js :

const {
  Client,
  Collection,
  Intents,
  GatewayIntentBits,
} = require("discord.js");
const fs = require("fs");
const { token } = require("./config.json");

// Create a new Discord client
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
  ],
});

// Set up a collection to hold your command files
client.commands = new Collection(); // define commands collection here
const commandFolders = fs.readdirSync("./commands");

for (const folder of commandFolders) {
  const commandFiles = fs
    .readdirSync(`./commands/${folder}`)
    .filter((file) => file.endsWith(".js"));

  for (const file of commandFiles) {
    const command = require(`./commands/${folder}/${file}`);
    client.commands.set(command.name, command); // use client.commands instead of commands
  }
}

// Set up event listeners for when the client is ready and when it receives a command interaction
client.once("ready", async () => {
  console.log(`Logged in as ${client.user.tag}!`);

  // Register slash commands
  try {
    const commandData = Array.from(client.commands.values()).map((command) => {
      const data = { ...command };
      if (typeof data.defaultPermission === "boolean") {
        data.defaultPermission = String(data.defaultPermission);
      }
      // Convert any BigInt values to string
      if (typeof data.id === "bigint") {
        data.id = data.id.toString();
      }
      return data;
    });
    await client.application.commands.set(commandData);
    console.log("Successfully registered application commands.");
  } catch (error) {
    console.error("Failed to register application commands:", error);
  }
});

client.on("interactionCreate", async (interaction) => {
  if (!interaction.isCommand()) return;

  const command = client.commands.get(interaction.commandName); // use client.commands instead of commands

  if (!command) return;

  try {
    await command.execute(interaction);
  } catch (error) {
    console.error(error);
    await interaction.reply({
      content: "There was an error while executing this command!",
      ephemeral: true,
    });
  }
});

// Log in to Discord with your bot token
client.login(token);

javascript discord.js
3个回答
1
投票

好的,我解决了我的错误。在我的代码中,我不需要以下部分:

options: [
    {
      name: "permission",
      description: "Permission level",
      type: "INTEGER",
      required: true,
      choices: [
        {
          name: "Administrator",
          value: PermissionFlagsBits.Administrator,
        },
      ],
    },
  ],

所以我把它删除了。现在可以了! 感谢您的帮助!


0
投票

在主文件中我简单地转换它

declare global {
    interface BigInt {
        toJSON(): Number;
    }
}

BigInt.prototype.toJSON = function () { return Number(this) }

参考该问题:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#use_within_json


-1
投票

我在进行玩笑测试时遇到了这个错误。

发生此错误时的示例:

expect(BigInt('1.2345')).toBe('1.2345'); // BigInt vs String

因此,如果您有条件,请检查它们并将它们重新定义为单一类型。

© www.soinside.com 2019 - 2024. All rights reserved.