'client.run("TOKEN") blocking issue (python & discord.py)

I know that client.run("TOKEN") blocks off any code following it...I'm trying to have my program print a message (in my case when a Nike product restocks), and then keep running and print another one when it picks up something again. How can I close/shut off my client.run("TOKEN") command so that my program can keep running?


else:
            print("NO RESTOCK FOUND...STILL MONITORING")

            client = commands.Bot(command_prefix = "!")

            channel = client.get_channel(ABCDEFG)
            await channel.send("NO RESTOCK FOUND...STILL MONITORING")

            client.run("TOKEN")

            time.sleep(0.5)

            client.close()



Solution 1:[1]

Instead of using client.run(), you can use await client.start(), which does not block the code.

import asyncio

async def client_start():
    await client.start('token.goes.here')

You can then call await client.start() in your function.


To send a message use message.channel.send('Message') or ctx.send('Message'), depending on if you are using an event or command.

Solution 2:[2]

i have a bot that require to send a signals every random time and some times i need to send messages bellow the client.run line , so i couldn't found any solution , the best way i found to send a messages in any place in the code in any time like this , using the basic URL request method :

all you need to change in this code is :

1/ line no 2 ( your channel id )

2/ line no 4 ( your channel Token ) or ( Bot Token if trying to send as bot )

3/ the_message = 'any message you want to send'

import requests
the_url = 'https://discord.com/api/v9/channels/your_channel_id/messages'


def send(the_message):
    TOKEN = 'Your_Bot_Token'
    header = {
        'authorization': f'Bot {TOKEN}',
    }

    payload = {
        'content': f'{the_message}',

        'author': {
            'pinned': True
        }
    }
    requests.post(the_url, data=payload, headers=header)


######### Calling the Function to send a message in any place in the code ^_^ #########

send(the_message='Hola')

you can call send function in any place in the code ^_^ .

Solution 3:[3]

You could import Threading and use the class Thread, basically make a function like:

def runClient():
    client.run("TOKEN")

and in that part that u want the client.run("TOKEN") to be run just do this: threading.Thread(target=runClient).start() this will create a thread that will run that function and will keep doing the rest after that function, hope this helps!!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eric Jin
Solution 2 Mr Dream
Solution 3 Tiago Oliveira