我创建了一个异步函数add_reaction_tasks
,它将特定的函数Map到字典键,这个函数将字典返回到一个变量tasks
,这个变量位于事件on_raw_reaction_add
中。
第一个问题是tasks = await add_reaction_tasks()
会引发以下错误:line 343, in _run_event await coro(*args, **kwargs)
.
第二个错误是,当我尝试使用键which_trigger
和参数payload
访问由tasks
表示的字典时,出现以下错误:'1' : await add_rules_messages_tasks, TypeError: object function can't be used in 'await' expression
.
我已经确保在可能的情况下使用await
。除此之外,我不确定我还必须做些什么才能使这段代码工作。
代码片段:
1)add_reaction_tasks中使用的函数
def display_messages_error(payload = discord.RawReactionActionEvent):
...
async def add_rules_messages_tasks(payload = discord.RawReactionActionEvent):
...
async def add_years_messages_tasks(payload = discord.RawReactionActionEvent):
...
async def add_programming_languages(payload = discord.RawReactionActionEvent):
...
2)添加React任务函数
async def add_reaction_tasks():
add_tasks = {
'0' : display_messages_error,
'1' : await add_rules_messages_tasks,
'2' : await add_years_messages_tasks,
'3' : await add_programming_languages
}
return add_tasks
3)原始React添加事件时
@bot.event
@commands.bot_has_permissions(manage_roles = True)
async def on_raw_reaction_add(payload : discord.RawReactionActionEvent):
role = None
guild = None
# if the guild is server_name
if payload.guild_id == server_id:
guild = find(lambda g : g.id == server_id, bot.guilds)
member = get(guild.members, id = payload.user_id)
if not guild: return
if not member: return
which_trigger = 0 # 0 stands for invalid message id (should trigger display_message_error function)
try:
which_trigger = str(all_role_reaction_ids[str(payload.message_id)]) # <= looks weird, but works
#print(f'\nwhich_trigger = {which_trigger}\n')
except KeyError as err:
print(f'KeyError: {err}')
print('Invalid role-reaction message id')
return
tasks = await add_reaction_tasks() # <= first error
await tasks[which_trigger](payload) # <= second error
return
1条答案
按热度按时间vfh0ocws1#
即使字典中的最后三个函数是异步的,删除它们前面的
await
也会使它们正常工作,不会引发错误。但是,由于在它们之前没有使用
await
关键字,它们如何异步运行呢?工作代码