Added first steam API command
This commit is contained in:
parent
82228b17eb
commit
ca91cfddaf
1
api/__init__.py
Normal file
1
api/__init__.py
Normal file
|
@ -0,0 +1 @@
|
|||
# This just exists so python recognizes this submodule
|
62
api/steam.py
Normal file
62
api/steam.py
Normal file
|
@ -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"]
|
64
bot.py
64
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()
|
||||
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)
|
23
cogs/api/steam.py
Normal file
23
cogs/api/steam.py
Normal file
|
@ -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 <Vanity URL>", 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))
|
18
cogs/fun/coinflip.py
Normal file
18
cogs/fun/coinflip.py
Normal file
|
@ -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))
|
1
util/__init__.py
Normal file
1
util/__init__.py
Normal file
|
@ -0,0 +1 @@
|
|||
# This just exists so python recognizes this submodule
|
22
util/logging.py
Normal file
22
util/logging.py
Normal file
|
@ -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)
|
Loading…
Reference in a new issue