compartmentalize and properly implement REST API stuff,

and fixes for the accompanying  breaking changes in default plugins
master
cynic 3 years ago
parent 09f451ed39
commit cee3f1e465
  1. 14
      client.py
  2. 6
      default_plugins/authy.py
  3. 8
      default_plugins/hotload.py
  4. 22
      disc_api.py
  5. 2
      plugins/dango.py

@ -17,6 +17,7 @@ class client():
with open(config_path, "r") as conf_fd: with open(config_path, "r") as conf_fd:
self.config = json.loads(conf_fd.read()) self.config = json.loads(conf_fd.read())
self.plugman = plugin_manager(self.logger, plugin_path = self.config["plugin_path"]) self.plugman = plugin_manager(self.logger, plugin_path = self.config["plugin_path"])
self.api = disc_api.rest("https://discordapp.com/api", {"Authorization": "Bot {0}".format(self.config["token"]), "User-Agent": "mbdf (cynic.moe, v1)", "Content-Type": "application/json"})
async def shit(self): async def shit(self):
# https://discord.com/developers/docs/topics/gateway#connecting-to-the-gateway # https://discord.com/developers/docs/topics/gateway#connecting-to-the-gateway
# you're supposed to ask an HTTP endpoint what the ws gateway is but the docs didnt tell me the domain after 1sec so HAHA NOPE # you're supposed to ask an HTTP endpoint what the ws gateway is but the docs didnt tell me the domain after 1sec so HAHA NOPE
@ -63,19 +64,6 @@ class client():
except websockets.exceptions.ConnectionClosedOK: except websockets.exceptions.ConnectionClosedOK:
pass pass
def get_channel(self, id):
endpoint = f"https://discordapp.com/api/channels/{id}"
headers = {"Authorization": "Bot {0}".format(self.config["token"]), "User-Agent": "mbdf (cynic.moe, v1)", "Content-Type": "application/json"}
return requests.get(endpoint, headers = headers).text
def execute_webhook(self, link, message, name = "webhook"):
#it doesn't work without the headers for some reason
headers = {"Content-Type": "application/json"}
requests.post(link, headers = headers, data = json.dumps({"content": message, "username": name}))
def send_msg(self, id, message):
endpoint = f"https://discordapp.com/api/channels/{id}/messages"
# fstring wasn't working for the auth
headers = {"Authorization": "Bot {0}".format(self.config["token"]), "User-Agent": "mbdf (cynic.moe, v1)", "Content-Type": "application/json"}
res = requests.post(endpoint, headers = headers, data = json.dumps({"content": message}))
def __enter__(self): def __enter__(self):
return self return self
def __exit__(self, type, value, traceback): def __exit__(self, type, value, traceback):

@ -1,12 +1,12 @@
hooks = ["MESSAGE_CREATE"] hooks = ["MESSAGE_CREATE"]
def run(event, ctx, bot): def run(event, ctx, bot):
if ctx["content"].startswith(":") and not(int(ctx["author"]["id"]) in bot.config["authed"]): if ctx["content"].startswith(":") and not(int(ctx["author"]["id"]) in bot.config["authed"]):
bot.send_msg(ctx["channel_id"], "you lack the proper authentication") bot.api.send_msg(ctx["channel_id"], "you lack the proper authentication")
return return
if ctx["content"] == ":ops": if ctx["content"] == ":ops":
bot.send_msg(ctx["channel_id"], ", ".join([str(ident) for ident in bot.config["authed"]])) bot.api.send_msg(ctx["channel_id"], ", ".join([str(ident) for ident in bot.config["authed"]]))
elif ctx["content"].startswith(":op"): elif ctx["content"].startswith(":op"):
for mention in ctx["mentions"]: for mention in ctx["mentions"]:
bot.config["authed"].append(int(mention["id"])) bot.config["authed"].append(int(mention["id"]))
bot.send_msg(ctx["channel_id"], f"added {mention['username']} to the session authed!") bot.api.send_msg(ctx["channel_id"], f"added {mention['username']} to the session authed!")
bot.logger.write(f"added auth {mention['id']} {mention['username']}") bot.logger.write(f"added auth {mention['id']} {mention['username']}")

