Skip to content

Commit

Permalink
Merge pull request #212 from alexraskin/generate-csv-update-lhguess
Browse files Browse the repository at this point in the history
🔄 Refactor data processing methods and optimize collection loading in LhGuess cog.
  • Loading branch information
alexraskin authored May 22, 2024
2 parents bd0c916 + 6df1e82 commit 63aee42
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 33 deletions.
2 changes: 1 addition & 1 deletion bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def owner(self) -> User:

@tasks.loop(minutes=60)
async def clean_dir() -> None:
clean_cache("./bot/files", ".pdf")
clean_cache("./bot/files", ".csv")


@client.event
Expand Down
57 changes: 36 additions & 21 deletions bot/cogs/lhcloudy.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from __future__ import annotations

import datetime
import sys

from typing import Optional, TYPE_CHECKING
from typing import TYPE_CHECKING

from discord import Colour, Embed
from discord.ext import commands
Expand All @@ -16,28 +15,21 @@ class LhCloudy(commands.Cog):
def __init__(self, client: LhBot):
self.client: LhBot = client

@commands.hybrid_group(invoke_without_command=True)
async def twitch(self, ctx: commands.Context):
if ctx.invoked_subcommand is None:
await ctx.send(
f"Please use `{self.client.config.bot_prefix}twitch help` to see the list of commands."
)

@twitch.command(name="lhfurry", with_app_command=True)
@commands.hybrid_command(name="lhfurry", with_app_command=True)
async def lhfurry(self, ctx: commands.Context) -> None:
"""
LhCloudy's furry side
"""
await ctx.send("https://i.gyazo.com/3ae8376713000ab829a2853d0f31e6f2.png")

@twitch.command(name="code", aliases=["workshop"], with_app_command=True)
@commands.hybrid_command(name="code", aliases=["workshop"], with_app_command=True)
async def code(self, ctx: commands.Context) -> None:
"""
LhCloudy's workshop code
"""
await ctx.send("rein: XEEAE | other: https://workshop.codes/u/Seita%232315")

@twitch.command(name="egirl", with_app_command=True)
@commands.hybrid_command(name="egirl", with_app_command=True)
async def egirl(self, ctx: commands.Context):
"""
Egirl Quote
Expand All @@ -48,14 +40,14 @@ async def egirl(self, ctx: commands.Context):
await message.add_reaction("👈")
await message.add_reaction("😌")

@twitch.command(name="instagram", with_app_command=True)
@commands.hybrid_command(name="instagram", with_app_command=True)
async def instagram(self, ctx: commands.Context):
"""
Get a link to LhCloudy's Instagram
"""
await ctx.send("https://www.instagram.com/lhcloudy/")

@twitch.command(name="spotify", with_app_command=True)
@commands.hybrid_command(name="spotify", with_app_command=True)
async def spotify(self, ctx: commands.Context):
"""
Get a link to LhCloudy's Spotify Playlist
Expand All @@ -64,7 +56,7 @@ async def spotify(self, ctx: commands.Context):
"https://open.spotify.com/playlist/3JuA2BZjl0aZsEHKry1B67?si=14278d6ea4c04330"
)

@twitch.command(name="playlist", with_app_command=True)
@commands.hybrid_command(name="playlist", with_app_command=True)
async def playlist(self, ctx: commands.Context):
"""
Get a link to LhCloudy's Youtube Music Playlist
Expand All @@ -73,29 +65,29 @@ async def playlist(self, ctx: commands.Context):
"https://www.youtube.com/watch?v=p1SlBlB5pzU&list=RDHiu1hPdJk-Y&index=23"
)

@twitch.command(name="tips", with_app_command=True)
@commands.hybrid_command(name="tips", with_app_command=True)
async def tips(self, ctx: commands.Context):
"""
Get a link to LhCloudy's Rein Tips
"""
await ctx.send("W+M1")

@twitch.command(name="twitter", with_app_command=True)
@commands.hybrid_command(name="twitter", with_app_command=True)
async def twitter(self, ctx: commands.Context):
"""
Get a link to LhCloudy's Twitter
"""
await ctx.send("https://twitter.com/LhCloudy")

@twitch.command(name="youtube", with_app_command=True)
@commands.hybrid_command(name="youtube", with_app_command=True)
async def youtube(self, ctx: commands.Context):
"""
Get a link to LhCloudy's Youtube Channel
"""
url = "SMÄSH THAT LIKE AND SUBSCRIBE BUTTON -> https://www.youtube.com/channel/UC2CV-HWvIrMO4mUnYtNS-7A"
await ctx.send(url)

@twitch.command(name="age", aliases=["oldman"], with_app_command=True)
@commands.hybrid_command(name="age", aliases=["oldman"], with_app_command=True)
async def age(self, ctx: commands.Context):
"""
Get LhCloudy's age
Expand All @@ -105,14 +97,37 @@ async def age(self, ctx: commands.Context):
age_years = int((td - bd).days / 365.25)
await ctx.send(age_years)

