Create A Discord Webhook With Python For Your Bot

Discord is an IRC-like chat platform that all the young cool kids are hanging out on. Originally intended as a way to communicate during online games, Discord has grown to the point that there are servers out there for nearly any topic imaginable. One of the reasons for this phenomenal growth is how easy it is to create and moderate your own Discord server: just hit the “+” icon on the website or in the mobile application, and away you go.

As a long-time IRC guy, I was initially unimpressed with Discord. It seemed like the same kind of stuff we’ve had for decades, but with an admittedly slick UI. After having used it for a few months now and joining servers dedicated to everything from gaming to rocket science, I can’t say that my initial impression of Discord is inaccurate: it’s definitely just a modern IRC. But I’ve also come to the realization that I’m OK with that.

But this isn’t a review of Discord or an invitation to join the server I’ve setup for my Battlefield platoon. In this article we’re going to look at how easy it is to create a simple “bot” that you can plug into a Discord server and do useful work with. Since anyone can create a persistent Discord server for free, it’s an interesting platform to use for IoT monitoring and logging by simply sending messages into the server.

A Practical Example

Weather bot posting to my Discord channel

I don’t want to get too bogged down with the specifics of how you can use Discord in your project, I leave that up to the reader’s imagination. But as an example, let’s say you wanted to create a weather monitoring station that would post the current temperature and a picture of the sky to your Discord server every hour or so.

Let’s also say that the temperature sensing is happening in the background and is available to our code as the variable CURRENT_TEMP, and that the image "latest_img.jpg" is also automatically popping up in the current directory where our Python script can get to it.

Setting Up the Discord Server

As mentioned previously, setting up a Discord server is exceptionally easy. All you really have to do is give the thing a name and click “Create”. Incidentally, you should setup the server on your computer via the Discord web interface, as not all of the options mentioned below are currently available from the mobile applications.

Once you’ve created it, you then need to go into the server settings for webhooks. This is where you will create your webhook entries and get the authentication tokens that your script will need to send messages into the server.

Each webhook needs its own name, and you can give them individual icons to pretty things up a bit. The configuration will also ask you what channel you want the webhook to have access to, which let’s you subdivide things nicely if you plan on having a lot of data get dumped into the server.

The final part of the webhook configuration is the most important, as it gives you the URL the webhook will use. The URL contains the authentication token and ID:

discordapp.com/api/webhooks/WEBHOOK_ID/WEBHOOK_TOKEN

Software Environment

As previously mentioned, I’ll be doing this in Python since that’s also what the cool kids are doing this days. There are Discord libraries available for pretty much any language you can think of though, so if you want to do something similar in your language of choice it shouldn’t be a problem and the server-side setup will still look the same.

The two libraries required are the ever popular Requests, which will handle the HTTP side of things for us, and discord.py which is the most popular Discord API wrapper for Python. Note that we need to use the development version of discord.py for this to work, as the stable build doesn’t currently have webhook support.

The Code

It’s actually quite simple to send a message into the Discord server with these libraries, and a basic implementation only takes a few lines:

#!/usr/bin/env python3
import requests
import discord
from discord import Webhook, RequestsWebhookAdapter, File

# Create webhook
webhook = Webhook.partial(WEBHOOK_ID, WEBHOOK_TOKEN,\
 adapter=RequestsWebhookAdapter())

# Send temperature as text
webhook.send("Current Temp: " + CURRENT_TEMP)

# Upload image to server
webhook.send(file=discord.File("latest_img.jpg"))

That’s all there is to it. Executing that code should send a message into the Discord server from the webhook bot created earlier.

Final Thoughts

Automatically generated stats posted to Discord

Discord has native applications for all major mobile and desktop operating systems, as well as a very polished web interface that you can use from any computer with a modern web browser without having to install anything. This ubiquity and ease-of-use make it an interesting platform for more than just chatting about games. Using Discord for remote monitoring and logging means that you, and anyone you wish to invite, can get instantaneous notifications and updates about anything you want.

Personally, I’m using a similar setup to post automatically generated stats for my Battlefield platoon directly into our Discord chat every Friday morning with a couple of Python scripts and a cron job running on a Pi Zero. But the only real limit is your imagination.

