From 9ebaac578ae2031dfb712e113155540bf5914cc6 Mon Sep 17 00:00:00 2001 From: tramoc Date: Wed, 25 Jun 2025 13:41:59 +0700 Subject: [PATCH] feat: add rank --- apps/currency.py | 20 +++++++++++++++++++- apps/noi_tu.py | 5 ++++- models/currency.py | 3 ++- repositories/currency.py | 31 +++++++++++++++++++++++++++++-- 4 files changed, 54 insertions(+), 5 deletions(-) diff --git a/apps/currency.py b/apps/currency.py index d5ecc65..5a62243 100644 --- a/apps/currency.py +++ b/apps/currency.py @@ -17,4 +17,22 @@ async def currency_check(ctx: commands.Context): await ctx.send("Có lỗi xảy ra khi tạo tài khoản currency") return - await ctx.send(f"Thông tin tài khoản của bạn: {currency.balance}") \ No newline at end of file + await ctx.send(f"Thông tin tài khoản của bạn: {currency.balance}") + +@bot.command(name="rank", description="list rank") +async def list_rank(ctx: commands.Context): + """Kiểm tra thông tin tài khoản của bạn""" + # Check if user is registered in database. If not, create a new one + balances = await currency_repo.get_all() + msg = "```\n" + msg += f"{'No.':<4} {'Name':<20} {'Win':>8}\n" + msg += "-" * 34 + "\n" + for i, b in enumerate(balances, start=1): + msg += f"{i:<4} {b.user_name:<20} {b.balance:>8}\n" + msg += "```" + + await ctx.send(msg) + +async def incr(user_id, user_name, amount): + await currency_repo.upsert_or_increment_balance(user_id, user_name, amount) + diff --git a/apps/noi_tu.py b/apps/noi_tu.py index 805e1df..7ed7841 100644 --- a/apps/noi_tu.py +++ b/apps/noi_tu.py @@ -5,6 +5,7 @@ from core.bot import bot from discord.ext import commands from typing import Dict, Set, Optional from datetime import datetime, timedelta +from apps.currency import incr # Lazy load repository để tránh lỗi database connection noi_tu_repo = None @@ -186,6 +187,7 @@ async def end_game(ctx): value=f"**{game.last_player_name}** - Từ cuối: **{game.current_word}**", inline=False ) + await incr(game.last_player_id, game.last_player_name, 1) await ctx.send(embed=embed) @@ -291,6 +293,7 @@ async def game_timeout(): value=f"**{game.last_player_name}** - Từ cuối: **{game.current_word}**", inline=False ) + await incr(game.last_player_id, game.last_player_name, 1) if game.channel: await game.channel.send(embed=embed) @@ -359,7 +362,7 @@ async def handle_game_message(message): await message.add_reaction('❌') return - with game.lock: + async with game.lock: if not is_valid(game.current_word, word): return # Từ hợp lệ diff --git a/models/currency.py b/models/currency.py index 4719ad2..a494b90 100644 --- a/models/currency.py +++ b/models/currency.py @@ -6,6 +6,7 @@ from typing import Optional class DiscordCurrency: id: Optional[int] user_id: int + user_name: str balance: int updated_at: datetime @@ -21,4 +22,4 @@ class DiscordCurrency: "user_id": self.user_id, "balance": self.balance, "updated_at": self.updated_at - } \ No newline at end of file + } diff --git a/repositories/currency.py b/repositories/currency.py index b901548..d90ec0a 100644 --- a/repositories/currency.py +++ b/repositories/currency.py @@ -61,12 +61,13 @@ class CurrencyRepository: async def get_all(self) -> List[DiscordCurrency]: """Lấy tất cả thông tin thành viên""" try: - response = self.table.select('*').execute() + response = self.table.select('*').order("balance", desc=True).execute() currencies = [] for data in response.data: currencies.append(DiscordCurrency( id=data.get('id'), user_id=data['user_id'], + user_name=data['user_name'], balance=data['balance'], updated_at=datetime.fromisoformat(data['updated_at'].replace('Z', '+00:00')) if data['updated_at'] else datetime.now() )) @@ -108,4 +109,30 @@ class CurrencyRepository: return currencies except Exception as e: print(f"Error getting all users with sort by balance: {e}") - return [] \ No newline at end of file + return [] + + async def upsert_or_increment_balance(self, user_id: str, user_name: str, amount: int) -> Optional[int]: + try: + response = self.table.select("*").eq("user_id", user_id).execute() + user_data = response.data[0] if response.data else None + + now_str = datetime.utcnow().isoformat() + "Z" + + if user_data: + new_balance = user_data["balance"] + amount + update_resp = self.table.update({ + "balance": new_balance, + "updated_at": now_str + }).eq("user_id", user_id).execute() + return new_balance + else: + insert_resp = self.table.insert({ + "user_id": user_id, + "user_name": user_name, + "balance": amount, + "updated_at": now_str + }).execute() + return amount + except Exception as e: + print(f"Error upserting balance for user {user_id}: {e}") + return None