Python开发Discord机器人斜杠命令未在服务器列表显示的解决求助
解决Discord斜杠命令未显示及库缺失问题
一、关于discord-py-slash-command库的问题
- 这个库已停止维护,且discord.py从v2.0版本开始原生支持斜杠命令,无需额外安装第三方库。
- 若你之前安装该库失败,直接放弃它,确保discord.py版本为v2.0以上,执行以下命令安装/升级:
pip install -U discord.py
二、将现有命令改为官方斜杠命令
你的当前代码用@bot.command()实现的是前缀命令(输入/profile可触发,但不会出现在斜杠命令列表中),要实现官方斜杠命令,需修改代码如下:
修改后的完整代码
import discord from discord import app_commands from discord.ext import commands from PIL import Image, ImageDraw, ImageFont import requests import io intents = discord.Intents.default() intents.message_content = True intents.members = True bot = commands.Bot(command_prefix='/', intents=intents) # Bot就绪时同步斜杠命令 @bot.event async def on_ready(): print(f"已登录为 {bot.user}") # 全局同步(所有服务器生效,可能需1小时同步) # 如需即时同步到指定服务器,取消下方注释并替换GUILD_ID # await bot.tree.sync(guild=discord.Object(id=GUILD_ID)) await bot.tree.sync() print("斜杠命令已同步") # 定义斜杠命令 @bot.tree.command(name="profile", description="生成你的用户信息卡片") async def profile(interaction: discord.Interaction): # 延迟响应,避免Discord判定命令超时 await interaction.response.defer() size = (241, 241) # 确保card.png在脚本同目录 image = Image.open("card.png") img = image.resize((1100, 500)) # 获取用户头像URL url = interaction.user.avatar.url response = requests.get(url, stream=True) avatar = Image.open(io.BytesIO(response.content)) avatar = avatar.convert("RGBA") avatar = avatar.resize(size) mask = Image.new("L", size, 0) mask_draw = ImageDraw.Draw(mask) mask_draw.ellipse((0, 0) + size, fill=255) avatar_rounded = Image.new("RGBA", size) avatar_rounded.paste(avatar, (0, 0), mask=mask) img.paste(avatar_rounded, (430, 47), avatar_rounded) idraw = ImageDraw.Draw(img) name = interaction.user.name mem = interaction.guild.member_count # 确保font.ttf在脚本同目录 headline = ImageFont.truetype('font.ttf', size=60) undertext = ImageFont.truetype('font.ttf', size=45) idraw.text((180, 310), f'{name} Присоеденяется!', font=headline) idraw.text((420, 395), f"Участник №{mem}", font=undertext, fill=(173,173,173)) img.save("usercard.png") # 发送生成的卡片 await interaction.followup.send(file=discord.File(fp="usercard.png")) # 替换为你的Bot Token bot.run("YOUR_BOT_TOKEN_HERE")
三、关键修改说明
- 引入
discord.app_commands模块,用@bot.tree.command()替代@bot.command(),定义官方斜杠命令。 - 添加
on_ready事件,调用bot.tree.sync()同步命令,这是命令出现在服务器斜杠列表的核心步骤。 - 斜杠命令参数从
ctx改为interaction,需先用interaction.response.defer()延迟响应,再用followup.send()发送结果,避免Discord判定命令超时。 - 修复了头像获取逻辑,使用
interaction.user.avatar.url更稳定可靠。
四、其他注意事项
- 确保Discord开发者门户中,你的Bot已开启Message Content Intent和Server Members Intent,与代码中的intents配置对应。
card.png和font.ttf必须放在脚本同一目录,否则会报错找不到文件。- 若需仅在特定服务器即时同步命令,取消
on_ready中指定服务器的代码注释,替换GUILD_ID为目标服务器ID即可。
内容的提问来源于stack exchange,提问作者Olimpiia_ ART
相关产品推荐
相关产品推荐

