Skip to content

Commit

Permalink
Merge pull request #18 from code-chaser/codeforcesAPI
Browse files Browse the repository at this point in the history
Codeforces api
  • Loading branch information
code-chaser authored Jun 22, 2022
2 parents dfed800 + df1aea0 commit 5d8b034
Show file tree
Hide file tree
Showing 6 changed files with 116 additions and 157 deletions.
17 changes: 10 additions & 7 deletions src/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,18 +35,19 @@ def __init__(self, *args, **kwargs):
self.load_extension(f'src.cogs.{file[:-3]}')

def connect_to_db(self) -> None:

self.DB_CONNECTION = psycopg2.connect(
host=os.getenv('DEX_DB_HOST'),
database=os.getenv('DEX_DB_NAME'),
user=os.getenv('DEX_DB_USER'),
port=os.getenv('DEX_DB_PORT'),
password=os.getenv('DEX_DB_PASSWORD'),
)

async def get_prefix(self, message):
cur = self.DB_CONNECTION.cursor()
cur.execute('SELECT prefix FROM guilds WHERE guild_id = \'' + str(message.guild.id) + '\';')
cur.execute('SELECT prefix FROM guilds WHERE guild_id = \'' +
str(message.guild.id) + '\';')
prefix = cur.fetchone()
return prefix

Expand All @@ -61,7 +62,8 @@ async def on_ready(self):

async def on_guild_join(self, guild) -> None:
cur = self.DB_CONNECTION.cursor()
cur.execute('INSERT INTO guilds (guild_id,prefix,tag_messages) VALUES (\'' + str(guild.id)+'\', \'$dex \', \'on\');')
cur.execute('INSERT INTO guilds (guild_id,prefix,tag_messages) VALUES (\'' +
str(guild.id)+'\', \'$dex \', \'on\');')
self.DB_CONNECTION.commit()
cur.close()
for channel in guild.text_channels:
Expand All @@ -73,18 +75,19 @@ async def on_guild_join(self, guild) -> None:

async def on_guild_remove(self, guild) -> None:
cur = self.DB_CONNECTION.cursor()
cur.execute('DELETE FROM guilds WHERE guild_id = \'' + str(guild.id) + '\';')
cur.execute('DELETE FROM guilds WHERE guild_id = \'' +
str(guild.id) + '\';')
self.DB_CONNECTION.commit()
cur.close()
return

async def on_message(self, message) -> None:
await self.process_commands(message)
cur = self.DB_CONNECTION.cursor()
cur.execute('SELECT tag_messages FROM guilds WHERE guild_id = \'' + str(message.guild.id) + '\';')
cur.execute('SELECT tag_messages FROM guilds WHERE guild_id = \'' +
str(message.guild.id) + '\';')
tag_switch = cur.fetchone()
cur.close()
print(tag_switch[0])
if tag_switch[0] == 'off':
return
target = message.author
Expand Down
73 changes: 73 additions & 0 deletions src/cogs/codeforces.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import discord
import aiohttp
import json
import os
import datetime
import typing
from discord.ext import commands
from psycopg2 import Timestamp


class Codeforces(commands.Cog):
cf_red = 0xff0000 # 2400+
cf_orange = 0xff8c00 # 2200 - 2399
cf_violet = 0xb200aa # 1900 - 2199
cf_blue = 0x0000ff # 1600 - 1899
cf_cyan = 0x03a89e # 1400 - 1599
cf_green = 0x008000 # 1200 - 1399
cf_gray = 0x808080 # 0 - 1199

def __init__(self, bot):
self.bot = bot
# ----------------------------------------------------------------------------------------------------------------------

async def get_user(self, username):
API_URL = "https://codeforces.com/api/user.info?handles=" + username + ";"
async with aiohttp.ClientSession() as session:
async with session.get(API_URL) as resp:
user_json = await resp.json()
return (user_json)

