目标:我试图处理来自Trello webhooks的POST请求,然后在discord公会上发送一个带有相关数据的嵌入。
目前的进展。我完成了处理POST请求的工作 我也知道如何发送嵌入之类的东西了 然而,当终于到了我需要实现两个 一起我意识到这是不可能的,只是... py trelloHandler.py
他们都开始运行。我做了一些研究,发现 同道中人. 对大多数人来说,这将是有帮助的,尽管我是python的新手(我喜欢在项目中学习),不知道如何实现线程。我确实找到了一个 指南在realpython.com上但我无法理解。
我的问题 (TL;DR):我如何能运行一个HTTP服务器,在与discord.py机器人相同的程序中监听帖子请求(更具体地说,使用线程)?
我的代码("bot_token_here "用我的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()