abcs-noob's picture
Update app.py
f73e368 verified
Raw History Blame Contribute Delete
5.68 kB
import discord
from google import genai
import os
import asyncio
import json
import threading
import aiohttp
import socket
from http.server import HTTPServer, BaseHTTPRequestHandler
# --- CẤU HÌNH BIẾN MÔI TRƯỜNG ---
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
# Khởi tạo Gemini Client (Dùng bản 2.0 Flash cho năm 2026)
client_ai = genai.Client(api_key=GEMINI_API_KEY)
MODERATION_PROMPT = """
Bạn là kiểm duyệt viên Discord. Phân tích tin nhắn tiếng Việt (kể cả teencode, viết lách luật).
Nếu vi phạm (Toxic, Sex, Scam, Hate Speech), trả về JSON:
{"violation": true, "reason": "Lý do ngắn gọn", "confidence": 0.9}
Nếu không vi phạm: {"violation": false, "reason": "", "confidence": 1.0}
"""
# --- LOGIC PHÂN TÍCH AI ---
async def analyze_message(content):
try:
response = client_ai.models.generate_content(
model="gemini-2.5-flash",
contents=content,
config={'system_instruction': MODERATION_PROMPT, 'response_mime_type': 'application/json'}
)
return json.loads(response.text)
except Exception as e:
print(f"⚠️ Lỗi AI: {e}")
return {"violation": False, "reason": "", "confidence": 0}
# --- CẤU HÌNH DISCORD BOT ---
intents = discord.Intents.default()
intents.message_content = True # BẮT BUỘC: Phải bật trong Developer Portal
bot = discord.Client(intents=intents)
async def get_webhook(channel):
try:
if not isinstance(channel, discord.TextChannel):
return None
webhooks = await channel.webhooks()
for wh in webhooks:
if wh.name == "GeminiGuard":
return wh
return await channel.create_webhook(name="GeminiGuard")
except Exception as e:
print(f"⚠️ Không thể lấy/tạo Webhook: {e}")
return None
@bot.event
async def on_ready():
print(f"==========================================")
print(f"✅ Bot Online: {bot.user.name}")
print(f"✅ ID: {bot.user.id}")
print(f"==========================================")
@bot.event
async def on_message(message):
# Bỏ qua tin nhắn của bot hoặc tin nhắn trống
if message.author == bot.user or not message.content:
return
# Gửi tin nhắn qua AI phân tích
analysis = await analyze_message(message.content)
if analysis.get('violation'):
try:
username = message.author.display_name
avatar_url = message.author.display_avatar.url
# Xóa tin nhắn toxic
await message.delete()
# Gửi tin nhắn thay thế qua Webhook
webhook = await get_webhook(message.channel)
if webhook:
await webhook.send(
content=f"####",
username="Abc's Noob Moderation",
avatar_url="https://uxwing.com/wp-content/themes/uxwing/download/shield-protection-security/shield-security-icon.png"
)
print(f"🛡️ Đã xử lý vi phạm từ: {username}")
except discord.Forbidden:
print(f"❌ Lỗi: Bot thiếu quyền 'Manage Messages' hoặc 'Manage Webhooks' tại channel {message.channel}")
except Exception as e:
print(f"❌ Lỗi xử lý tin nhắn: {e}")
# --- WEB SERVER GIỮ CHO BOT LUÔN CHẠY (PORT 7860) ---
class HealthCheckHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(b"Bot is online and healthy!")
def log_message(self, format, *args):
return # Tắt log GET / để tránh làm bẩn bảng console
def run_web_server():
server = HTTPServer(('0.0.0.0', 7860), HealthCheckHandler)
print("🌍 Health Check Server đã sẵn sàng tại cổng 7860")
server.serve_forever()
# --- HÀM KHỞI CHẠY CHÍNH VỚI FIX DNS & SESSION ---
async def main():
# 1. Chạy Web Server trong một Thread riêng
threading.Thread(target=run_web_server, daemon=True).start()
# 2. CẤU HÌNH DNS THỦ CÔNG ĐỂ VƯỢT LỖI [No address associated with hostname]
# Sử dụng Google DNS (8.8.8.8) để phân giải discord.com
resolver = aiohttp.AsyncResolver(nameservers=["8.8.8.8", "8.8.4.4"])
connector = aiohttp.TCPConnector(resolver=resolver, family=socket.AF_INET)
# Khởi tạo session với DNS đã cấu hình
async with aiohttp.ClientSession(connector=connector) as session:
# Gán connector này vào hệ thống của bot
bot.http.connector = connector
retry_count = 0
while True:
try:
print(f"📡 Đang kết nối tới Discord Gateway (Lần {retry_count + 1})...")
# Xóa bot.start cũ và dùng cách chạy chuẩn nhất
await bot.login(DISCORD_TOKEN)
await bot.connect()
except discord.errors.LoginFailure:
print("❌ LỖI: Token Discord không hợp lệ!")
break
except Exception as e:
retry_count += 1
print(f"⚠️ Lỗi kết nối (DNS/Mạng): {e}")
print("🔄 Thử lại sau 15 giây...")
await asyncio.sleep(15)
finally:
if not bot.is_closed():
await bot.close()
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("👋 Bot đã dừng.")