javascriptdiscord.js

TypeError: Do not know how to serialize a BigInt


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

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

And here is the precise output :

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)

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


Solution

  • 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 !