0

I wanted to combine a discord bot with a command line application. However, after the function fruit() is being called on startup, my discord bot commands will not work (no errors). The fruit() function will be runned infinitely after the bot is ran. Any code after client.run will not work. Any solutions to fix my code so that, upon running the script, activates the commands and run the bot, then run the main function forever?

from discord.ext import commands
token = "my token"
client = commands.Bot(command_prefix=">")

def fruit():
    option = input("Choose a fruit, 1 for banana, 2 for lime")
    if option == 1:
        print("Bananas are sweet")
        fruit()
    elif option == 2:
        print("Limes are sour")
        fruit()
    else:
        print("Invalid option")
        fruit()

@client.command()
async def sayhi(ctx):
    await ctx.send("Hi")

@client.event
async def on_ready():
    fruit()

client.run(token)```
  • 3
    Try some of the solutions for input [here](https://stackoverflow.com/questions/2408560/non-blocking-console-input). Also you might want to change the code so that you don't eventually hit a recursion limit. – duckboycool May 21 '21 at 19:41

1 Answers1

0

input is a blocking function (what does "blocking" mean), it blocks your whole thread until it finishes, you can use something like aioconsole.ainput or make your own non-blocking input function:

async def ainput(text):
    return await client.loop.run_in_executor(None, input, text)
    
async def fruit():
    option = await ainput("Choose a fruit, 1 for banana, 2 for lime")
    if option == '1': # `input` by default returns a string, so comparing to an integer will not work
        print("Bananas are sweet")
        await fruit()
    elif option == '2':
        print("Limes are sour")
        await fruit()
    else:
        print("Invalid option")
        await fruit()

@client.event
async def on_ready():
    await fruit()

One thing to take in note is that fruit is now a coroutine, it should be awaited.

Also as duckboycool said, you might wanna change your code a bit so you don't hit the recursion limit (a while loop will do the trick).

Łukasz Kwieciński
  • 14,992
  • 4
  • 21
  • 39