Skip to content

Commit

Permalink
Merge pull request #20 from varundeepsaini/lint
Browse files Browse the repository at this point in the history
Lint
  • Loading branch information
varundeepsaini authored Sep 24, 2023
2 parents e9bfde2 + 4c2242f commit 5e37c05
Show file tree
Hide file tree
Showing 9 changed files with 199 additions and 84 deletions.
13 changes: 13 additions & 0 deletions .github/workflows/lint.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
name: Lint

on: [push, pull_request]

jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: psf/black@stable
with:
options: "--check --verbose"
src: "."
71 changes: 47 additions & 24 deletions cogs/contests.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,28 +22,46 @@ def fetch_upcoming_contests():

print(data) # For debugging
upcoming_contests = []
current_time = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ') # Get current time in UTC
current_time = datetime.utcnow().strftime(
"%Y-%m-%dT%H:%M:%S.%fZ"
) # Get current time in UTC
count = 0
for contestList in data:
if 'name' in contestList and 'start_time' in contestList and 'end_time' in contestList:
start_time_str = contestList['start_time']
end_time_str = contestList['end_time']

if start_time_str > current_time and count < 7: # Check if the contest is after the current time
if (
"name" in contestList
and "start_time" in contestList
and "end_time" in contestList
):
start_time_str = contestList["start_time"]
end_time_str = contestList["end_time"]

if (
start_time_str > current_time and count < 7
): # Check if the contest is after the current time
try:
start_time = datetime.strptime(start_time_str, '%Y-%m-%dT%H:%M:%S.%fZ')
end_time = datetime.strptime(end_time_str, '%Y-%m-%dT%H:%M:%S.%fZ')
start_time = datetime.strptime(
start_time_str, "%Y-%m-%dT%H:%M:%S.%fZ"
)
end_time = datetime.strptime(end_time_str, "%Y-%m-%dT%H:%M:%S.%fZ")
except ValueError:
print(f"Could not parse date-time string: {start_time_str} or {end_time_str}")
print(
f"Could not parse date-time string: {start_time_str} or {end_time_str}"
)
continue

upcoming_contests.append({
'Name': contestList['name'],
'Start Time': start_time.strftime('%H:%M %d-%m-%Y'), # Format the datetime object to a string
'End Time': end_time.strftime('%H:%M %d-%m-%Y'), # Format the datetime object to a string
'Site': contestList['site'],
'URL': contestList['url']
})
upcoming_contests.append(
{
"Name": contestList["name"],
"Start Time": start_time.strftime(
"%H:%M %d-%m-%Y"
), # Format the datetime object to a string
"End Time": end_time.strftime(
"%H:%M %d-%m-%Y"
), # Format the datetime object to a string
"Site": contestList["site"],
"URL": contestList["url"],
}
)
count += 1

return upcoming_contests
Expand All @@ -56,18 +74,23 @@ def __init__(self, bot: commands.Bot):
@commands.slash_command(description="Get the list of all the Upcoming Contests")
async def upcoming_contest(self, ctx: commands.Context):
contest_item = fetch_upcoming_contests()
response = Embed(title="Upcoming Contests", description="Here are some upcoming coding contests.",
color=0x00ff00)
response = Embed(
title="Upcoming Contests",
description="Here are some upcoming coding contests.",
color=0x00FF00,
)

for contestList in contest_item:
contest_name = contestList['Name']
contest_url = contestList.get('URL', 'No URL provided')
start_time = contestList['Start Time']
end_time = contestList['End Time']
site = contestList['Site']
contest_name = contestList["Name"]
contest_url = contestList.get("URL", "No URL provided")
start_time = contestList["Start Time"]
end_time = contestList["End Time"]
site = contestList["Site"]

