Skip to content

Commit

Permalink
add grouped embed back, refactored embed code to consolidate more log…
Browse files Browse the repository at this point in the history
…ic in there
  • Loading branch information
howardt12345 committed Jan 11, 2025
1 parent e7a8447 commit baebdc4
Show file tree
Hide file tree
Showing 3 changed files with 121 additions and 65 deletions.
54 changes: 21 additions & 33 deletions commands/bbt_count/bbt_count.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import discord
from discord import app_commands


from bot import TWPlaceClient
from commands.bbt_count.consts import BBT_LIST_GROUP_BY_CHOICES
from components.paginator import GenericPaginator
Expand All @@ -25,7 +24,7 @@
user_transfer_embed,
bbt_stats_embed,
)
from .helpers import bubble_tea_data
from .helpers import bubble_tea_data, calculate_prices
from modules import logging


Expand Down Expand Up @@ -313,49 +312,38 @@ async def bbt_count_list(
await interaction.response.defer()
entries = get_bbt_entries(user.id if user else interaction.user.id, year)

# Define items per page
items_per_page = 10

if not entries:
embed = discord.Embed(
title="No bubble tea entries found",
color=discord.Color.red()
)
await interaction.followup.send(embed=embed)
return

total_prices = calculate_prices(entries, None)["default_group"]

# Split entries into chunks
chunks = [entries[i:i + items_per_page] for i in range(0, len(entries), items_per_page)]
total_pages = len(chunks)

embeds = []
for i, chunk in enumerate(chunks):
embed = (
bbt_list_default_embed(
user.id if user else interaction.user.id,
chunk,
year,
interaction.created_at.astimezone().tzinfo,
)
if not group_by
else bbt_list_grouped_embed(
user.id if user else interaction.user.id,
chunk,
year,
interaction.created_at.astimezone().tzinfo,
group_by.value,
)
if group_by:
embeds = bbt_list_grouped_embed(
user.id if user else interaction.user.id,
entries,
year,
interaction.created_at.astimezone().tzinfo,
group_by.value,
total_prices,
)

# Add total entries count and page info to title
embed.title = f"{embed.title} ({len(entries)} total)"
embed.set_footer(text=f"Page {i+1} of {total_pages}")
embeds.append(embed)

else:
embeds = bbt_list_default_embed(
user.id if user else interaction.user.id,
entries,
year,
interaction.created_at.astimezone().tzinfo,
total_prices,
len(entries),
)

paginator = GenericPaginator(embeds)
await interaction.followup.send(embed=embeds[0], view=paginator)


# leaderboard
@bbt_count.command(
name="leaderboard",
Expand Down
102 changes: 70 additions & 32 deletions commands/bbt_count/embeds.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
bubble_tea_string,
calculate_prices,
entry_string,
organize_entries_by_group,
price_string,
cost_string,
average_year_string,
Expand Down Expand Up @@ -75,48 +76,85 @@ def bbt_list_default_embed(
entries: list[dict],
year: int | None,
timezone: datetime.tzinfo,
total_prices: dict = None,
total_entries: int = 0,
items_per_page: int = 10,
):
prices = calculate_prices(entries, None).get("default_group", {})
embed = discord.Embed(
title=f"Bubble tea entries {f'for {year}' if year else 'for the past year'} 🧋",
color=discord.Color.blue(),
)
embed.description = (
f"For <@{user_id}>: **{len(entries)} total entries**\n{average_year_string(year, len(entries))}"
+ (
"\n\n__Total costs__:\n"
+ "\n".join([cost_string(prices[currency]["prices"], currency) for currency in prices])
+ "\n\n"
+ "\n".join([entry_string(entry, timezone) for entry in entries])
chunks = [entries[i:i + items_per_page] for i in range(0, len(entries), items_per_page)]
embeds = []

for i, chunk in enumerate(chunks):
prices = calculate_prices(chunk, None).get("default_group", {})

embed = discord.Embed(
title=f"Bubble tea entries {f'for {year}' if year else 'for the past year'} 🧋",
color=discord.Color.blue(),
)
if len(entries)
else ""
)
return embed

embed.description = (
f"For <@{user_id}>: **{total_entries} total entries**\n{average_year_string(year, total_entries)}"
+ (
"\n\n__Total costs (all entries)__:\n"
+ "\n".join([cost_string(total_prices[currency]["prices"], currency) for currency in total_prices])
+ "\n\n__Current page entries:__\n"
+ "\n".join([entry_string(entry, timezone) for entry in chunk])
)
if len(chunk)
else ""
)
embed.set_footer(text=f"Page {i+1}/{len(chunks)} • Total entries: {total_entries}")
embeds.append(embed)

return embeds

def bbt_list_grouped_embed(
user_id: int,
entries: list[dict],
year: int,
year: int | None,
timezone: datetime.tzinfo,
group_by: str,
total_prices: dict = None,
items_per_page: int = 10,
):
prices = calculate_prices(entries, group_by)
embed = discord.Embed(
title=f"Bubble tea entries {f'for {year}' if year else 'for the past year'} grouped by {group_by} 🧋",
color=discord.Color.blue(),
)
embed.description = f"For <@{user_id}>: **{len(entries)} total entries**"
organized_data = organize_entries_by_group(entries, group_by)
embeds = []
total_entries = len(entries)

for group in prices:
group_entries = [entry for entry in entries if entry[group_by] == group]
embed.description += f"\n\n---\n**{group}: {len(group_entries)} entries**"
for currency in prices[group]:
embed.description += f"\n{currency}: {cost_string(prices[group][currency]['prices'], currency)}"
embed.description += "\n\n"
embed.description += "\n".join([entry_string(entry, timezone) for entry in group_entries])
return embed
for group_name, group_data in organized_data.items():
group_entries = group_data["entries"]
chunks = [group_entries[i:i + items_per_page] for i in range(0, len(group_entries), items_per_page)]

for i, chunk in enumerate(chunks):
embed = discord.Embed(
title=f"Bubble tea entries {f'for {year}' if year else 'for the past year'} grouped by {group_by} 🧋",
color=discord.Color.blue(),
)

# Add total information
embed.description = f"For <@{user_id}>: **{total_entries} total entries**"

if i == 0: # Only for first page of each group
embed.description += "\n\n__Total costs (all entries)__:\n"
embed.description += "\n".join([
cost_string(total_prices[currency]["prices"], currency)
for currency in total_prices
])

# Add group information
embed.description += f"\n\n---\n**{group_name}: {len(group_entries)} entries**"
for currency in group_data["prices"]:
embed.description += f"\n{currency}: {cost_string(group_data['prices'][currency]['prices'], currency)}"

# Add entries for this chunk
embed.description += "\n\n"
embed.description += "\n".join([
entry_string(entry, timezone)
for entry in chunk
])

embed.set_footer(text=f"Group: {group_name} • Page {i+1}/{len(chunks)} • Total entries: {total_entries}")
embeds.append(embed)

return embeds


def bbt_stats_embed(
Expand Down
30 changes: 30 additions & 0 deletions commands/bbt_count/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,36 @@ def calculate_prices(entries: list[dict], group_by: str):

return prices

def organize_entries_by_group(entries: list[dict], group_by: str = None):
"""Organize entries into groups and calculate statistics"""
if not group_by:
return {
"default_group": {
"entries": entries,
"prices": calculate_prices(entries, None)["default_group"]
}
}

groups = {}
for entry in entries:
group_key = entry.get(group_by, "Unknown")
if group_key not in groups:
groups[group_key] = {
"entries": [],
"prices": {}
}
groups[group_key]["entries"].append(entry)

# Calculate prices for each group
for group_key, group_data in groups.items():
group_data["prices"] = calculate_prices(group_data["entries"], None)["default_group"]

# Sort groups by number of entries
return dict(sorted(
groups.items(),
key=lambda x: len(x[1]["entries"]),
reverse=True
))

def cost_string(prices: list[float], currency: str):
p = np.array(prices)
Expand Down

0 comments on commit baebdc4

Please sign in to comment.