2

Goal: I'm trying to handle POST requests from Trello webhooks, then send an embed with relevant data on a discord guild.

Current Progress: I got handling POST requests done, and I know how to send an embed and such. However, when it finally got to a point where I need to implement the two together, I realized it wouldn't be possible to just py trelloHandler.py and they both start running. I did some research and found someone asking a similar question. To most people this would be helpful, though I am pretty new to python (I like working on projects to learn) and not sure how I'd implement threading. I did manage to find a guide over on realpython.com, but I'm failing to understand it.

My Question (TL;DR): How can I run an HTTP server that will listen to post requests in the same program as a discord.py bot (more specifically, using threading)?

My Code ("bot_token_here" is replaced with my discord token):

import discord
import json
from http.server import HTTPServer, BaseHTTPRequestHandler
from discord.ext import commands

client = commands.Bot(command_prefix = "~")

class requestHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        # Interpret and process the data
        content_len = int(self.headers.get('content-length', 0))
        post_body = self.rfile.read(content_len)
        data = json.loads(post_body)

        # Action and Models data
        action = data['action']
        actionData = action['data']
        model = data['model']

        # Board and card data
        board = action['data']['board']
        card = action['data']['card']

        # Member data
        member = action['memberCreator']
        username = member['username']

        # Keep at end of do_POST
        self.send_response(204)
        self.send_header('content-type', 'text/html')
        self.end_headers()

    def do_HEAD(self):
        self.send_response(200)
        self.end_headers()

@client.event
async def on_ready():
    print("Bot is online, and ready to go! (Listening to {} servers!)".format(len(list(client.guilds))))

def main():
    PORT = 9090
    server_address = ('localhost', PORT)
    server = HTTPServer(server_address, requestHandler)
    server.serve_forever()
    client.run("bot_token_here")

if __name__ == '__main__':
    main()
Zander
  • 123
  • 1
  • 2
  • 14
  • I'm not too sure what you want to do, but ```server_address = ('localhost', PORT)``` should be ```server_address = ('localhost:', PORT)``` –  Jun 17 '20 at 04:18
  • The HTTP server works perfectly fine without changing that. – Zander Jun 17 '20 at 04:21
  • You might find [this](https://stackoverflow.com/questions/52336409/discord-py-rewrite-basic-aiohttp-webserver-in-a-cog) helpful. By rule of thumb you don't bring threading & async together. – InsertCheesyLine Jun 17 '20 at 16:28

0 Answers0