在异步函数中使用递归
Using recursion in asynchronous functions
我的 Discord 机器人有一个 start
命令,我可以在其中检查用户是否已经在我的数据库中,如果没有(运行ning start
命令是第一次)我想要将此用户添加到我的数据库中。
这是我尝试过的想法:
client = commands.Bot(command_prefix = '/')
# define commands
@client.command()
async def start(ctx):
await start_command(ctx)
async def start_command(ctx):
user_id : int = ctx.message.author.id
result : int = does_user_exist(user_id) # returns 0 if no entry in database
if (result == 0):
print('Create user')
create_user(user_id)
await start_command(ctx)
else:
welcome_message = 'Welcome!'
await ctx.send(welcome_message)
我的想法是检查用户是否已经注册(=我的数据库中的条目)。如果他是,则消息被发送。为了避免 运行ning /start
两次,我尝试使用递归。
我的问题是用户不存在的情况。用户是用 create_user(user_id)
创建的,但递归没有按我预期的那样工作。在这种情况下,在机器人发送我的消息之前,我需要 运行 /start
第二次。
(这就是为什么我知道用户已创建,否则运行宁/start
第二次不会显示我的消息
我如何使用递归实现我的目标?
不要使用递归来实现循环,句号。
async def start_command(ctx):
user_id : int = ctx.message.author.id
while True:
result : int = does_user_exist(user_id)
if result != 0:
break
print('Create user')
create_user(user_id)
welcome_message = 'Welcome!'
await ctx.send(welcome_message)
根据 create_user
的可靠性,您根本不需要循环。
async def start_command(ctx):
user_id : int = ctx.message.author.id
result : int = does_user_exist(user_id)
if result == 0:
print('Create user')
create_user(user_id)
welcome_message = 'Welcome!'
await ctx.send(welcome_message)
我的 Discord 机器人有一个 start
命令,我可以在其中检查用户是否已经在我的数据库中,如果没有(运行ning start
命令是第一次)我想要将此用户添加到我的数据库中。
这是我尝试过的想法:
client = commands.Bot(command_prefix = '/')
# define commands
@client.command()
async def start(ctx):
await start_command(ctx)
async def start_command(ctx):
user_id : int = ctx.message.author.id
result : int = does_user_exist(user_id) # returns 0 if no entry in database
if (result == 0):
print('Create user')
create_user(user_id)
await start_command(ctx)
else:
welcome_message = 'Welcome!'
await ctx.send(welcome_message)
我的想法是检查用户是否已经注册(=我的数据库中的条目)。如果他是,则消息被发送。为了避免 运行ning /start
两次,我尝试使用递归。
我的问题是用户不存在的情况。用户是用 create_user(user_id)
创建的,但递归没有按我预期的那样工作。在这种情况下,在机器人发送我的消息之前,我需要 运行 /start
第二次。
(这就是为什么我知道用户已创建,否则运行宁/start
第二次不会显示我的消息
我如何使用递归实现我的目标?
不要使用递归来实现循环,句号。
async def start_command(ctx):
user_id : int = ctx.message.author.id
while True:
result : int = does_user_exist(user_id)
if result != 0:
break
print('Create user')
create_user(user_id)
welcome_message = 'Welcome!'
await ctx.send(welcome_message)
根据 create_user
的可靠性,您根本不需要循环。
async def start_command(ctx):
user_id : int = ctx.message.author.id
result : int = does_user_exist(user_id)
if result == 0:
print('Create user')
create_user(user_id)
welcome_message = 'Welcome!'
await ctx.send(welcome_message)