@ -2,19 +2,19 @@ from importlib import reload
hooks = ["MESSAGE_CREATE"] hooks = ["MESSAGE_CREATE"]
def run(event, ctx, bot): def run(event, ctx, bot):
if ctx["content"].startswith(":") and not(int(ctx["author"]["id"]) in bot.config["authed"]): if ctx["content"].startswith(":") and not(int(ctx["author"]["id"]) in bot.config["authed"]):
bot.send_msg(ctx["channel_id"], "you lack the proper authentication") bot.api.send_msg(ctx["channel_id"], "you lack the proper authentication")
return return
plugin_manager = bot.plugman plugin_manager = bot.plugman
if ctx["content"].startswith(":reload"): if ctx["content"].startswith(":reload"):
cmd = ctx["content"].split(" ")[1] cmd = ctx["content"].split(" ")[1]
if not(cmd in [m.__name__ for m in plugin_manager.plugins_loaded]): if not(cmd in [m.__name__ for m in plugin_manager.plugins_loaded]):
bot.send_msg(ctx["channel_id"], f"plugin {cmd} could not be found for reloading!") bot.api.send_msg(ctx["channel_id"], f"plugin {cmd} could not be found for reloading!")
else: else:
for m in plugin_manager.plugins_loaded: for m in plugin_manager.plugins_loaded:
if m.__name__ == cmd: if m.__name__ == cmd:
reload(m) reload(m)
bot.send_msg(ctx["channel_id"], f"reloaded plugin {cmd}!") bot.api.send_msg(ctx["channel_id"], f"reloaded plugin {cmd}!")
bot.logger.write(f"reloaded {cmd}") bot.logger.write(f"reloaded {cmd}")
elif ctx["content"] ==":plugins": elif ctx["content"] ==":plugins":
plugins = ", ".join([m.__name__ for m in plugin_manager.plugins_loaded]) plugins = ", ".join([m.__name__ for m in plugin_manager.plugins_loaded])
bot.send_msg(ctx["channel_id"], f"{plugins}") bot.api.send_msg(ctx["channel_id"], f"{plugins}")

@ -1,3 +1,5 @@
import requests, json
gateway_opcodes = { # https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-opcodes gateway_opcodes = { # https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-opcodes
0: "dispatch", 0: "dispatch",
1: "heartbeat", 1: "heartbeat",
@ -27,3 +29,23 @@ gateway_close_event_codes = { # https://discord.com/developers/docs/topics/opcod
4013: "You sent an invalid intent for a Gateway Intent. You may have incorrectly calculated the bitwise value.", 4013: "You sent an invalid intent for a Gateway Intent. You may have incorrectly calculated the bitwise value.",
4014: "You sent a disallowed intent for a Gateway Intent. You may have tried to specify an intent that you have not enabled or are not approved for." 4014: "You sent a disallowed intent for a Gateway Intent. You may have tried to specify an intent that you have not enabled or are not approved for."
} }
class rest():
def __init__(self, gatewa, header):
self.gateway = gatewa
self.headers = header
def get(self, endpoint):
return requests.get(self.gateway+endpoint, headers = self.headers).text
def post(self, endpoint, dat):
requests.post(self.gateway+endpoint, headers = self.headers, data = dat)
def get_channel(self, id):
return self.get(f"/channels/{id}")
def get_guild_channels(self, id):
return self.get(f"/guilds/{id}/channels")
def execute_webhook(self, link, message, name):
self.post(link, json.dumps({"content": message, "username": name}))
def send_msg(self, id, message):
self.post(f"/channels/{id}/messages", json.dumps({"content": message}))

@ -14,4 +14,4 @@ this particular example listens for a message that contains the string 'dango' a
hooks = ["MESSAGE_CREATE"] # run() will be called when client.dispatch() gets a MESSAGE_CREATE hooks = ["MESSAGE_CREATE"] # run() will be called when client.dispatch() gets a MESSAGE_CREATE
def run(event, ctx, bot): def run(event, ctx, bot):
if ctx["content"] == "dango": # if the message body matches... if ctx["content"] == "dango": # if the message body matches...
bot.send_msg(ctx["channel_id"], "to all the motherfuckers that shed a tear") bot.api.send_msg(ctx["channel_id"], "to all the motherfuckers that shed a tear")
Loading…
Cancel
Save