在使用discord-ui和discord.py在Python中制作discord机器人时,我想制作一个命令来为特定角色执行特定的操作。就像如果我有
att_role
和 aot_role
,它会执行这两个角色的代码,如果我添加另一个像 est_role
这样的角色,它也会执行它的代码。我在这里使用 PyCharm 作为 IDE。
我是一名新手程序员,所以我不知道这是否是最好的方法,但是当我这样做时,我收到“应用程序没有响应”的错误。以下是它何时有效、何时无效:
当我有
att_role
时,即使我从列表中添加更多角色,它也能完美运行。如果我删除 att_role
并从列表中添加其他两个角色,它也适用于这些角色。如果我只有 rs_role
,它也适用。但是,如果我只有 aot_role
或只有 est_role
,我在不和谐频道中运行后会收到此错误:- The application did not respond
。如果我在其中添加任何其他角色,它会完美地工作。 它在我的 IDE(PyCharm) 中没有显示任何错误。
如果你没有正确理解我的意思,请告诉我最好的方法:为不同的角色制作不同的东西。
这是我的代码:
import discord
from discord.ext import commands
from discord_ui import UI, SelectOption, SelectMenu
import asyncio
# Clients
client = commands.Bot(' ')
client.remove_command('help')
ui = UI(client)
@ui.slash.command()
async def log(ctx):
"""Use this command to log trainings/tryouts"""
# These are the roles allowed to use this command
allowed_roles = [
'Advanced Trooper Training Section',
'Advanced Officer Training Section,',
'Recruiting Staff',
'Academy Instructor'
'Executive Sergeant Training Section',
'TB Bot Manager'
]
author_roles = ctx.author.roles
# If statement to check if the user can use this command
if any(role.name in allowed_roles for role in author_roles):
att_role = discord.utils.get(author_roles, name='Advanced Trooper Training Section')
aot_role = discord.utils.get(author_roles, name='Advanced Officer Training Section')
rs_role = discord.utils.get(author_roles, name='Recruiting Staff')
ai_role = discord.utils.get(author_roles, name='Academy Instructor')
est_role = discord.utils.get(author_roles, name='Executive Sergeant Training Section')
manager_role = discord.utils.get(author_roles, name='TB Bot Manager')
# Different stuff for different roles
if att_role is not None and att_role.name == 'Advanced Trooper Training Section':
await ctx.send('att') # Sample Stuff
if rs_role is not None and rs_role.name == 'Recruiting Staff':
await ctx.send('rs') # Sample Stuff
if ai_role is not None and ai_role.name == 'Academy Instructor':
await ctx.send('ai') # Sample Stuff
if est_role is not None and est_role.name == 'Executive Sergeant Training Section':
await ctx.send('est') # Sample Stuff
if manager_role is not None and manager_role.name == 'TB Bot Manager':
await ctx.send('manager') # Sample Stuff
if aot_role is not None and aot_role.name == 'Advanced Officer Training Section':
await ctx.send('aot') # Sample Stuff
client.run(TOKEN)
如果您的机器人在 3 秒内未响应交互,则交互将失败(尽管您的应用程序中不一定发生错误)。如果您知道需要更长的时间,您可以推迟。
在 Pycord 中,它位于 InteractionResponse.defer 下,但由于您没有提到您正在使用哪个库,所以我不知道您必须调用哪个方法。
你应该使用
await ctx.respond()
而不是
await ctx.send()
处理斜线命令时。如果这不起作用,那将是由于代码中的错误(它应该出现在终端中)
这里之前的答案建议使用
ctx.respond()
而不是 ctx.send()
,此解决方案将在当前版本的 discord.py
中引发错误:
改为使用:
await ctx.reply()
对于后来发现这个的人:
我用这段代码解决了这个问题
respond = discord.InteractionResponse(parent=ctx)
在命令的开头(在装饰器中包含 ctx: discord.Interaction
,即使它不使用上下文)
然后用命令回复
await respond.send_message(content="Example message")
您可以在文档中找到所有这些内容这里