Fabulous Job
Fabulous Job

Reputation: 150

Send data to a Discord webhook

Without using the requests module, how can I send messages to a Discord webhook? I have tried following code:

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

This returns following error:

urllib2.HTTPError: HTTP Error 403: Forbidden

Upvotes: 1

Views: 19725

Answers (3)

Tal Folkman
Tal Folkman

Reputation: 2571

You can send the message to a Discord webhook.

  1. make a discord webhook with this tutorial.

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

  3. Use the discord.Webhook.send method to send a message using the webhook.

if you're using version 2 of discord.py, this snippet will work for you:

from discord import SyncWebhook

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

if you're not using version 2 you can use this snippet:

import requests
from discord import Webhook, RequestsWebhookAdapter

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

Upvotes: 5

Guy Nachshon
Guy Nachshon

Reputation: 2635

My first suggestion is the following steps:

  1. Make a webhook in the desired Discord channel.
  2. use the discord.Webhook.from_url method to fetch a Webhook object from the URL Discord gave you.
  3. use the discord.Webhook.send method to send a message.

another option is to use discord.py (v2) like this:

from discord import SyncWebhook

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

Upvotes: 0

Daemotron
Daemotron

Reputation: 121

Your data is not correct - according to the Discord API documentation, it should look like this:

values = {
    'username': 'Bot',
    'content': 'your message here'
}

Please note that one of content, file or embeds is required. Otherwise the API will not accept your request.

Upvotes: 1

Related Questions