Discord webhook: simple Python script to post messages to a channel

August 25, 2016

You'll want to get a bot token at https://discordapp.com/developers/applications/me first. Create the application and the bot token, and authorise it with the client ID by adding it to your own server.

Set DISCORD_BOT_TOKEN="yourBotTokenFromTheApplicationsTab" as an environment variable when starting.

import requests
from flask import Flask, request, jsonify
import os
import json

app = Flask(__name__)

headers = {
    'User-Agent': 'discord-simple-webhook (0.0.1)',
    'Authorization': os.environ["DISCORD_BOT_TOKEN"],
    'Content-Type': 'application/json'

@app.route("/post_message", methods=['POST'])
def msg():
    d = json.dumps({'content': request.form['message']})
    r = requests.post('https://discordapp.com/api/channels/' + 
                      request.form['channel_id'] + '/messages', headers=headers, data=d)
    return jsonify(r.json())

if __name__ == "__main__":

You can then send a HTTP POST /post_message with the postdata message=Your+message+here&channel_id=00000000000. You can get your channel's snowflake ID by right clicking it and clicking Copy ID if you have Developer Mode enabled in Discord.

This is a really basic mini-webserver I use for local posting and doesn't do authentication as-is, so keep it listening locally or add some Flask middleware to do so.