feat: add rank

This commit is contained in:
tramoc
2025-06-25 13:41:59 +07:00
parent 59f1e477e4
commit 9ebaac578a
4 changed files with 54 additions and 5 deletions
+19 -1
View File
@@ -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") await ctx.send("Có lỗi xảy ra khi tạo tài khoản currency")
return return
await ctx.send(f"Thông tin tài khoản của bạn: {currency.balance}") 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)
+4 -1
View File
@@ -5,6 +5,7 @@ from core.bot import bot
from discord.ext import commands from discord.ext import commands
from typing import Dict, Set, Optional from typing import Dict, Set, Optional
from datetime import datetime, timedelta from datetime import datetime, timedelta
from apps.currency import incr
# Lazy load repository để tránh lỗi database connection # Lazy load repository để tránh lỗi database connection
noi_tu_repo = None 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}**", value=f"**{game.last_player_name}** - Từ cuối: **{game.current_word}**",
inline=False inline=False
) )
await incr(game.last_player_id, game.last_player_name, 1)
await ctx.send(embed=embed) 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}**", value=f"**{game.last_player_name}** - Từ cuối: **{game.current_word}**",
inline=False inline=False
) )
await incr(game.last_player_id, game.last_player_name, 1)
if game.channel: if game.channel:
await game.channel.send(embed=embed) await game.channel.send(embed=embed)
@@ -359,7 +362,7 @@ async def handle_game_message(message):
await message.add_reaction('') await message.add_reaction('')
return return
with game.lock: async with game.lock:
if not is_valid(game.current_word, word): if not is_valid(game.current_word, word):
return return
# Từ hợp lệ # Từ hợp lệ
+2 -1
View File
@@ -6,6 +6,7 @@ from typing import Optional
class DiscordCurrency: class DiscordCurrency:
id: Optional[int] id: Optional[int]
user_id: int user_id: int
user_name: str
balance: int balance: int
updated_at: datetime updated_at: datetime
@@ -21,4 +22,4 @@ class DiscordCurrency:
"user_id": self.user_id, "user_id": self.user_id,
"balance": self.balance, "balance": self.balance,
"updated_at": self.updated_at "updated_at": self.updated_at
} }
+29 -2
View File
@@ -61,12 +61,13 @@ class CurrencyRepository:
async def get_all(self) -> List[DiscordCurrency]: async def get_all(self) -> List[DiscordCurrency]:
"""Lấy tất cả thông tin thành viên""" """Lấy tất cả thông tin thành viên"""
try: try:
response = self.table.select('*').execute() response = self.table.select('*').order("balance", desc=True).execute()
currencies = [] currencies = []
for data in response.data: for data in response.data:
currencies.append(DiscordCurrency( currencies.append(DiscordCurrency(
id=data.get('id'), id=data.get('id'),
user_id=data['user_id'], user_id=data['user_id'],
user_name=data['user_name'],
balance=data['balance'], balance=data['balance'],
updated_at=datetime.fromisoformat(data['updated_at'].replace('Z', '+00:00')) if data['updated_at'] else datetime.now() 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 return currencies
except Exception as e: except Exception as e:
print(f"Error getting all users with sort by balance: {e}") print(f"Error getting all users with sort by balance: {e}")
return [] 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