abcs-noob commited on
Commit
eb86f44
·
verified ·
1 Parent(s): 716c8ec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -41
app.py CHANGED
@@ -4,12 +4,14 @@ import os
4
  import asyncio
5
  import json
6
  import threading
 
7
  from http.server import HTTPServer, BaseHTTPRequestHandler
8
 
9
  # --- CẤU HÌNH ---
10
  DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
11
  GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
12
 
 
13
  client_ai = genai.Client(api_key=GEMINI_API_KEY)
14
 
15
  MODERATION_PROMPT = """
@@ -22,24 +24,14 @@ Nếu không vi phạm: {"violation": false, "reason": "", "confidence": 1.0}
22
  # --- LOGIC AI ---
23
  async def analyze_message(content):
24
  try:
25
- # Ưu tiên Gemini 3 Flash cho tốc độ
26
  response = client_ai.models.generate_content(
27
- model="gemini-3-flash",
28
  contents=content,
29
  config={'system_instruction': MODERATION_PROMPT, 'response_mime_type': 'application/json'}
30
  )
31
- result = json.loads(response.text)
32
-
33
- # Nếu chưa chắc chắn, dùng Gemma 3 27B để thẩm định sâu
34
- if not result['violation'] and result.get('confidence', 1.0) < 0.8:
35
- gemma_res = client_ai.models.generate_content(
36
- model="gemma-3-27b",
37
- contents=f"Kiểm tra kỹ câu này xem có chửi thề ẩn ý hoặc lách luật không: {content}",
38
- config={'response_mime_type': 'application/json'}
39
- )
40
- result = json.loads(gemma_res.text)
41
- return result
42
- except:
43
  return {"violation": False, "reason": "", "confidence": 0}
44
 
45
  # --- CẤU HÌNH DISCORD BOT ---
@@ -48,16 +40,18 @@ intents.message_content = True
48
  bot = discord.Client(intents=intents)
49
 
50
  async def get_webhook(channel):
51
- # Tìm webhook có sẵn do bot tạo hoặc tạo mới
52
- webhooks = await channel.webhooks()
53
- for wh in webhooks:
54
- if wh.name == "GeminiGuard":
55
- return wh
56
- return await channel.create_webhook(name="GeminiGuard")
 
 
57
 
58
  @bot.event
59
  async def on_ready():
60
- print(f'✅ Bot Webhook đã sẵn sàng: {bot.user}')
61
 
62
  @bot.event
63
  async def on_message(message):
@@ -66,39 +60,62 @@ async def on_message(message):
66
 
67
  analysis = await analyze_message(message.content)
68
 
69
- if analysis['violation']:
70
  try:
71
- # 1. Lấy thông tin người dùng
72
  username = message.author.display_name
73
  avatar_url = message.author.display_avatar.url
74
 
75
- # 2. Xóa tin nhắn gốc
76
  await message.delete()
77
 
78
- # 3. Gửi tin nhắn thay thế qua Webhook
79
  webhook = await get_webhook(message.channel)
80
- await webhook.send(
81
- content=f"#### *(Tin nhắn đã bị ẩn do: {analysis['reason']})*",
82
- username=username,
83
- avatar_url=avatar_url
84
- )
85
-
86
- print(f"Đã xử lý tin nhắn của {username} qua Webhook.")
87
-
88
- except discord.Forbidden:
89
- print("Thiếu quyền 'Manage Messages' hoặc 'Manage Webhooks'.")
90
  except Exception as e:
91
- print(f"Lỗi: {e}")
92
 
93
- # --- KEEP ALIVE SERVER ---
94
  class HealthCheckHandler(BaseHTTPRequestHandler):
95
  def do_GET(self):
96
- self.send_response(200); self.end_headers()
97
- self.wfile.write(b"Bot is online!")
 
 
98
 
99
  def run_web_server():
100
- HTTPServer(('0.0.0.0', 7860), HealthCheckHandler).serve_forever()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  if __name__ == "__main__":
 
103
  threading.Thread(target=run_web_server, daemon=True).start()
104
- bot.run(DISCORD_TOKEN)
 
 
 
 
 
 
4
  import asyncio
5
  import json
6
  import threading
7
+ import aiohttp
8
  from http.server import HTTPServer, BaseHTTPRequestHandler
9
 
10
  # --- CẤU HÌNH ---
11
  DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
12
  GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
13
 
14
+ # Khởi tạo Gemini Client
15
  client_ai = genai.Client(api_key=GEMINI_API_KEY)
16
 
17
  MODERATION_PROMPT = """
 
