我正在制作一个 Discord 机器人,它使用 OpenAI 根据用户的输入生成图像。运行主文件 index.js 后,我在命令中输入提示符来测试它。它确实生成了图像并在控制台中记录了图像的 url,但是随后,它无法发送相同的图像。我经历了错误,
这是我的index.js 文件:
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);
/* This block of code is iterating over each folder in the `commands` directory and then for each file
within those folders that ends with `.js`, it requires the file and checks if it has both a `data`
and `execute` property. If the required properties are present, it adds the command to the
`client.commands` Collection with the command's name as the key. If the required properties are
missing, it logs a warning message indicating that the command file is missing the necessary
properties. */
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}`);
});
/* This block of code is handling interactions created by users in a Discord server. */
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);
这是我的命令/generate_images.js
const { SlashCommandBuilder } = require("discord.js");
const OpenAI = require("openai");
const openai = new OpenAI({
apiKey: "sk-proj-my-api-key",
});
/**
* This code block is defining a Discord slash command handler
for generating high-quality AI images using the OpenAI API.
*/
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");
if (!promptInput) {
// Handling case where prompt is not provided
interaction.reply("Please provide a prompt.");
return;
}
try {
const response = await openai.images.generate({
model: "dall-e-3",
prompt: promptInput,
n: 1,
size: "1024x1024",
});
console.log("Response:", response); // Add this line
interaction.reply(response.data);
} catch (error) {
console.error(error);
interaction.reply("An error occurred while generating the image.");
}
},
};
这是错误:
throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
^
DiscordAPIError[10062]: Unknown interaction
at handleErrors (C:\Users\Acer\Desktop\discord-bot\node_modules\@discordjs\rest\dist\index.js:722:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async BurstHandler.runRequest (C:\Users\Acer\Desktop\discord-bot\node_modules\@discordjs\rest\dist\index.js:826:23)
at async _REST.request (C:\Users\Acer\Desktop\discord-bot\node_modules\@discordjs\rest\dist\index.js:1266:22)
at async ChatInputCommandInteraction.reply (C:\Users\Acer\Desktop\discord-bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:111:5) {
requestBody: {
files: [],
json: {
type: 4,
data: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined,
thread_name: undefined
}
}
},
rawError: { message: 'Unknown interaction', code: 10062 },
code: 10062,
status: 404,
method: 'POST',
url: 'https://discord.com/api/v10/interactions/1231599602235605074/aW50ZXJhY3Rpb246MTIzMTU5OTYwMjIzNTYwNTA3NDpTQ0d2WjZUUENrbmVabHJzY29rSDZ2SmFrUVpCbTdoODZqZUcwQ3VWa0JFU3RoUHpYMHJpZzl6cXFHTnVJN1dycUNicXJTVFhZNzFMRDFoZkF4aW9pbm9XSlkzNkNTSndzakJhV09rWVp5cklKeUhVRVF2MThoeEJ0a2xlOEJvaw/callback'
}
// 20240421191342
// https://discord.com/api/v10/interactions/1231599602235605074/aW50ZXJhY3Rpb246MTIzMTU5OTYwMjIzNTYwNTA3NDpTQ0d2WjZUUENrbmVabHJzY29rSDZ2SmFrUVpCbTdoODZqZUcwQ3VWa0JFU3RoUHpYMHJpZzl6cXFHTnVJN1dycUNicXJTVFhZNzFMRDFoZkF4aW9pbm9XSlkzNkNTSndzakJhV09rWVp5cklKeUhVRVF2MThoeEJ0a2xlOEJvaw/callback
{
"message": "405: Method Not Allowed",
"code": 0
}
我改了很多次代码,但还是不行。
如果您在控制台中收到未知的交互,则交互很可能会超时,以避免您可以添加 deferReply 方法,该方法会发送机器人正在思考的初始回复。而不是做 interearaction.reply 你应该做interaction.editReply。
我认为这应该可以解决问题。
关于 4O5 方法错误,当我更正语法并切换到 djs 14 时,它已为我解决。