Start working on server backend, create main bot class

pull/72/head
Stijn De Clercq 2021-06-14 23:33:53 +02:00
parent 0439b634d9
commit 92a5e6454d
3 changed files with 117 additions and 21 deletions

46
backend/server.py 100644
View File

@ -0,0 +1,46 @@
import json
from discord.ext import ipc
from quart import Quart, jsonify, request
from quart_cors import cors
from time import time
app = Quart(__name__)
# TODO allow_origin=re.compile(r"http://localhost:.*")
# needs higher Python & Quart version
app = cors(app, allow_origin="*")
app.config.from_object(__name__)
ipc_client = ipc.Client(secret_key="SOME_SECRET_KEY")
@app.route("/ping", methods=["GET"])
async def ping():
"""
Send a ping request, monitors bot latency, endpoint time, and PSQL latency
"""
latency = await ipc_client.request("get_bot_latency")
return jsonify({"bot_latency": latency, "response_sent": time()})
@app.route("/dm", methods=["POST"])
async def send_dm():
"""
Send a DM to the given user
"""
data = json.loads((await request.body).decode('UTF-8'))
dm = await ipc_client.request(
"send_dm",
user=int(data["userid"]),
message=data.get("message")
)
return jsonify({"response": dm})
if __name__ == "__main__":
app.run()

25
cogs/ipc.py 100644
View File

@ -0,0 +1,25 @@
from discord.ext import commands, ipc
class IPC(commands.Cog):
def __init__(self, client):
self.client = client
@ipc.server.route()
async def send_dm(self, data):
print("got here")
user = self.client.get_user(data.user)
await user.send(data.message)
print("sent")
return True
@ipc.server.route()
async def get_bot_latency(self):
"""
Get Didier's latency
"""
return str(round(self.client.latency * 1000))
def setup(client):
client.add_cog(IPC(client))

View File

@ -1,33 +1,58 @@
import discord
from discord.ext import commands
from discord.ext import commands, ipc
from dotenv import load_dotenv
from functions.prefixes import get_prefix
import os
load_dotenv(verbose=True)
class Didier(commands.Bot):
"""
Main Bot class for Didier
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# IPC Server
# TODO secret key
self.ipc = ipc.Server(self, secret_key="SOME_SECRET_KEY")
# Cogs that should be loaded before the others
self.preload = ("ipc", "utils", "failedchecks", "events",)
# Remove default help command
self.remove_command("help")
self.init_extensions()
def init_extensions(self):
# Load initial extensions
for ext in self.preload:
self.load_extension(f"cogs.{ext}")
# Load all remaining cogs
for file in os.listdir("./cogs"):
if file.endswith(".py") and not (file.startswith(self.preload)):
self.load_extension("cogs.{}".format(file[:-3]))
async def on_ipc_ready(self):
print("IPC server is ready.")
async def on_ipc_error(self, endpoint, error):
print(endpoint, "raised", error)
# Configure intents (1.5.0)
intents = discord.Intents.default()
intents.members = True
if __name__ == "__main__":
load_dotenv(verbose=True)
client = commands.Bot(command_prefix=get_prefix, case_insensitive=True, intents=intents)
# Configure intents (1.5.0)
intents = discord.Intents.default()
intents.members = True
# Remove default help because it sucks & I made my own
client.remove_command("help")
client = Didier(command_prefix=get_prefix, case_insensitive=True, intents=intents)
# Load utils first so it can be used in other places & it's not None
client.load_extension("cogs.utils")
client.load_extension("cogs.failedchecks")
client.load_extension("cogs.events")
# Get the token out of the file & run the bot
with open("files/client.txt", "r") as fp:
token = fp.readline()
# Load all remaining cogs
for file in os.listdir("./cogs"):
if file.endswith(".py") and not (file.startswith(("utils", "failedchecks", "events"),)):
client.load_extension("cogs.{}".format(file[:-3]))
# Get the token out of the file & run the bot
with open("files/client.txt", "r") as fp:
token = fp.readline()
client.run(token)
client.ipc.start()
client.run(token)