@commands.command(name="cf-handle", aliases=["cf-user"], help="shows details of the requested codeforces handle")
async def send_user(self, ctx, username):
handle = await self.get_user(username)
if handle["status"] == "FAILED":
async with ctx.typing():
embed = discord.Embed(title="Error",
description=handle["comment"],
colour=0xff0000,
timestamp=datetime.datetime.utcnow())
await ctx.send(embed=embed)
return
async with ctx.typing():
embed = discord.Embed(title=username,
description=(handle["result"][0]["firstName"] if "firstName" in handle["result"][0] else "") + " " + (
handle["result"][0]["lastName"] if "lastName" in handle["result"][0] else ""),
colour=self.cf_red if handle["result"][0]["maxRating"] >= 2400 else self.cf_orange if handle["result"][0]["maxRating"] >= 2200 else self.cf_violet if handle["result"][0]["maxRating"] >= 1900 else self.cf_blue if handle[
"result"][0]["maxRating"] >= 1600 else self.cf_cyan if handle["result"][0]["maxRating"] >= 1400 else self.cf_green if handle["result"][0]["maxRating"] >= 1200 else self.cf_gray,
timestamp=datetime.datetime.utcnow())
embed.add_field(name="City", value=handle["result"][0]["city"]
if "city" in handle["result"][0] else "Unknown", inline=True)
embed.add_field(name="Country", value=handle["result"][0]["country"]
if "country" in handle["result"][0] else "Unknown", inline=True)
embed.add_field(
name="Friend of", value=handle["result"][0]["friendOfCount"], inline=True)
embed.add_field(name="Max Rating",
value=handle["result"][0]["maxRating"], inline=True)
embed.add_field(name="Max Rank",
value=handle["result"][0]["maxRank"], inline=True)
embed.add_field(name="Organization", value=handle["result"][0]["organization"]
if handle["result"][0]["organization"] != "" else "Unknown", inline=True)
embed.add_field(
name="Rating", value=handle["result"][0]["rating"], inline=True)
embed.add_field(
name="Rank", value=handle["result"][0]["rank"], inline=True)
embed.add_field(name="Last Online", value=datetime.datetime.utcfromtimestamp(
handle["result"][0]["lastOnlineTimeSeconds"]).strftime('%Y-%m-%d %H:%M:%S'), inline=True)
embed.set_thumbnail(url=handle["result"][0]["avatar"])
await ctx.send(embed=embed)
# ----------------------------------------------------------------------------------------------------------------------


def setup(bot):
bot.add_cog(Codeforces(bot))
74 changes: 0 additions & 74 deletions src/cogs/fun.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,80 +55,6 @@ async def send_nasa_pic_otd(self, ctx):
await ctx.send(embed=embed)
# ----------------------------------------------------------------------------------------------------------------------

async def get_covid19_details(self):
API_URL = "https://api.covid19api.com/summary"
async with aiohttp.ClientSession() as session:
async with session.get(API_URL) as resp:
data_json = await resp.json()
return (data_json)

@commands.command(name="covid19", help="sends COVID-19 stats of the given country (global stats if country == null)")
async def covid19_data(self, ctx, *args):
countr = ""
for arg in args:
countr += arg + " "
size = len(countr)
country = countr[:size - 1]
original = country
found = False
stats = await self.get_covid19_details()
if country:
for k in stats["Countries"]:
if ((k["CountryCode"]).lower() == country.lower()) or ((k["Country"]).lower() == country.lower()):
embed = discord.Embed(
title=(k["Country"]).title(),
description="COVID-19 Statistics",
colour=0xff0000,
timestamp=datetime.datetime.utcnow()
)
flag_url = "https://flagcdn.com/w640/" + \
str(k["CountryCode"]).lower() + ".jpg"
embed.set_thumbnail(url=flag_url)
fields = [
("New Confirmed Cases", k["NewConfirmed"], True),
("Total Confirmed Cases", k["TotalConfirmed"], True),
("Country Code", k["CountryCode"], True),
("New Deaths", k["NewDeaths"], True),
("Total Deaths", k["TotalDeaths"], True),
("Report Time (UTC)", "Date: " +
k["Date"][0:10] + " & Time: " + k["Date"][11:19], True),
]
for n, v, i in fields:
embed.add_field(name=n, value=v, inline=i)
await ctx.send(embed=embed)
found = True
else:
k = stats["Global"]
embed = discord.Embed(
title="Global",
description="COVID-19 Statistics",
colour=0xff0000,
timestamp=datetime.datetime.utcnow()
)
embed.set_thumbnail(
url="https://user-images.githubusercontent.com/63065397/156144079-6f90504d-ad48-4f2e-bec5-bae31cebd858.png"
)
fields = [
("New Confirmed Cases", k["NewConfirmed"], True),
("Total Confirmed Cases", k["TotalConfirmed"], True),
("New Deaths", k["NewDeaths"], True),
("Total Deaths", k["TotalDeaths"], True),
]
for n, v, i in fields:
embed.add_field(name=n, value=v, inline=i)
await ctx.send(embed=embed)
found = True
if not found:
embed = discord.Embed(
title="Error",
description="Country Not Found",
colour=0xff0000
)
embed.add_field(name="Given Country Name",
value=original, inline=True)
await ctx.send(embed=embed)
# ----------------------------------------------------------------------------------------------------------------------

