Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

bots - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a Discord webhook.

First, make a webhook in the Discord channel you'd like to send messages to. Here's the Discord help page for that.

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.

Here's an example using the requests module:

import requests
from discord import Webhook, RequestsWebhookAdapter

webhook = Webhook.from_url("url-here", adapter=RequestsWebhookAdapter())
webhook.send("Hello World")

In discord.py v2, the syntax has changed a bit

import requests
from discord import SyncWebhook

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...