Home > front end >  Using recursion in asynchronous functions
Using recursion in asynchronous functions

Time:10-27

My Discord bot has a start command where I check if a user is already inside my database and if not (running start command for the first time) I want to add this user to my database.

Here is the idea I tried:

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)

My idea here was to check if the user is already registered (=entry in my database). If he is, message gets send. To avoid running /start twice I tried using a recursion.

My issue is in the case if the user does not exist already. The user gets created with create_user(user_id), but the recursion does not work as expected by me. I need to run /start a second time in this case before my message gets send by the bot.

(this is why I know that the user was created, otherwise running /start a second time wouldn't display my message

How would I achieve my goal using a recursion?

CodePudding user response:

Don't use recursion to implement a loop, period.

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)

Depending on how reliable create_user is, you won't need a loop at all.

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)
  • Related