async def get_meme(self):
API_URL = "https://meme-api.herokuapp.com/gimme"
async with aiohttp.ClientSession() as session:
Expand Down
18 changes: 11 additions & 7 deletions src/cogs/modset.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ async def modset(self, ctx, target: Optional[Member]):
@command(name="tags", aliases=["tagging", "msgtag"], help="toggles message tags")
async def message_tags(self, ctx, switch: Optional[str]):
cur = self.bot.DB_CONNECTION.cursor()
cur.execute('SELECT tag_messages FROM guilds WHERE guild_id = \'' + str(ctx.guild.id) + '\';')
cur.execute(
'SELECT tag_messages FROM guilds WHERE guild_id = \'' + str(ctx.guild.id) + '\';')
tag_messages = cur.fetchone()
tag_switch = tag_messages[0]
if switch is None:
Expand All @@ -42,7 +43,8 @@ async def message_tags(self, ctx, switch: Optional[str]):
return

cur = self.bot.DB_CONNECTION.cursor()
cur.execute('UPDATE guilds SET tag_messages = \'' + tag_switch + '\' WHERE guild_id = \'' + str(ctx.guild.id) + '\';')
cur.execute('UPDATE guilds SET tag_messages = \'' + tag_switch +
'\' WHERE guild_id = \'' + str(ctx.guild.id) + '\';')
self.bot.DB_CONNECTION.commit()
cur.close()
embed = Embed(title="Status",
Expand All @@ -55,7 +57,6 @@ async def message_tags(self, ctx, switch: Optional[str]):
@command(name="changepref", aliases=["changeprefix"], help="changes the prefix to the appended string")
async def change_prefix(self, ctx, *args):
prefix = "".join(args)
prefix += ' '
if ctx.guild.id == int(os.environ['PUBLIC_BOT_SERVER']):
embed = Embed(title="Status",
colour=0xff0000,
Expand All @@ -73,8 +74,10 @@ async def change_prefix(self, ctx, *args):
await ctx.send(embed=embed)
return
if (prefix != "") and (len(prefix) <= 27):
prefix += " "
cur = self.bot.DB_CONNECTION.cursor()
cur.execute("UPDATE guilds SET prefix = \'"+prefix+"\' WHERE guild_id = \'"+str(ctx.guild.id)+"\';")
cur.execute("UPDATE guilds SET prefix = \'"+prefix +
"\' WHERE guild_id = \'"+str(ctx.guild.id)+"\';")
self.bot.DB_CONNECTION.commit()
cur.close()
embed = Embed(title="Status",
Expand All @@ -88,7 +91,7 @@ async def change_prefix(self, ctx, *args):
colour=0xff0000,
timestamp=datetime.utcnow())
embed.add_field(
name="Error", value="prefix length must be strictly between (0 - 28)", inline=True)
name="Error", value="prefix length must be between (1 - 27)", inline=True)
await ctx.send(embed=embed)

@command(name="goodbye!", aliases=["leaveThisServer"], help="makes the bot to leave the server (only for server owner)")
Expand Down Expand Up @@ -117,8 +120,9 @@ async def leave_this_server(self, ctx):
await ctx.send(embed=embed)
guild = ctx.guild
await ctx.guild.leave()
cur=self.bot.DB_CONNECTION.cursor()
cur.execute("DELETE FROM guilds WHERE guild_id = \'"+str(guild.id)+"\';")
cur = self.bot.DB_CONNECTION.cursor()
cur.execute("DELETE FROM guilds WHERE guild_id = \'" +
str(guild.id)+"\';")
self.bot.DB_CONNECTION.commit()
cur.close()
return
Expand Down
Loading

0 comments on commit 5d8b034

Please sign in to comment.