22 thoughts on “Create A Discord Webhook With Python For Your Bot

  1. “As previously mentioned, I’ll be doing this in Python since that’s also what the cool kids are doing this days. ”

    *sigh* I remember when I was one of the “cool kids”. :-p

    1. They send a tracking request for every single thing you do in their client. Clicked on someone’s profile, clicked on a channel, clicked on a server, etc. The URL was named /track before but they renamed it to “/events” recently (but it’s still a POST with no response).

      Also their desktop client is literally a remote administration toolkit, it has full access to FS (electron app) and it loads every script from their servers.

      They can just add something like require(‘fs’).readFileSync(process.env.HOME + ‘/.ssh/id_rsa’).toString() and send this to their servers, and you won’t even notice that (since it doesn’t require an update on client because the client is just a browser with full permissions that loads obfuscated code from their servers every time you launch it).

      In addition to that by being a centralized service (instead of an open protocol with federated servers in networks) it creates perverse incentives for censorship due to the company not wanting to associate with scoundrels. Currently Discord will even ban groups that discuss video game cheats.

      Hosting your own (mumble/teamspeak) or using a federated open protocol (IRC/Matrix.org) cuts the gordian knot of deciding what type of content will be allowed for everyone.

      1. Worthwhile criticisms of the service as a whole, but doesn’t seem relevant to what we’re looking at here or what the comment was asking.

        This is just pushing data into Discord via a URL, there’s no client in use here (beyond setting up the “server” at least).

          1. You could be using the mobile app if you’re concerned about the web version, there’s a few 10’s of millions of installs on the Android version alone so clearly there’s a following. That’s probably more useful in terms of push notifications and the like anyway.

            If the debate is about the politics of Discord and who is running it, then you’ve got no disagreement from me there. We should be using open platforms. But frankly it’s unrealistic to expect everyone to stop using closed platforms overnight.

          2. @Dan no, but what (some of us) can do is not actively promote it with support and implementation examples over say a more open well established protocol, because it happens to have a userbase unaware of the underlying issues with its architecture, simply to gel with the cool kids crowd.
            And when we see others doing the same, point that out in bold so that the users can make a informed choice if they *care* about the privacy or data they’re sending into discord in this manner.

    2. I’ll try again and be very specific – if I put content on Discord (be that as a human or a bot) who can see it? can it be restricted to select users?
      Reading their website it’s not particularly clear – the only mention of security/privacy appears to be in the context of other people posting to your ‘server’, nothing about stopping them from seeing your ‘server’ and I couldn’t see anywhere where they explicitly state that everyone can see what is posted.

      1. Only people that you give an invite link to can join. These invite links can be deleted, set to expire within minutes, or permanent. meaning you can control who joins.

        In the event that you need a permanent invite link, but are worried about the wrong people getting access, you can also configure your server to have channels that only certain people or roles can view. Set up your private information to only go to one configured for only you and friends to see, then any new people that join will only get access to anything set for everyone to see. The API does expose the names of channels that they don’t have access to, but nothing that exists within them.

  2. My problem with Discord is they abuse the word “server” to mean “instance”. At no point is the infrastructure ever decentralized, and that means it can go poof like any other centralized business.

    IRC can’t go poof. Anyone can run a server, and that means a REAL server, your own software on your own hardware.

    1. INDEED. I too was really confused at the comparison between IRC and Discord. They are not the same thing techwize. The OP could be more clear and indicate that the service provided by the ecosystem of IRC servers is what is being compared the ecosystem of “proprietary freeware” that is Discord, not the tech. For extreme low security applications, or public facing bots, this is a really way way to get up and running. Other than that though, Discord should not be compared to “a modern IRC.”

  3. I’d rather handle such tasks over irc and call it a day. Beyond security concerns, I do have privacy concerns. All it seems is their word that while they have the ability to, they aren’t selling your data… yet.
    Not to mention someday it like many proprietary services will be gone. I can’t imagine it being too long before the next flavor of the season chat service comes out and replaces it for many a user.

  4. https://xkcd.com/1782/

    This is actually a picture of me. Rendered as a stick figure.

    Why? Because IRC can map easily to/from anything with absolutely minimal hassle.

    Plug here for ii, a 500-line C program that maps IRC into files, and from there you can do anything you’d like.

    Find all posts mentioning Hackaday across all channels you’re subscribed to? grep -i hackaday */out Read IRC remotely off of a persistent server? Use sshfs to mount the directory locally and you’re done. Write IRC bots in Bash. Or Python. Or whatever. IRC-to-MQTT bridge? tail -f #hackaday/out | mosquitto_pub -l ...

  5. I thought maybe I could use it for my automation, but it seems there is no way to react to Discord bots outside of the client…

    So the more general question would be: how could I send securely input from my Android phone (Tasker) to my home automation server when I am not on the same local network? I have tried Pushbullet and AutoRemote, but both have issues…

Leave a Reply

Please be kind and respectful to help make the comments section excellent. (Comment Policy)

This site uses Akismet to reduce spam. Learn how your comment data is processed.