24
  # --- LOGIC AI ---
25
  async def analyze_message(content):
26
  try:
 
27
  response = client_ai.models.generate_content(
28
+ model="gemini-2.0-flash", # Cập nhật model mới nhất cho 2026
29
  contents=content,
30
  config={'system_instruction': MODERATION_PROMPT, 'response_mime_type': 'application/json'}
31
  )
32
+ return json.loads(response.text)
33
+ except Exception as e:
34
+ print(f"⚠️ Lỗi AI: {e}")
 
 
 
 
 
 
 
 
 
35
  return {"violation": False, "reason": "", "confidence": 0}
36
 
37
  # --- CẤU HÌNH DISCORD BOT ---
 
40
  bot = discord.Client(intents=intents)
41
 
42
  async def get_webhook(channel):
43
+ try:
44
+ webhooks = await channel.webhooks()
45
+ for wh in webhooks:
46
+ if wh.name == "GeminiGuard":
47
+ return wh
48
+ return await channel.create_webhook(name="GeminiGuard")
49
+ except:
50
+ return None
51
 
52
  @bot.event
53
  async def on_ready():
54
+ print(f'✅ Bot đã kết nối thành công: {bot.user}')
55
 
56
  @bot.event
57
  async def on_message(message):
 
60
 
61
  analysis = await analyze_message(message.content)
62
 
63
+ if analysis.get('violation'):
64
  try:
 
65
  username = message.author.display_name
66
  avatar_url = message.author.display_avatar.url
67
 
 
68
  await message.delete()
69
 
 
70
  webhook = await get_webhook(message.channel)
71
+ if webhook:
72
+ await webhook.send(
73
+ content=f"#### *(Tin nhắn ẩn do: {analysis['reason']})*",
74
+ username=username,
75
+ avatar_url=avatar_url
76
+ )
 
 
 
 
77
  except Exception as e:
78
+ print(f"❌ Lỗi xử lý tin nhắn: {e}")
79
 
80
+ # --- HEALTH CHECK SERVER ---
81
  class HealthCheckHandler(BaseHTTPRequestHandler):
82
  def do_GET(self):
83
+ self.send_response(200)
84
+ self.send_header('Content-type', 'text/plain')
85
+ self.end_headers()
86
+ self.wfile.write(b"Bot is online and healthy!")
87
 
88
  def run_web_server():
89
+ server = HTTPServer(('0.0.0.0', 7860), HealthCheckHandler)
90
+ print("🌍 Web Server running on port 7860")
91
+ server.serve_forever()
92
+
93
+ # --- HÀM KHỞI CHẠY CHÍNH (SỬA LỖI DNS) ---
94
+ async def start_bot_safely():
95
+ # Ép sử dụng IPv4 bằng TCPConnector
96
+ connector = aiohttp.TCPConnector(family=2) # 2 = socket.AF_INET
97
+
98
+ async with aiohttp.ClientSession(connector=connector) as session:
99
+ # Ghi đè session của bot bằng session IPv4 của chúng ta
100
+ bot.http.connector = connector
101
+
102
+ retry_count = 0
103
+ while True:
104
+ try:
105
+ print(f"📡 Đang kết nối Discord (Lần thử {retry_count + 1})...")
106
+ await bot.start(DISCORD_TOKEN)
107
+ except Exception as e:
108
+ retry_count += 1
109
+ print(f"❌ Lỗi kết nối: {e}")
110
+ print("🔄 Sẽ thử lại sau 15 giây...")
111
+ await asyncio.sleep(15)
112
 
113
  if __name__ == "__main__":
114
+ # 1. Chạy Web Server trong thread riêng
115
  threading.Thread(target=run_web_server, daemon=True).start()
116
+
117
+ # 2. Chạy Bot bằng Event Loop để xử lý lỗi DNS/IPv4 triệt để
118
+ try:
119
+ asyncio.run(start_bot_safely())
120
+ except KeyboardInterrupt:
121
+ print("Bot stopped by user.")