discord.py 处理多个异常
Posted
技术标签:
【中文标题】discord.py 处理多个异常【英文标题】:discord.py handling multiple exceptions 【发布时间】:2019-08-30 04:25:36 【问题描述】:在我的 try 块中,我添加了 2 个例外。一个如果机器人没有权限,另一个例外是其他一切。但是,下面的代码没有显示权限错误的异常,而是使用了另一个。
@commands.command(no_pm=True)
async def mal(self, *, srch=None):
try:
if srch is None:
await self.Nao.say('You need to provide an anime name')
return
if " " in srch:
srch.replace(" ", "/")
url = 'https://api.jikan.moe/v3/search/anime/?q=' + srch + '&page=1'
response = requests.get(url)
data = response.json()
malEmbed = discord.Embed(title=data['results'][0]['title'], description=data['results'][0]['synopsis'], url=data['results'][0]['url'], color=0xff00ff)
malEmbed.set_thumbnail(url=data['results'][0]['image_url'])
malEmbed.add_field(name='Episodes: ', value=data['results'][0]['episodes'])
malEmbed.add_field(name='Rated: ', value=data['results'][0]['rated'])
await self.Nao.say(embed=malEmbed)
except PermissionError:
await self.Nao.say('I need permission to embed links to do this.')
return
except:
await self.Nao.say('There was an error. My developers have been alerted!')
我已删除机器人嵌入链接的权限,这意味着它应该响应 PermissionError
的异常但返回“出现错误。我的开发人员已收到警报!”而是。
【问题讨论】:
你使用的是哪个 discord.py? 另外,你能提供一个完整的工作示例吗? requests 目前还没有定义,所以对我来说,这个错误取代了 PermissionError (在这个错误发生之前,机器人从不尝试嵌入链接)。当您使用命令扩展时,我还建议您查看以下帖子:***.com/questions/48612603/… 它是处理权限和异常的更好方法 imo 那是 async 分支,该命令的工作原理就是我所说的错误 【参考方案1】:您应该制作一个带有角色 ID 的权限列表:
administrative_roles = [ 856116059912011777 , 924800792773398548 , 929356299777490994]
然后像这样进行检查:
for arole in administrative_roles:
if arole in [role.id for role in ctx.author.roles]:
(your command)
else:
await.ctx.channel.send('No enaugh permission')
【讨论】:
【参考方案2】:我已找到该错误的修复方法。而不是让它尝试并抓住没有许可。我首先检查了机器人的权限,如果它有权限,它将运行重置,如果没有,它将直接跳转到 else 语句
@commands.command(pass_context=True, no_pm=True)
async def mal(self, ctx, *, srch=None):
if ctx.message.server.me.server_permissions.embed_links:
try:
if srch is None:
await self.Nao.say('You need to provide an anime name')
return
if " " in srch:
srch.replace(" ", "/")
url = 'https://api.jikan.moe/v3/search/anime/?q=' + srch + '&page=1'
response = requests.get(url)
data = response.json()
malEmbed = discord.Embed(title=data['results'][0]['title'], description=data['results'][0]['synopsis'], url=data['results'][0]['url'], color=0xff00ff)
malEmbed.set_thumbnail(url=data['results'][0]['image_url'])
malEmbed.add_field(name='Episodes: ', value=data['results'][0]['episodes'])
malEmbed.add_field(name='Rated: ', value=data['results'][0]['rated'])
await self.Nao.say(embed=malEmbed)
except:
await self.Nao.say('There was an error. My developers have been alerted!')
else:
await self.Nao.say('I need permission to embed links to do this.')
【讨论】:
以上是关于discord.py 处理多个异常的主要内容,如果未能解决你的问题,请参考以下文章
传递真实成员时出现discord.py MemberNotFound异常
如何在 discord.py 库中设置多个前缀或使前缀不区分大小写?
使用 Discord.py 在有权限的情况下发送嵌入频道会引发异常