Discord用户审批机器人报错:无法导入InvalidArgument
Discord机器人导入错误:无法从'discord'导入'InvalidArgument'
问题详情
我正在开发一款用于Discord服务器的用户审批机器人,运行代码时触发导入错误,代码和报错信息如下:
机器人代码
import discord from discord_components import Button, DiscordComponents from discord.ext import commands import os import discord.ui from discord import ui intents = discord.Intents.all() intents.members = True bot = commands.Bot(command_prefix="/", intents=intents, help_command=None) DiscordComponents(bot) @bot.event async def on_ready(): print(f"Bot Ligado.") bot.add_view(Verify()) #---------------------------------------------------- class Questionare(ui.Modal, title="Solicitar SET"): qra = ui.TextInput(label="QRA:") patente = ui.TextInput(label="PATENTE:", placeholder="Aluno / Agente") async def on_submit(self, interaction: discord.Interaction): user = interaction.user guild = interaction.guild role = guild.get_role(1073616684763578398) if self.patente.value.lower() == "aluno": await user.edit(nick=f"Aln. {self.qra.value}") elif self.patente.value.lower() == "agente": await user.edit(nick=f"Agt. {self.qra.value}") channel = interaction.guild.get_channel(1078375134479515708) # canal de logs embed = discord.Embed(color=discord.Color.green()) embed.set_author(name="Novo Registro", icon_url="https://cdn-icons-png.flaticon.com/512/3804/3804348.png") embed.set_thumbnail(url=user.avatar.url) embed.add_field(name="QRA: ", value=user.mention, inline=False) embed.add_field(name="CARGO: ", value=self.patente.value , inline=False) # 改用原生View处理按钮 await channel.send(embed=embed, view=ApprovalView(user)) await interaction.response.send_message("Sucesso! Seja Bem-Vindo.", ephemeral=True) #---------------------------------------------------- class ApprovalView(discord.ui.View): def __init__(self, user): super().__init__(timeout=None) self.user = user @discord.ui.button(label="Aprovar", style=discord.ButtonStyle.success, custom_id="button1") async def approve(self, interaction: discord.Interaction, button: discord.ui.Button): # 可添加给用户分配角色的逻辑 await interaction.response.send_message(f"Usuário {self.user.mention} aprovado!", ephemeral=True) @discord.ui.button(label="Negar", style=discord.ButtonStyle.danger, custom_id="button2") async def deny(self, interaction: discord.Interaction, button: discord.ui.Button): # 可添加拒绝用户的逻辑(如踢人、发送提醒) await interaction.response.send_message(f"Usuário {self.user.mention} negado!", ephemeral=True) class Verify(discord.ui.View): def __init__(self): super().__init__(timeout = None) @discord.ui.button(label="Identifique-se", custom_id="Verify", style= discord.ButtonStyle.success) async def verify(self, interaction: discord.Interaction, button: discord.ui.Button): await interaction.response.send_modal(Questionare()) @bot.command() async def iniciar(ctx): embed = discord.Embed( title="INVESTIGAÇÕES PCERJ", description="Para ter acesso, identifique-se abaixo.", colour= 14483456 ) embed.set_thumbnail(url="https://i.pinimg.com/originals/8d/a3/ad/8da3ad9575652bba957033720f43434f.png") await ctx.send(embed = embed , view = Verify()) bot.run("TOKEN")
报错信息
PS C:\Users\negojha\Desktop\botteste> & C:/Users/negojha/AppData/Local/Programs/Python/Python311/python.exe c:/Users/negojha/Desktop/botteste/main.py Traceback (most recent call last): File "c:\Users\negojha\Desktop\botteste\main.py", line 2, in from discord_components import Button, DiscordComponents File "C:\Users\negojha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord_components\__init__.py", line 1, in from .client import * File "C:\Users\negojha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord_components\client.py", line 12, in from .component import Component File "C:\Users\negojha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord_components\component.py", line 3, in from discord import PartialEmoji, Emoji, InvalidArgument ImportError: cannot import name 'InvalidArgument' from 'discord' (C:\Users\negojha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\__init__.py)
错误原因
discord_components是第三方组件库,仅兼容旧版discord.py(v1.x)。而当前安装的是discord.py v2.x,在这个版本中,InvalidArgument已被迁移到discord.errors模块下,不再直接从discord根模块导出,导致discord_components导入失败。另外,代码中已经使用了discord.py v2.x特有的Modal功能(旧版v1.x不支持),所以降级discord.py并非可行方案。
解决方案
直接改用discord.py v2.x内置的原生UI组件系统,完全移除discord_components依赖:
- 删除代码中
from discord_components import Button, DiscordComponents和DiscordComponents(bot)两行 - 将原本用
discord_components.Button的逻辑,替换成discord.py原生的discord.ui.Button,并通过自定义View类管理按钮和点击回调 - 移除
bot.wait_for("button_click")的监听逻辑,改用View类中的按钮回调函数处理点击事件
上面的修改后代码已实现上述调整,同时修复了原代码中的小问题(如user.avatar需加.url获取图片链接、简化字符串判断逻辑、移除冗余参数等)。
内容的提问来源于stack exchange,提问作者Nêgo Jhá
相关产品推荐
相关产品推荐

