通过API向Discord用户发送DM,无需on_event或侦听器



我有一个应用程序,当我的Python代码出现问题时(例如,新用户在我的网站上注册),我想在其中向Discord用户(我或其他人)发送DM消息。我不需要听不和谐的事件,也不需要保持网络沟通的开放性。有没有什么方法可以让我在不监听事件的情况下将消息(像我们通常使用的api的post方法)发送到discord服务器?到目前为止,我已经能够使用webhook将其发送到一个频道(见下文)。但是,webhook不支持DM。

通道中webhook通知的代码:

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

您可以尝试将此函数实现为对事件的回调(webhook、API请求、计时器等)。
它将通过用户的id获取用户,如果不存在,可以选择创建DMChannel,并最终发送消息。

async def send_message(user_id, *args, **kwargs):
user = await client.fetch_user(user_id)
if user.dm_channel is None:
await user.create_dm()
await user.dm_channel.send(*args, **kwargs)

相关内容

最新更新