【问题标题】:Discord - Send message only from python app to discord channel (one way communication)Discord - 仅从 python 应用程序向不和谐通道发送消息(单向通信)
【发布时间】:2020-10-25 03:09:29
【问题描述】:

我正在设计一个应用程序,当我的 python 代码发生某些事情时(例如,我的网站上的新用户注册),我可以向我的不和谐频道发送通知。这将是一种单向通信,因为只有 python 应用程序才会向不和谐频道发送消息。

这是我尝试过的。

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")

问题是仅发送第一条消息(即 abc),然后 aysn 函数阻塞了第二个调用(def)。

我不需要收听不和谐事件,也不需要保持网络通信畅通。有什么方法可以让我在不监听事件的情况下将文本(我们通常使用的 api 的发布方法)发布到不和谐服务器?

谢谢。

【问题讨论】:

    标签: python bots discord python-asyncio discord.py


    【解决方案1】:

    我找到了。 “Webhook”就是答案。无需使用 discord.py,只需为您的频道创建一个 webhook,然后将数据发布到该端点。

    import requests
    
    #Webhook of my channel. Click on edit channel --> Webhooks --> Creates webhook
    mUrl = "https://discord.com/api/webhooks/729017161942******/-CC0BNUXXyrSLF1UxjHMwuHA141wG-FjyOSDq2Lgt*******************"
    
    data = {"content": 'abc'}
    response = requests.post(mUrl, json=data)
    
    print(response.status_code)
    
    print(response.content)
    

    【讨论】:

      【解决方案2】:

      您可以将消息发送到 Discord webhook。

      首先,make a webhook 在 Discord 频道中您要向其发送消息。

      然后,使用 discord.Webhook.from_url 方法从 Discord 提供的 URL 中获取 Webhook 对象。

      最后,使用 discord.Webhook.send 方法通过 webhook 发送消息。

      如果你使用的是 discord.py 的第 2 版,你可以使用这个 sn-p:

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

      否则,您可以使用requests 模块:

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

      【讨论】:

      • 这太棒了,是这个问题的完美答案,请记住 webhook 只能发布到频道,不能直接向用户发送消息等。
      【解决方案3】:

      这可能是最好的方法之一,因为它节省了添加更多 python 包(@john 提到的一个),但我相信对于这种情况有一个更强大和简单的解决方案,因为你可以添加图像,制作表格并使这些通知看起来更具表现力。

      python library 专门用于向 discord 服务器发送消息。 PyPI 页面中的一个简单示例是:

      from discord_webhook import DiscordWebhook
      
      webhook = DiscordWebhook(url='your webhook url', content='Webhook Message')
      response = webhook.execute()
      

      页面上有更多示例。

      This is how the sent notification/message would look like

      Discord notification with table

      【讨论】:

        猜你喜欢
        • 2020-04-07
        • 2021-03-24
        • 2020-12-23
        • 2021-01-10
        • 1970-01-01
        • 2023-03-07
        • 2020-04-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多