Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discord - Send message only from python app to discord channel (one way communication)

I am designing an app where I can send notification to my discord channel when something happen with my python code (e.g new user signup on my website). It will be a one way communication as only python app will send message to discord channel.

Here is what I have tried.

import os
import discord
import asyncio


TOKEN = ""
GUILD = ""

def sendMessage(message):
    client = discord.Client()

    @client.event
    async def on_ready():


        channel = client.get_channel(706554288985473048)
        await channel.send(message)
        print("done")

        return ""


    client.run(TOKEN)
    print("can you see me?")


if __name__ == '__main__':

    sendMessage("abc")
    sendMessage("def")

The issue is only first message is being sent (i-e abc) and then aysn function is blocking the second call (def).

I don't need to listen to discord events and I don't need to keep the network communication open. Is there any way where I can just post the text (post method of api like we use normally) to discord server without listening to events?

Thanks.

like image 670
john Avatar asked Jul 04 '20 16:07

john


People also ask

How do I send a message to a Discord channel in Python?

How do I send a message to my channel Discord bot? Send DM's with the prefix command "! sendmsg <@member> <message>" or to a channel with "!

How do you make Discord bot send messages only on one channel?

How do you get Discord bots messages on one channel? At the moment, the only way to restrict bots to one channel only is to manually remove the bot's chat permissions in each channel that you don't want it in. The more channels you have in a server, the more tedious it becomes.

How do I send a message to Discord using API?

Under Method, select POST. Under Body Type, select Raw. Under Content Type, select JSON (application/json) Finally, under Request Content, type in the message to be sent to the channel as a JSON payload as per Discord's API.


1 Answers

You can send the message to a Discord webhook.

First, make a webhook in the Discord channel you'd like to send messages to.

Then, use the discord.Webhook.from_url method to fetch a Webhook object from the URL Discord gave you.

Finally, use the discord.Webhook.send method to send a message using the webhook.

If you're using version 2 of discord.py, you can use this snippet:

from discord import SyncWebhook

webhook = SyncWebhook.from_url("url-here")
webhook.send("Hello World")

Otherwise, you can make use of the requests module:

import requests
from discord import Webhook, RequestsWebhookAdapter

webhook = Webhook.from_url("url-here", adapter=RequestsWebhookAdapter())
webhook.send("Hello World")
like image 54
Ben Soyka Avatar answered Oct 06 '22 00:10

Ben Soyka