Search code examples
node.jsdiscord.jsopenai-api

Method Not Allowed Error While trying to run a bot in discord.js


So I'm making a bot for my server that's AI powered and I'm encountring a "405: Method Not Allowed Error".

Here's my index.js code:

const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.commands = new Collection();
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

for (const folder of commandFolders) {
    const commandsPath = path.join(foldersPath, folder);
    const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
    for (const file of commandFiles) {
        const filePath = path.join(commandsPath, file);
        const command = require(filePath);
        if ('data' in command && 'execute' in command) {
            client.commands.set(command.data.name, command);
        } else {
            console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
        }
    }
}

client.once(Events.ClientReady, readyClient => {
    console.log(`Ready! Logged in as ${readyClient.user.tag}`);
});

client.on(Events.InteractionCreate, async interaction => {
    if (!interaction.isChatInputCommand()) return;
    const command = interaction.client.commands.get(interaction.commandName);

    if (!command) {
        console.error(`No command matching ${interaction.commandName} was found.`);
        return;
    }

    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        if (interaction.replied || interaction.deferred) {
            await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
        } else {
            await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
        }
    }
});

client.login(token);

My commands\generate_images.js (from where the error is occuring):

const { SlashCommandBuilder } = require("discord.js");
const axios = require("axios");

module.exports = {
  data: new SlashCommandBuilder()
    .setName("generate-images")
    .setDescription("Generate High Quality AI Images Using The Best Model!")
    .addStringOption((option) =>
      option.setName("prompt").setDescription("Prompt").setRequired(true)
    ),
  async execute(interaction) {
    const promptInput = interaction.options.getString("prompt") ?? "Make an image of a person sitting on a bench and holding a 404 banner";
    
    try {
      const response = await axios.post(
        "https://api.openai.com/v1/images/generations",
        {
          model: "dall-e-3",
          prompt: promptInput,
          n: 1,
          size: "1024x1024",
        },
        {
          headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer (My OpenAI Key Its Correct)",
          },
        }
      );
      
      const url = response.data;
      interaction.reply(url);
    } catch (error) {
      console.error(error);
      interaction.reply("An error occurred while generating the image.");
    }
  },
};

I did some tweaks and changes but the same error kept occuring.

I even checked the whole index.js thoroughly.


Solution

  • OpenAI has an official NPM package to interface with their API. I recommend using it as it could solve a bunch of formatting issues due to the odd requirements the API has.

    https://www.npmjs.com/package/openai