将数据发送到 Discord webhook

Fab*_*Job 1 python urllib2 webhooks python-2.7 discord

在不使用 requests 模块的情况下,如何将消息发送到 Discord webhook?我尝试过以下代码:

import urllib2
import json

url = 'webhook url'
values = {"username": "Bot", "text": "This is a test message."}

data = json.dumps(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
Run Code Online (Sandbox Code Playgroud)

这将返回以下错误:

urllib2.HTTPError: HTTP Error 403: Forbidden
Run Code Online (Sandbox Code Playgroud)

Tal*_*man 5

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

  1. 使用本教程制作一个discord webhook 。

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

  3. 使用该discord.Webhook.send方法通过webhook.

如果您使用的是Discord.py的版本 2 ,此代码片段将适合您:

from discord import SyncWebhook

webhook = SyncWebhook.from_url("your-url")
webhook.send("Hello")
Run Code Online (Sandbox Code Playgroud)

如果您不使用版本 2,您可以使用以下代码片段:

import requests
from discord import Webhook, RequestsWebhookAdapter

webhook = Webhook.from_url("youre-url", adapter=RequestsWebhookAdapter())
webhook.send("Hello")
Run Code Online (Sandbox Code Playgroud)