field_name = "Contest Details"
field_value = f"[{contest_name}]({contest_url})\n" # Hyperlink the contest name
field_value = (
f"[{contest_name}]({contest_url})\n" # Hyperlink the contest name
)
field_value += f"Start Time: {start_time}\n"
field_value += f"End Time: {end_time}\n"
field_value += f"Site: {site}"
Expand Down
36 changes: 26 additions & 10 deletions cogs/cp_profiles/AtCoder.py
Original file line number Diff line number Diff line change
@@ -1,44 +1,60 @@
from requests import get
from bs4 import BeautifulSoup
from discord import Embed, Colour, ApplicationContext, bot
from discord import Embed, Colour, ApplicationContext, bot
from discord.ext import commands


class AtCoderProfile:
success = False

def __init__(self, username: str):
response = get(f"https://atcoder.jp/users/{username}")
if not response.ok:
self.success = False
return
soup = BeautifulSoup(response.content, 'html5lib')
self.username = soup.find('a', attrs={'class': 'username'}).contents[0].getText()
self.kyu = soup.find('div', attrs={'id': 'main-container'}).find('h3').find('b').contents[0]
statsRows = soup.findAll('div', attrs={'id': 'main-container', 'class': 'container'})[0].findAll('table')[1].findAll('tr')
soup = BeautifulSoup(response.content, "html5lib")
self.username = (
soup.find("a", attrs={"class": "username"}).contents[0].getText()
)
self.kyu = (
soup.find("div", attrs={"id": "main-container"})
.find("h3")
.find("b")
.contents[0]
)
statsRows = (
soup.findAll("div", attrs={"id": "main-container", "class": "container"})[0]
.findAll("table")[1]
.findAll("tr")
)
self.rank = statsRows[0].td.getText()
self.rating = statsRows[1].td.span.getText()
self.highestRating = statsRows[2].td.span.getText()
self.ratedMatches = statsRows[3].td.getText()
self.success = True

def embed(self):
embed = Embed(title=self.username, color=Colour.dark_grey())
embed.set_author(name="AtCoder", icon_url="https://img.atcoder.jp/assets/icon/avatar.png")
embed.set_author(
name="AtCoder", icon_url="https://img.atcoder.jp/assets/icon/avatar.png"
)
embed.add_field(name="", value=f"**{self.kyu}**", inline=False)
embed.add_field(name="Rank", value=self.rank)
embed.add_field(name="Rated Matches", value=self.ratedMatches)
embed.add_field(name="Rating", value=self.rating)
embed.add_field(name="Highest Rating", value=self.highestRating)
return embed

class AtCoder(commands.Cog):

class AtCoder(commands.Cog):
@commands.slash_command()
async def at_coder(self, ctx: ApplicationContext, username: str):
profile = AtCoderProfile(username)
if (not profile.success):
if not profile.success:
await ctx.respond("Invalid username")
return
await ctx.respond(embed=profile.embed())


def setup(bot: bot.Bot):
bot.add_cog(AtCoder(bot))
bot.add_cog(AtCoder(bot))
71 changes: 55 additions & 16 deletions cogs/cp_profiles/LeetCode.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,75 @@
from discord import Embed, ApplicationContext, bot
from discord.ext import commands


