diff --git a/api/__init__.py b/api/__init__.py new file mode 100644 index 0000000..bb25534 --- /dev/null +++ b/api/__init__.py @@ -0,0 +1 @@ +# This just exists so python recognizes this submodule \ No newline at end of file diff --git a/api/steam.py b/api/steam.py new file mode 100644 index 0000000..e05cf9a --- /dev/null +++ b/api/steam.py @@ -0,0 +1,62 @@ +import requests +import json +from util import logging + +# This module acts as an interface between the bot and the Steam API +# The responses of the API are formatted and returned in a standard format + +with open("config.json", "r") as key_file: + json = json.load(key_file) + key = json["api_keys"]["steam"] + +# Returns a (hopefully) valid Steam API URL +def assemble_url(interface_name, method_name, version): + return f"http://api.steampowered.com/{interface_name}/{method_name}/v{version}/?key={key}&format=json" + +def get_json_request_response(url : str): + response = requests.get(url) + + if not response.ok: + logging.error(f"Steam API response not OK: {response.status_code} [{url}]") + return None + + json = response.json() + return json + +# Finds the SteamID of a user by their Vanity URL +def resolve_vanity_url(vanity_url : str) -> str: + url = assemble_url("ISteamUser", "ResolveVanityURL", 1) + f"&vanityurl={vanity_url}" + json = get_json_request_response(url) + + success = json["response"]["success"] + if success != 1: + logging.error(f"Something went wrong while resolving Vanity URL: {success}") + return None + + return json["response"]["steamid"] + + +# Gets a users steam level +def get_steam_level(vanity_url : str) -> str: + steamid = resolve_vanity_url(vanity_url) + if steamid is None: + logging.error("Could not resolve Vanity URL") + return None + + url = assemble_url("IPlayerService", "GetSteamLevel", 1) + f"&steamid={steamid}" + json = get_json_request_response(url) + + if len(json["response"]) == 0: + return None + + return json["response"]["player_level"] + +# Gets the percentage of players who have a lower level +def get_steam_level_distribution(level : str) -> str: + url = assemble_url("IPlayerService", "GetSteamLevelDistribution", 1) + f"&player_level={level}" + json = get_json_request_response(url) + + if len(json["response"]) == 0: + return None + + return json["response"]["player_level_percentile"] \ No newline at end of file diff --git a/bot.py b/bot.py index cd29f90..ffefff9 100644 --- a/bot.py +++ b/bot.py @@ -1,10 +1,68 @@ import discord +import os +import json from discord.ext import commands +from util import logging + +# Bot URL https://discordapp.com/api/oauth2/authorize?client_id=657709911337074698&permissions=314432&scope=bot + +client = commands.Bot(command_prefix='.', case_insensitive=True) + +@client.command() +@commands.is_owner() +async def load(ctx, extension): + client.load_extension(f"cogs.{extension}") + await ctx.message.add_reaction("👍") + +@client.command() +@commands.is_owner() +async def unload(ctx, extension): + client.unload_extension(f"cogs.{extension}") + await ctx.message.add_reaction("👍") + -client = commands.Bot(command_prefix='.') @client.event async def on_ready(): - print(f"Logged in as {client.user.name}") + logging.info("Starting up...\n") + logging.info("Trying to load cogs...\n") + total = 0 + failed = 0 + # Load all cogs on startup + # Load "fun" cogs + for filename in os.listdir("./cogs/fun"): + if filename.endswith(".py"): + total += 1 + cog = f"cogs.fun.{filename[:-3]}" -client.run() \ No newline at end of file + try: + client.load_extension(cog) + logging.info(f"Trying {cog}.....Success!") + except: + logging.error(f"Trying {cog}.....Failed!") + failed += 1 + + + # Load "api" cogs + for filename in os.listdir("./cogs/api"): + if filename.endswith(".py"): + total += 1 + cog = f"cogs.api.{filename[:-3]}" + + try: + client.load_extension(cog) + logging.info(f"Trying {cog}.....Success!") + except: + logging.error(f"Trying {cog}.....Failed!") + failed += 1 + + logging.info("Finished loading cogs.") + logging.info(f"Total {total}, Failed {failed}\n") + + logging. info("Deep Blue finished loading.") + +with open("config.json", "r") as key_file: + json = json.load(key_file) + key = json["client_key"] + +client.run(key) \ No newline at end of file diff --git a/cogs/api/steam.py b/cogs/api/steam.py new file mode 100644 index 0000000..5be733e --- /dev/null +++ b/cogs/api/steam.py @@ -0,0 +1,23 @@ +import discord +from discord.ext import commands +from api import steam + +class Steam(commands.Cog): + + def __init__(self, client): + self.client = client + + @commands.command(name="SteamLevel", description="Finds the steam level of a user", usage="SteamLevel ", aliases=["level"]) + @commands.cooldown(1, 2) + async def SteamLevel(self, ctx, vanity_url): + level = steam.get_steam_level(vanity_url) + percentile = round(float(steam.get_steam_level_distribution(level)), 2) + if level is not None: + await ctx.send(f"{vanity_url} is level {level}! This makes him better than {percentile}% of Steam users!") + else: + await ctx.send(f"There is nobody named \"{vanity_url}\" on Steam, or their profile might be pivate.") + + + +def setup(client): + client.add_cog(Steam(client)) \ No newline at end of file diff --git a/cogs/fun/coinflip.py b/cogs/fun/coinflip.py new file mode 100644 index 0000000..d18f959 --- /dev/null +++ b/cogs/fun/coinflip.py @@ -0,0 +1,18 @@ +import discord +import random +from discord.ext import commands + +class Coinflip(commands.Cog): + + def __init__(self, client): + self.client = client + + @commands.command(name="coinflip", description="Flips a coin and reacts with the result", aliases=["coin", "flip"]) + async def coinflip(self, ctx): + if random.randint(0, 1) == 0: + await ctx.message.add_reaction("🌑") + else: + await ctx.message.add_reaction("🌕") + +def setup(client): + client.add_cog(Coinflip(client)) \ No newline at end of file diff --git a/util/__init__.py b/util/__init__.py new file mode 100644 index 0000000..bb25534 --- /dev/null +++ b/util/__init__.py @@ -0,0 +1 @@ +# This just exists so python recognizes this submodule \ No newline at end of file diff --git a/util/logging.py b/util/logging.py new file mode 100644 index 0000000..94612d4 --- /dev/null +++ b/util/logging.py @@ -0,0 +1,22 @@ +import datetime + +path = "logs/log.txt" +cleanup = open(path, "w+") +cleanup.close() + +def log(msg, log_type, mute): + log = f"[{datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S')}] [{log_type.upper()}] {msg}" + log_file = open(path, "a") + log_file.write(log + "\n") + log_file.close() + if mute == False: + print(log) + +def info(msg, mute=False): + log(msg, "info", mute) + +def warning(msg, mute=False): + log(msg, "warning", mute) + +def error(msg, mute=False): + log(msg, "error", mute)