How to use Discord bot to print messages while waitig for user input

Viewed 82

I wanted to make a bot that I can chat with my friends through the bot without needing to open discord. I tried sending messages by getting user input but while waiting for the input it can't print my friends messages at the same time. I tried to use threading but it doesn't seem to work.

Is there any way to do this? ,this is my code.

import discord

client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    username = str(message.author).split('#')[0]
    usermessage = str(message.content)
    channel = str(message.channel.name)
    while True:
        if message.author == client.user:
            return
        print(username,':',usermessage)
        answer = input('You: ')
        await message.channel.send(answer)
        if usermessage == message.content:
            return
        
              
client.run('TOKEN')

If someone sends stacked messages before I reply it can only get one reply per message I send. Is there any way for it to keep printing messages from discord before I reply?

1 Answers

Try with something like this:

@Bot.command()
async def command(ctx):
    for i in range(10):
        await ctx.send("ping")
        try:
            message = await Bot.wait_for('message', check=lambda message: message.author == ctx.author, timeout=10.0)
        except asyncio.TimeoutError:
            continue

If you want to do it through the shell, you can try this:

@Bot.command()
async def chat(ctx):
    message = ctx.message
    while true:
        print(ctx.message.content)
        answer = input()
        await message.reply(answer)
        message = Bot.wait_for('message')
        if (message.content == 'stop'):
            return

You can recieve more than a message in a row using this:

while True:
    while True:
        try:
            message = Bot.wait_for('message', timeout=20.0) # you can use a function argument instead of 20.0
        except TimeoutError:
            pass
        if message != None:
            print(message.content)
            if message.content == "stop":
                await ctx.send("The chat has ended")
                return
        else:
            await ctx.send("The time is over, wait for an answer")
            break
    await message.reply(input())
    del message
        
Related