def getLeetCodeEmbed(username: str) -> Embed | None:
profile_url = f"https://leetcode.com/{username}/"
response = get(f"https://leetcode-stats-api.herokuapp.com/{username}")
if not response.ok:
return None
data = response.json()
embed = Embed(title=username, color=0x00ff00)
embed.set_author(name="LeetCode", icon_url="https://www.google.com/url?sa=i&url=https%3A%2F%2Fleetcode.com%2F&psig=AOvVaw1bZXtsAts5pg_h6It7I9kX&ust=1695556446675000&source=images&cd=vfe&opi=89978449&ved=0CBAQjRxqFwoTCOi11o_WwIEDFQAAAAAdAAAAABAE")
embed = Embed(title=username, color=0x00FF00)
embed.set_author(
name="LeetCode",
icon_url="https://www.google.com/url?sa=i&url=https%3A%2F%2Fleetcode.com%2F&psig=AOvVaw1bZXtsAts5pg_h6It7I9kX&ust=1695556446675000&source=images&cd=vfe&opi=89978449&ved=0CBAQjRxqFwoTCOi11o_WwIEDFQAAAAAdAAAAABAE",
)
embed.add_field(name="Handle", value=f"[{username}]({profile_url})", inline=False)
embed.add_field(name="Ranking", value=data['ranking'], inline=False)
embed.add_field(name="Total Solved", value=f"{data['totalSolved']} / {data['totalQuestions']}", inline=False)
embed.add_field(name="Percentage Solved", value=f"{round(100 * data['totalSolved'] / data['totalQuestions'], 2)}%", inline=False)
embed.add_field(name="Total Easy Solved", value=f"{data['easySolved']} / {data['totalEasy']}", inline=False)
embed.add_field(name="Percentage Easy Solved", value=f"{round(100 * data['easySolved']/ data['totalEasy'], 2)}%", inline=False)
embed.add_field(name="Total Medium Solved", value=f"{data['mediumSolved']} / {data['totalMedium']}", inline=False)
embed.add_field(name="Percentage Medium Solved", value=f"{round(100 * data['mediumSolved'] / data['totalMedium'], 2)}%",inline=False)
embed.add_field(name="Total Hard Solved", value=f"{data['hardSolved']} / {data['totalHard']}", inline=False)
embed.add_field(name="Percentage Hard Solved", value=f"{round(100 * data['hardSolved'] / data['totalHard'], 2)}%", inline=False)
embed.add_field(name="Acceptance Rate", value=f"{data['acceptanceRate']}%", inline=False)
embed.add_field(name="Ranking", value=data["ranking"], inline=False)
embed.add_field(
name="Total Solved",
value=f"{data['totalSolved']} / {data['totalQuestions']}",
inline=False,
)
embed.add_field(
name="Percentage Solved",
value=f"{round(100 * data['totalSolved'] / data['totalQuestions'], 2)}%",
inline=False,
)
embed.add_field(
name="Total Easy Solved",
value=f"{data['easySolved']} / {data['totalEasy']}",
inline=False,
)
embed.add_field(
name="Percentage Easy Solved",
value=f"{round(100 * data['easySolved']/ data['totalEasy'], 2)}%",
inline=False,
)
embed.add_field(
name="Total Medium Solved",
value=f"{data['mediumSolved']} / {data['totalMedium']}",
inline=False,
)
embed.add_field(
name="Percentage Medium Solved",
value=f"{round(100 * data['mediumSolved'] / data['totalMedium'], 2)}%",
inline=False,
)
embed.add_field(
name="Total Hard Solved",
value=f"{data['hardSolved']} / {data['totalHard']}",
inline=False,
)
embed.add_field(
name="Percentage Hard Solved",
value=f"{round(100 * data['hardSolved'] / data['totalHard'], 2)}%",
inline=False,
)
embed.add_field(
name="Acceptance Rate", value=f"{data['acceptanceRate']}%", inline=False
)
return embed

class LeetCode(commands.Cog):


class LeetCode(commands.Cog):
@commands.slash_command()
async def leetcode(self, ctx: ApplicationContext, username: str):
profile = getLeetCodeEmbed(username)
if (profile is None):
if profile is None:
await ctx.respond("Invalid username")
return
await ctx.respond(embed=profile)


def setup(bot: bot.Bot):
bot.add_cog(LeetCode(bot))
bot.add_cog(LeetCode(bot))
24 changes: 15 additions & 9 deletions cogs/cp_profiles/codechef.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,23 @@


def codechef_embed(formatted_response, handle: str):
name = formatted_response['name']
rating = formatted_response['currentRating']
max_rating = formatted_response['highestRating']
stars = formatted_response['stars'][:1]
global_rank = formatted_response['globalRank']
country_rank = formatted_response['countryRank']
name = formatted_response["name"]
rating = formatted_response["currentRating"]
max_rating = formatted_response["highestRating"]
stars = formatted_response["stars"][:1]
global_rank = formatted_response["globalRank"]
country_rank = formatted_response["countryRank"]
profile_url = f"https://www.codechef.com/users/{handle}"

