Discord.py: how to create a custom function notify and call trigger the discord client to invoke it

Viewed 217

I want to ask a discord client to execute a specific function WITHOUT being triggered by an on message, or on ready or having a LOOP that repeats itself.

Basically, I want a function notify(msg) and make the discord client send a message to a channel

I have tried with the following without success

async notify(message, client):
    await client.wait_until_ready()
    channel = client.get_channel(os.getenv('CHANNEL_ID'))
    await channel.send(message)

client.run(os.getenv('CLIENT_TOKEN'))

# Notice that I try to run the task after the client run
# Because I may call notify multiple times after the client has been created

client.loop.create_task(notify())

I want to invoke this function after the client has been created and without looping indefinitely.

Tried also to run

asyn def main():
    await client.connect()
    await client.log(client.run(os.getenv('CLIENT_TOKEN')))
    await notify('My message', client)

# then

if __name__ = "__main__":
  asyncio.run(main())

This just doesnt run ... having errors with http requests and so on.

2 Answers
client.loop.create_task(notify(*args))

That pass the function to be executed in the client's loop and will be called only once whenever you want to.

What I was looking for are webhooks. The role of the client is to act on predefined events (like on start, on message received ... etc). If we want to trigger something externally, Discord provides webhooks:

https://discordpy.readthedocs.io/en/stable/api.html?highlight=webhooks#discord.TextChannel.webhooks

Basically webhooks are unique urls for discord channels to which we can send data, the minimal data is of the form {'content': "my message} which sends a simple message. You can improve this further by including embeds.

Here is an basic example using aihttp

from discord import Webhook, AsyncWebhookAdapter
import aiohttp

async def foo():
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('url-here', adapter=AsyncWebhookAdapter(session))
        await webhook.send('Hello World', username='Foo')

And here another example using Requests library

import requests
from discord import Webhook, RequestsWebhookAdapter

webhook = Webhook.partial(123456, 'abcdefg', adapter=RequestsWebhookAdapter())
webhook.send('Hello World', username='Foo')
Related