fix error when add word with id exits

This commit is contained in:
2025-09-18 10:29:46 +07:00
parent 670c124943
commit a86b0be26e
4 changed files with 51 additions and 10 deletions
+20
View File
@@ -14,6 +14,9 @@ CHANNEL_HOME_DEBT_ID=1234567890123456789
# Game Nối Từ - Hỗ trợ nhiều channel với dấu phẩy # Game Nối Từ - Hỗ trợ nhiều channel với dấu phẩy
CHANNEL_NOI_TU_ID=1383424686708363336,9876543210987654321,5555555555555555555 CHANNEL_NOI_TU_ID=1383424686708363336,9876543210987654321,5555555555555555555
# Admin IDs - Hỗ trợ nhiều admin với dấu phẩy
ADMIN_IDS=123456789012345678,987654321098765432
``` ```
## Các ví dụ khác nhau ## Các ví dụ khác nhau
@@ -33,6 +36,18 @@ CHANNEL_NOI_TU_ID=1383424686708363336,9876543210987654321
CHANNEL_NOI_TU_ID=1383424686708363336,9876543210987654321,5555555555555555555 CHANNEL_NOI_TU_ID=1383424686708363336,9876543210987654321,5555555555555555555
``` ```
### Admin IDs
```bash
# 1 admin
ADMIN_IDS=123456789012345678
# 2 admin
ADMIN_IDS=123456789012345678,987654321098765432
# 3+ admin
ADMIN_IDS=123456789012345678,987654321098765432,555555555555555555
```
## Lưu ý quan trọng ## Lưu ý quan trọng
-**Đúng**: `CHANNEL_NOI_TU_ID=123,456,789` -**Đúng**: `CHANNEL_NOI_TU_ID=123,456,789`
@@ -40,6 +55,11 @@ CHANNEL_NOI_TU_ID=1383424686708363336,9876543210987654321,5555555555555555555
-**Sai**: `CHANNEL_NOI_TU_ID="123,456,789"` (có dấu ngoặc kép) -**Sai**: `CHANNEL_NOI_TU_ID="123,456,789"` (có dấu ngoặc kép)
-**Sai**: `CHANNEL_NOI_TU_ID=123,abc,789` (có ký tự không phải số) -**Sai**: `CHANNEL_NOI_TU_ID=123,abc,789` (có ký tự không phải số)
-**Đúng**: `ADMIN_IDS=123456789,987654321`
-**Sai**: `ADMIN_IDS=123456789, 987654321` (có khoảng trắng)
-**Sai**: `ADMIN_IDS="123456789,987654321"` (có dấu ngoặc kép)
-**Sai**: `ADMIN_IDS=123456789,abc123` (có ký tự không phải số)
## Cách test ## Cách test
1. Cập nhật file `.env` với format mới 1. Cập nhật file `.env` với format mới
+8 -9
View File
@@ -1,6 +1,6 @@
import discord import discord
import asyncio import asyncio
from core.bot import bot, CHANNEL_NOI_TU_IDS from core.bot import bot, CHANNEL_NOI_TU_IDS, ADMIN_IDS
from typing import Set, Dict from typing import Set, Dict
from datetime import datetime from datetime import datetime
from apps.score import incr from apps.score import incr
@@ -43,7 +43,7 @@ def get_game_for_channel(channel_id: int) -> NoiTuGame:
def is_admin(ctx): def is_admin(ctx):
"""Kiểm tra xem user có phải là admin không""" """Kiểm tra xem user có phải là admin không"""
return ctx.author.guild_permissions.administrator return ctx.author.id in ADMIN_IDS
def is_correct_channel(ctx): def is_correct_channel(ctx):
"""Kiểm tra xem command có được thực hiện trong đúng channel không""" """Kiểm tra xem command có được thực hiện trong đúng channel không"""
@@ -225,12 +225,7 @@ async def add_word(ctx, *, word: str):
await ctx.send("❌ Từ phải có đúng 2 từ ghép!") await ctx.send("❌ Từ phải có đúng 2 từ ghép!")
return return
# Kiểm tra từ đã tồn tại chưa # Thêm từ (repository sẽ tự kiểm tra duplicate)
if await get_noi_tu_repo().is_exist(word):
await ctx.send(f"❌ Từ '{word}' đã tồn tại trong cơ sở dữ liệu!")
return
# Thêm từ
success = await get_noi_tu_repo().add(word) success = await get_noi_tu_repo().add(word)
if success: if success:
embed = discord.Embed( embed = discord.Embed(
@@ -240,7 +235,11 @@ async def add_word(ctx, *, word: str):
) )
await ctx.send(embed=embed) await ctx.send(embed=embed)
else: else:
await ctx.send("❌ Có lỗi xảy ra khi thêm từ!") # Kiểm tra xem có phải do duplicate không
if await get_noi_tu_repo().is_exist(word):
await ctx.send(f"❌ Từ '{word}' đã tồn tại trong cơ sở dữ liệu!")
else:
await ctx.send("❌ Có lỗi xảy ra khi thêm từ!")
@bot.command(name='remove') @bot.command(name='remove')
async def remove_word(ctx, *, word: str): async def remove_word(ctx, *, word: str):
+10
View File
@@ -35,6 +35,16 @@ if channel_noi_tu_env:
# Giữ lại CHANNEL_NOI_TU_ID cho backward compatibility (lấy ID đầu tiên) # Giữ lại CHANNEL_NOI_TU_ID cho backward compatibility (lấy ID đầu tiên)
CHANNEL_NOI_TU_ID = CHANNEL_NOI_TU_IDS[0] if CHANNEL_NOI_TU_IDS else 0 CHANNEL_NOI_TU_ID = CHANNEL_NOI_TU_IDS[0] if CHANNEL_NOI_TU_IDS else 0
# Admin IDs - Hỗ trợ nhiều admin với format: ID1,ID2,ID3
ADMIN_IDS = []
admin_ids_env = os.getenv('ADMIN_IDS', '')
if admin_ids_env:
for admin_id in admin_ids_env.split(','):
try:
ADMIN_IDS.append(int(admin_id.strip()))
except ValueError:
print(f"Invalid admin ID: {admin_id}")
@bot.tree.command(name='help', description='Show help') @bot.tree.command(name='help', description='Show help')
async def help(interaction: discord.Interaction): async def help(interaction: discord.Interaction):
+13 -1
View File
@@ -25,8 +25,20 @@ class NoiTuRepository:
async def add(self, word: str) -> bool: async def add(self, word: str) -> bool:
"""Thêm từ vào bảng""" """Thêm từ vào bảng"""
try: try:
# Kiểm tra từ đã tồn tại chưa trước khi thêm
if await self.is_exist(word):
print(f"Word '{word}' already exists")
return False
async with self.Session() as session: async with self.Session() as session:
noi_tu = DiscordNoiTu(word=word) # Lấy ID cao nhất hiện tại và tạo ID mới
stmt = select(DiscordNoiTu.id).order_by(DiscordNoiTu.id.desc()).limit(1)
result = await session.execute(stmt)
max_id = result.scalar_one_or_none()
next_id = (max_id + 1) if max_id is not None else 1
# Tạo object với ID cụ thể
noi_tu = DiscordNoiTu(id=next_id, word=word)
session.add(noi_tu) session.add(noi_tu)
await session.commit() await session.commit()
return True return True