使用discord.py开发Discord图片上传机器人遇链接生成故障求助
Discord机器人图片转Imgur链接功能故障排查与修复
我在用Python开发Discord机器人,目标是实现上传图片后生成对应的Imgur链接,但功能无法正常运行。执行/imgur命令上传图片后,仅在控制台打印了一串对象代码,没有返回预期的URL。
机器人相关截图:
演示动图:
原代码
import discord from discord.ext import commands from discord import Client from discord_slash import SlashCommand from discord_slash.utils.manage_commands import create_choice, create_option from discord_slash import SlashCommand, SlashContext #### bot = Client() intents = discord.Intents.all() bot = commands.Bot(command_prefix=['!','/','.'], description="ayuda bot") #Comando bot.remove_command("help") # Borra el comando por defecto !help slash = SlashCommand(bot, sync_commands=True) @slash.slash( name="imgur", description="imgur", options=[ create_option( name="image", description="Attach an Image", required=True, option_type=11, #Attachment )]) async def _imgur(ctx:SlashContext, image: discord.Attachment): print(image) @bot.event async def on_ready(): print("BOTS ready") bot.run("")
问题排查
- 核心逻辑缺失:原代码仅打印了
discord.Attachment对象,完全没有实现将图片上传到Imgur并获取URL的逻辑,这是功能失效的根本原因。 - 代码冗余:先实例化
Client()后又用commands.Bot覆盖,属于无效代码,会造成不必要的资源浪费。 - 缺少API集成:要实现图片上传,必须调用Imgur的API,原代码没有任何相关的网络请求逻辑。
修复方案
1. 获取Imgur API凭证
前往Imgur开发者平台注册一个应用,获取专属的CLIENT_ID,这是调用Imgur API的必要凭证。
2. 修复后的完整代码
import discord import requests from discord.ext import commands from discord_slash import SlashCommand, SlashContext from discord_slash.utils.manage_commands import create_option # 替换为你的Imgur Client ID IMGUR_CLIENT_ID = "你的Imgur Client ID" # 替换为你的Discord机器人Token DISCORD_BOT_TOKEN = "你的机器人Token" # 初始化Bot,正确配置intents intents = discord.Intents.all() bot = commands.Bot(command_prefix=['!', '/', '.'], description="ayuda bot", intents=intents) bot.remove_command("help") slash = SlashCommand(bot, sync_commands=True) @slash.slash( name="imgur", description="上传图片到Imgur并获取链接", options=[ create_option( name="image", description="选择要上传的图片", required=True, option_type=11 # Attachment类型 ) ] ) async def _imgur(ctx: SlashContext, image: discord.Attachment): # 校验上传文件是否为图片类型 if not image.content_type.startswith('image/'): await ctx.send("请上传图片格式的文件!") return try: # 读取Discord附件中的图片数据 image_data = await image.read() # 调用Imgur API上传图片 headers = {"Authorization": f"Client-ID {IMGUR_CLIENT_ID}"} data = {"image": image_data} response = requests.post("https://api.imgur.com/3/image", headers=headers, files=data) if response.status_code == 200: # 解析API返回结果,提取图片URL img_url = response.json()['data']['link'] await ctx.send(f"图片上传成功!链接:{img_url}") else: await ctx.send(f"上传失败,错误码:{response.status_code}") except Exception as e: await ctx.send(f"发生错误:{str(e)}") @bot.event async def on_ready(): print("机器人已就绪!") bot.run(DISCORD_BOT_TOKEN)
3. 代码说明
- 移除了冗余的
Client()实例化,正确配置并传递intents给commands.Bot - 添加图片类型校验,避免非图片文件上传
- 使用
requests库调用Imgur上传API,传入图片数据和身份凭证 - 解析API返回的JSON数据,提取图片链接并发送给用户
- 增加异常捕获,处理上传过程中可能出现的网络错误或API异常
内容的提问来源于stack exchange,提问作者paulita
相关产品推荐
相关产品推荐

