最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeError: Do not know how to serialize a BigInt - Stack Overflow

programmeradmin3浏览0评论

I'm working on a discord bot project in Javascript. To deploy my mands I have to register them in my index.js file. Here is the structure of my project :

  • index.js
  • node_modules
  • other config files...
  • mands ∟ mand_folder1 ∟ mand1.js ∟ mand2.js ∟ mand-folder2 ∟ mand3.js ∟ mand4.js ∟ mand-folder...

Something like that.

But I have this error : TypeError: Do not know how to serialize a BigInt

Here is my index.js file :

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 mand files
clientmands = new Collection(); // define mands collection here
const mandFolders = fs.readdirSync("./mands");

for (const folder of mandFolders) {
  const mandFiles = fs
    .readdirSync(`./mands/${folder}`)
    .filter((file) => file.endsWith(".js"));

  for (const file of mandFiles) {
    const mand = require(`./mands/${folder}/${file}`);
    clientmands.set(mand.name, mand); // use clientmands instead of mands
  }
}

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

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

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

  const mand = clientmands.get(interactionmandName); // use clientmands instead of mands

  if (!mand) return;

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

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

And here is the precise output :

Logged in as botname#0000 !
Failed to register application mands: 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)

Edit :

Here is the file that make trouble :

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);
      }
    );
  },
};

Here is my 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 mand files
clientmands = new Collection(); // define mands collection here
const mandFolders = fs.readdirSync("./mands");

for (const folder of mandFolders) {
  const mandFiles = fs
    .readdirSync(`./mands/${folder}`)
    .filter((file) => file.endsWith(".js"));

  for (const file of mandFiles) {
    const mand = require(`./mands/${folder}/${file}`);
    clientmands.set(mand.name, mand); // use clientmands instead of mands
  }
}

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

  // Register slash mands
  try {
    const mandData = Array.from(clientmands.values()).map((mand) => {
      const data = { ..mand };
      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.applicationmands.set(mandData);
    console.log("Successfully registered application mands.");
  } catch (error) {
    console.error("Failed to register application mands:", error);
  }
});

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

  const mand = clientmands.get(interactionmandName); // use clientmands instead of mands

  if (!mand) return;

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

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

I'm working on a discord bot project in Javascript. To deploy my mands I have to register them in my index.js file. Here is the structure of my project :

  • index.js
  • node_modules
  • other config files...
  • mands ∟ mand_folder1 ∟ mand1.js ∟ mand2.js ∟ mand-folder2 ∟ mand3.js ∟ mand4.js ∟ mand-folder...

Something like that.

But I have this error : TypeError: Do not know how to serialize a BigInt

Here is my index.js file :

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 mand files
client.mands = new Collection(); // define mands collection here
const mandFolders = fs.readdirSync("./mands");

for (const folder of mandFolders) {
  const mandFiles = fs
    .readdirSync(`./mands/${folder}`)
    .filter((file) => file.endsWith(".js"));

  for (const file of mandFiles) {
    const mand = require(`./mands/${folder}/${file}`);
    client.mands.set(mand.name, mand); // use client.mands instead of mands
  }
}

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

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

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

  const mand = client.mands.get(interaction.mandName); // use client.mands instead of mands

  if (!mand) return;

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

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

And here is the precise output :

Logged in as botname#0000 !
Failed to register application mands: 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)

Edit :

Here is the file that make trouble :

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);
      }
    );
  },
};

Here is my 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 mand files
client.mands = new Collection(); // define mands collection here
const mandFolders = fs.readdirSync("./mands");

for (const folder of mandFolders) {
  const mandFiles = fs
    .readdirSync(`./mands/${folder}`)
    .filter((file) => file.endsWith(".js"));

  for (const file of mandFiles) {
    const mand = require(`./mands/${folder}/${file}`);
    client.mands.set(mand.name, mand); // use client.mands instead of mands
  }
}

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

  // Register slash mands
  try {
    const mandData = Array.from(client.mands.values()).map((mand) => {
      const data = { ...mand };
      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.mands.set(mandData);
    console.log("Successfully registered application mands.");
  } catch (error) {
    console.error("Failed to register application mands:", error);
  }
});

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

  const mand = client.mands.get(interaction.mandName); // use client.mands instead of mands

  if (!mand) return;

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

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

Share Improve this question edited Mar 18, 2023 at 14:25 Alden Vacker asked Mar 15, 2023 at 20:53 Alden VackerAlden Vacker 991 gold badge1 silver badge7 bronze badges 10
  • 2 One of your mand files has a BigInt literal in it. – tenshi Commented Mar 15, 2023 at 20:55
  • 1 this is happening because of a miss configuration in one mand. Can you try enabling only one (temporary move the other files)? if the issue still occurs, send the single mand file. If the issue disappears, repeat the process for each mand until you find the miss configured one. – Androz2091 Commented Mar 15, 2023 at 20:56
  • 3 You can fix it by converting it to a string: bigIntValue.toString(). – code Commented Mar 15, 2023 at 20:57
  • @Androz2091 ok thanks I will try tonight and send the miss configured mand file ! – Alden Vacker Commented Mar 16, 2023 at 6:48
  • Okay I did it ! – Alden Vacker Commented Mar 16, 2023 at 22:23
 |  Show 5 more ments

5 Answers 5

Reset to default 3

In main file I simply convert it

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

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

ref to the issue: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#use_within_json

For those of you that got here because a failing test involves some BigInt, you can temporarily circumvent this issue by setting maxWorkers: 1 in your jest configuration or run test with --maxWorkers=1 flag.

Link to jest issue

Okay I resolve my error. In my code I didn't need the following part :

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

So I remove it. And now it works ! Thanks for your help !

I was having the same issue and here's what worked for me.

In my index.ts file where my script's started i defined this piece of code:

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

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

After that all my BigInt instances are converted to string automatically when the method toJSON() is called. I didn't have to make any changes in my code besides that. So, if i have and array with objects that have some fields of type BigInt, all of them bee strings. In my HTTP response, for example, i receive every bigint type as a string and then i convert them back to BigInt

I faced with this error when I was working with jest tests.

An example when this error happens:

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

So if you have conditions check them and redefine them to single type.

发布评论

评论列表(0)

  1. 暂无评论