embed = Embed(title="Codechef Profile", description="Here is your Codechef Profile.", color=0x00ff00)
embed = Embed(
title="Codechef Profile",
description="Here is your Codechef Profile.",
color=0x00FF00,
)
embed.add_field(name="Name", value=name, inline=False)
embed.add_field(name="Handle", value=f"[{handle}]({profile_url})", inline=False) # hyperlink the handle
embed.add_field(
name="Handle", value=f"[{handle}]({profile_url})", inline=False
) # hyperlink the handle
embed.add_field(name="Rating", value=rating, inline=False)
embed.add_field(name="Max Rating", value=max_rating, inline=False)
embed.add_field(name="Stars", value=stars, inline=False)
Expand Down Expand Up @@ -42,7 +48,7 @@ async def codechef(self, ctx: commands.Context, handle: str):
'https://cdn.codechef.com/download/flags/24/in.png', 'countryName': 'India', 'globalRank': 66569, 'countryRank':
61804, 'stars': '1★'}
"""
if formatted_response['success']:
if formatted_response["success"]:
embed = codechef_embed(formatted_response, handle)
await ctx.send(embed=embed)
return
Expand Down
41 changes: 25 additions & 16 deletions cogs/cp_profiles/codeforces.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,34 @@


def codeforces_embed(formatted_response: dict):
embed = Embed(title="Codeforces Profile", description="Here is your Codeforces Profile.", color=0x00ff00)
embed = Embed(
title="Codeforces Profile",
description="Here is your Codeforces Profile.",
color=0x00FF00,
)
keys = formatted_response.keys()
handle = formatted_response['handle']
if ("firstName" in keys):
name = formatted_response['firstName'] + " " + formatted_response['lastName']
handle = formatted_response["handle"]
if "firstName" in keys:
name = formatted_response["firstName"] + " " + formatted_response["lastName"]
embed.add_field(name="Name", value=name, inline=False)
if ("rank" in keys):
rank = formatted_response['rank']
if "rank" in keys:
rank = formatted_response["rank"]
embed.add_field(name="Rank", value=rank.capitalize(), inline=False)

if ("maxRank" in keys):
max_rank = formatted_response['maxRank']
if "maxRank" in keys:
max_rank = formatted_response["maxRank"]
embed.add_field(name="Max Rank", value=max_rank.capitalize(), inline=False)

if ("rating" in keys):
rating = formatted_response['rating']
max_rating = formatted_response['maxRating']
if "rating" in keys:
rating = formatted_response["rating"]
max_rating = formatted_response["maxRating"]
embed.add_field(name="Max Rating", value=max_rating, inline=False)
else:
rating = "*unrated*"
profile_url = f"https://codeforces.com/profile/{handle}"

embed.add_field(name="Rating", value=rating, inline=False)
embed.add_field(name="Handle", value=f"[{handle}]({profile_url})", inline=False) # hyperlink the handle
embed.add_field(name="Handle", value=f"[{handle}]({profile_url})", inline=False)

return embed

Expand All @@ -38,19 +42,24 @@ def __init__(self, bot: commands.Bot):

@commands.slash_command(description="Get Your Codeforces Profile")
async def codeforces(self, ctx: commands.Context, username: str):
formatted_response = Embed(title="Codeforces Profile", description="Here is your Codeforces Profile.",
color=0x00ff00)
formatted_response = Embed(
title="Codeforces Profile",
description="Here is your Codeforces Profile.",
color=0x00FF00,
)
url = f"https://codeforces.com/api/user.info?handles={username}"
formatted_response = requests.get(url)
if formatted_response.status_code != 200:
print(f"Failed to get data from API. Status code: {formatted_response.status_code}")
print(
f"Failed to get data from API. Status code: {formatted_response.status_code}"
)
return
try:
data = formatted_response.json()
except ValueError:
print("Failed to decode JSON data from API response.")
return
if data['status'] == "FAILED":
if data["status"] == "FAILED":
await ctx.send("Invalid username")
return
else:
Expand Down
Loading

0 comments on commit 5e37c05

Please sign in to comment.