@twitch.command(name="from", with_app_command=True)
@commands.hybrid_command(name="birthday", with_app_command=True)
async def birthday(self, ctx: commands.Context):
"""
Get days until next birthday
"""
birthday_str = "21.5.1999"
birthday = datetime.datetime.strptime(birthday_str, "%d.%m.%Y").date()

today = datetime.date.today()
current_year_birthday = birthday.replace(year=today.year)
next_birthday = current_year_birthday

if today > current_year_birthday:
next_birthday = birthday.replace(year=today.year + 1)

days_until_next_birthday = (next_birthday - today).days

if days_until_next_birthday == 0:
await ctx.send("Today is Cloudy's birthday! 🎉")
await ctx.send("https://tenor.com/bmYbD.gif")
else:
await ctx.send(f"There are {days_until_next_birthday} days until Cloudy's birthday.")

@commands.hybrid_command(name="from", with_app_command=True)
async def from_(self, ctx: commands.Context):
"""
Where is LhCloudy from?
"""
await ctx.send("kotka of south eastern finland of the continent of europe")

@twitch.command(name="links", aliases=["urls"], with_app_command=True)
@commands.hybrid_command(name="links", aliases=["urls"], with_app_command=True)
async def links(self, ctx: commands.Context) -> None:
"""
Get a list of LhCloudy's links
Expand Down
17 changes: 10 additions & 7 deletions bot/cogs/lhguess.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

from bson.objectid import ObjectId
from discord import Embed, app_commands, ui, TextStyle, Interaction, File
from discord.ext import commands, tasks
from discord.ext import commands
from async_lru import alru_cache
from utils import checks
from utils.banwords import banned_words
from utils.generate_csv import MongoDataProcessor
Expand Down Expand Up @@ -47,15 +48,15 @@ def __init__(self, client: LhBot) -> None:
self.guess_list = []
self.database = self.client.db_client.lhbot
self.collection = self.database.get_collection("lhbot_collection")
self.load_collection_list.start()

@tasks.loop(seconds=30)
@alru_cache(maxsize=32)
async def load_collection_list(self) -> list:
async for guess in self.collection.find():
data = helper(guess)
self.guess_list.append(
{"guess": data["guess"], "guessedBy": data["guessedBy"]}
)
return self.guess_list

def check(self, guess: str) -> bool:
if not str(guess).lower().startswith("l"):
Expand Down Expand Up @@ -142,8 +143,9 @@ async def lhcount(self, ctx: commands.Context):
Get the current guess count.
"""
embed = Embed(title="LhGuess Count", color=self.success_color)
count = await self.load_collection_list()
embed.add_field(
name="Current guess Count:", value=f"{len(self.guess_list)} 🦍", inline=True
name="Current guess Count:", value=f"{len(count)} 🦍", inline=True
)
await ctx.send(embed=embed)

Expand All @@ -159,7 +161,7 @@ async def lhreport(self, ctx: commands.Context):
return
now = datetime.now()
file_name_friendly_date = now.strftime("%Y-%m-%d_%H-%M-%S")
report = MongoDataProcessor(self.guess_list)
report = MongoDataProcessor(await self.load_collection_list())
report.export_to_csv(f"lhguess_report_{file_name_friendly_date}.csv")
await ctx.send(file=File(report.file_path))

Expand Down Expand Up @@ -204,15 +206,16 @@ async def lhdelete(self, ctx: commands.Context, guess_id: int):
@commands.hybrid_command()
@commands.guild_only()
@app_commands.guild_only()
async def latest(self, ctx: commands.Context):
async def lhlatest(self, ctx: commands.Context):
"""
Get the 5 latest guesses.
"""
if ctx.guild.id != self.client.config.main_guild:
await ctx.send("This command can only be used in Cloudy's Discord.")
return
embed = Embed(title="Latest LhGuesses", color=self.success_color)
for guess in self.guess_list[-5:]:
guess_list = await self.load_collection_list()
for guess in guess_list[-5:]:
embed.add_field(
name=f"LhGuess: {guess['guess']}",
value=f"Guessed by: {guess['guessedBy']}",
Expand Down
8 changes: 4 additions & 4 deletions bot/utils/generate_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,22 @@


class MongoDataProcessor:
def __init__(self, data):
def __init__(self, data) -> None:
self.data = data
self.df = pd.DataFrame(data)
self.filename = None

def count_items(self):
def count_items(self) -> pd.DataFrame:
self.item_count = self.df.shape[0]
self.df["item_count"] = self.item_count
return self.df

def export_to_csv(self, filename="report.csv"):
def export_to_csv(self, filename="report.csv") -> None:
file_path = os.path.join("./bot/files", filename)
self.df.to_csv(file_path, index=False)
self.filename = filename

def get_dataframe(self):
def get_dataframe(self) -> pd.DataFrame:
return self.df

@property
Expand Down
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ aiohttp-jinja2==1.5
aiosignal==1.3.1
anyio==4.2.0
astroid==2.12.10
async-lru==2.0.4
async-timeout==4.0.2
attrs==21.4.0
blinker==1.6.2
botocore==1.34.110
certifi==2023.7.22
cffi==1.15.1
chardet==4.0.0
Expand Down

0 comments on commit 63aee42

Please sign in to comment.