How to Set up a HTTP Endpoint for Your Python Discord Bot

Setting up an HTTP Endpoint is how your Discord bot gets a public internet address to receive special data directly from Discord. This is essential for features like Slash Commands and message Buttons, giving Discord a secure place to send instructions when users interact with your bot.


Packages:

  • discord.py: Z Python library for building bots and interacting with the Discord API using commands and events.
  • Flask: Used to create the minimal web server and define the /interactions endpoint.
  • PyNaCl: Used to handle cryptographic tasks, specifically verifying the security signatures from Discord.

Getting a Discord Public Key:

  1. Log In to the Discord Developer Portal
  2. Select your application
  3. Scroll to “PUBLIC KEY” then select the ‘Copy’ button

Discord Developer Portal, PUBLIC KEY is highlighted

1. Log In to Your Panel


2. Select the ‘Files’ Tab

Cybrancee Panel in the files page, "Files" tab on the sidebar is highlighted

3. Create index.py

This file will create a web server (using Flask) and handles the Discord security check and the PING/PONG test.

Paste the following code into the file:

import os
from flask import Flask, request, jsonify, abort
from nacl.signing import VerifyKey
from nacl.exceptions import BadSignatureError

PUBLIC_KEY = "YOUR_DISCORD_PUBLIC_KEY_HERE"
verify_key = VerifyKey(bytes.fromhex(PUBLIC_KEY))
app = Flask(__name__)

@app.route('/interactions', methods=['POST'])
def discord_interactions():
    signature = request.headers.get('X-Signature-Ed25519')
    timestamp = request.headers.get('X-Signature-Timestamp')
    body = request.data.decode('utf-8')

    try:
        verify_key.verify(f'{timestamp}{body}'.encode(), bytes.fromhex(signature))
    except BadSignatureError:
        abort(401) 

    data = request.json
    if data and data.get("type") == 1:
        return jsonify({"type": 1}) 

    return jsonify({"type": 4, "data": {"content": "Command received!"}}) 
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)

Ensure that the port number is the same as your server’s port.


4. Get your Public URL and Register in Discord

Once you’ve hosted your web server, ensure your web server must be running on https not http.

  1. Copy https://example.com/interaction
  2. Go back to the Discord Developer Portal, then your application.
  3. Paste your copied URL into the “INTERACTIONS ENDPOINT URL” then save changes

Discord Developer Portal, in the GENERAL tab of an application. PUBLIC KEY and SAVE CHANGES are highlighted

Discord Bot Hosting

Starts at $1.49

External link icon
Was this article helpful?
Please Share Your Feedback
How Can We Improve This Article?
Table of Contents