使用Hikari Lightbulb开发Discord Bot发图片遇404/405错误求助
Discord Bot发送AI生成图片时的404/405错误解决
问题详情
开发Discord Bot时,通过AI生成图片并保存到本地后,使用SlashCommand发送图片时触发异常,报错信息如下:
hikari.errors.NotFoundError: Not Found 404: (10062)- Discord返回:
{"message": "405: Method Not Allowed", "code": 0}
已排除ctx.respond()的delete_after参数超时问题(默认值为None),推测是Discord端提前判定请求失败。相关代码:
# random input just generates a string from a list @bot.command @lightbulb.command('hampter','Generates Hampter Image with AI') @lightbulb.implements(lightbulb.SlashCommand) async def generate_image(ctx): response = openai.Image.create( prompt= randomInput() , n=1, size="512x512" ) image_url = response['data'][0]['url'] img_data = requests.get(image_url).content with open('temp.png', 'wb') as handler: handler.write(img_data) image = hikari.File(r'C:\filepath\temp.png') await ctx.respond(image)
解决办法
1. 跳过本地文件存储,直接用字节流发送
本地文件读写可能引发路径权限或解析问题,建议直接将下载的图片字节流包装成hikari.File发送,无需保存到本地:
from io import BytesIO @bot.command @lightbulb.command('hampter','Generates Hampter Image with AI') @lightbulb.implements(lightbulb.SlashCommand) async def generate_image(ctx): response = openai.Image.create( prompt= randomInput() , n=1, size="512x512" ) image_url = response['data'][0]['url'] img_data = requests.get(image_url).content # 用字节流创建文件对象,指定文件名 image = hikari.File(BytesIO(img_data), filename="hampter.png") await ctx.respond(image)
2. 先发送临时响应避免超时
Discord要求SlashCommand必须在3秒内返回初始响应,否则会判定请求失效返回404。如果图片生成或下载耗时较长,先发送临时提示,再编辑响应添加图片:
@bot.command @lightbulb.command('hampter','Generates Hampter Image with AI') @lightbulb.implements(lightbulb.SlashCommand) async def generate_image(ctx): # 先发送临时响应,抢占3秒窗口期 temp_msg = await ctx.respond("正在生成仓鼠图片,请稍候...") # 执行图片生成与下载逻辑 response = openai.Image.create( prompt= randomInput() , n=1, size="512x512" ) image_url = response['data'][0]['url'] img_data = requests.get(image_url).content image = hikari.File(BytesIO(img_data), filename="hampter.png") # 编辑临时响应,替换为图片 await temp_msg.edit(attachment=image)
3. 基础权限与版本检查
- 确保Bot在目标频道拥有发送消息和上传文件的权限
- 更新hikari与lightbulb到最新版本,避免旧版本的API兼容性问题
内容的提问来源于stack exchange,提问作者scrimdougy
相关产品推荐
相关产品推荐

