File size: 5,679 Bytes
4fd8a6e
 
 
 
 
 
eb86f44
7ebd271
4fd8a6e
 
b6c887c
4fd8a6e
 
 
b6c887c
4fd8a6e
 
 
 
 
 
 
 
 
b6c887c
4fd8a6e
 
 
c1d90dd
4fd8a6e
 
 
eb86f44
 
 
4fd8a6e
 
 
 
b6c887c
4fd8a6e
 
 
eb86f44
b6c887c
 
eb86f44
 
 
 
 
b6c887c
 
eb86f44
4fd8a6e
 
 
b6c887c
 
 
 
4fd8a6e
 
 
b6c887c
4fd8a6e
 
 
b6c887c
4fd8a6e
 
eb86f44
4fd8a6e
 
 
 
b6c887c
4fd8a6e
 
b6c887c
4fd8a6e
eb86f44
 
f73e368
 
b6c887c
eb86f44
b6c887c
 
 
4fd8a6e
eb86f44
4fd8a6e
b6c887c
4fd8a6e
 
eb86f44
 
 
 
4fd8a6e
b6c887c
 
 
4fd8a6e
eb86f44
b6c887c
eb86f44
 
b6c887c
 
 
 
 
7ebd271
 
 
 
eb86f44
7ebd271
eb86f44
7ebd271
eb86f44
 
 
 
 
b6c887c
7ebd271
 
 
b6c887c
7ebd271
b6c887c
eb86f44
 
7ebd271
b6c887c
eb86f44
b6c887c
 
 
4fd8a6e
 
eb86f44
b6c887c
eb86f44
b6c887c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
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.")