'Discord.py run after close

I am just trying to write a simple "send message" function using Discord.py but I am battling a lot.

If you comment out send_something('second') then this works perfectly. But if you use this function twice then you get the RuntimeWarning.

def send_something(message):
    client = discord.Client()
    @client.event
    async def on_ready():
        connection = await client.fetch_user(USER_ID)
        await connection.send(message)
        await client.close()

    client.run(TOKEN)

# You can run the first one, but you can't run both
send_something('first') 
send_something('second') # RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited

Then I tried making it an async function, adding await, in which case you now have to "wait" for the outside function in some way. So I did this:

async def send_something(message):
    client = discord.Client()
    @client.event
    async def on_ready():
        connection = await client.fetch_user(USER_ID)
        await connection.send(message)
        await client.close()

    await client.run(TOKEN)

# No error but no message gets sent
asyncio.ensure_future(send_something('first'))
asyncio.ensure_future(send_something('second'))

Now there is no error, but the messages never get sent. I'm guessing the script ends and "closes" before the work is finished?

Any idea how I can write some kind of "send message" function? Because all the discord.py examples I find are based on waiting for "events" which is not what I need here.



Solution 1:[1]

The best option is to create a post request to discord api:

Code:

headers = {'Authorization': 'Bot %s' % YOUR_BOT_TOKEN } dm = requests.post(url='https://discord.com/api/v6/users/@me/channels', headers=headers, json={"recipient_id": RECEIVER_ID}).json() requests.post(f"https://discord.com/api/v6/channels/{dm['id']}/messages", headers=headers, json={"content": "Hello!"})

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