-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
169 lines (150 loc) · 4.86 KB
/
main.py
File metadata and controls
169 lines (150 loc) · 4.86 KB
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import discord
from discord.ext import commands
import asyncio
import logging
from flask import Flask, request
import threading
import os
import sqlite3
# -----------------------------
# 환경변수
TOKEN = os.environ.get("DISCORD_BOT_TOKEN")
LOG_CHANNEL_ID = 1417052732019310652
PORT = 10000
DB_PATH = "db.sqlite"
# -----------------------------
# 로깅 설정
logger = logging.getLogger("takkari")
logger.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter("[%(asctime)s] [%(levelname)s] %(message)s"))
logger.addHandler(console_handler)
# -----------------------------
# Flask 서버
app = Flask(__name__)
@app.route("/")
def home():
return "Takkari Bot Server is running!"
# DB 저장
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("INSERT INTO riot_codes (code) VALUES (?)", (code,))
conn.commit()
conn.close()
def run_flask():
logger.info(f"Flask 서버 시작 (포트 {PORT})")
app.run(host="0.0.0.0", port=PORT)
# -----------------------------
# Discord Bot 로그 핸들러
class DiscordLogHandler(logging.Handler):
def __init__(self, bot, channel_id):
super().__init__()
self.bot = bot
self.channel_id = channel_id
self.queue = asyncio.Queue()
self.worker_started = False
async def log_worker(self):
await self.bot.wait_until_ready()
channel = self.bot.get_channel(self.channel_id)
while True:
log_entry = await self.queue.get()
try:
if channel:
await channel.send(f"```{log_entry}```")
except Exception as e:
print("Log send error:", e)
def emit(self, record):
log_entry = self.format(record)
try:
self.queue.put_nowait(log_entry)
except Exception as e:
print("Queue put error:", e)
# -----------------------------
# Bot 초기화
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="/", intents=intents)
# setup_hook에서 worker 등록
@bot.event
async def setup_hook():
if not hasattr(bot, "log_worker_started"):
bot.log_worker_started = True
handler_task = bot.loop.create_task(discord_handler.log_worker())
# Discord 로그 채널 핸들러 연결
discord_handler = DiscordLogHandler(bot, LOG_CHANNEL_ID)
formatter = logging.Formatter("[%(asctime)s] [%(levelname)s] %(message)s")
discord_handler.setFormatter(formatter)
logger.addHandler(discord_handler)
# -----------------------------
# DB 초기화
def init_db():
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users(
id INTEGER PRIMARY KEY,
name TEXT
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS riot_codes(
id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT NOT NULL
)
""")
conn.commit()
conn.close()
logger.info("✅ DB 초기화 완료")
# -----------------------------
# 코그 로딩
async def load_cogs():
cogs = [
"takkari_bot.cogs.userinfo",
"takkari_bot.cogs.announce",
"takkari_bot.cogs.dm_feature",
"takkari_bot.cogs.support",
"takkari_bot.cogs.help",
"takkari_bot.cogs.patchnote",
"takkari_bot.cogs.dblookup",
"takkari_bot.cogs.updown",
"takkari_bot.cogs.schedule",
"takkari_bot.cogs.loglookup",
"takkari_bot.cogs.riot"
]
for cog in cogs:
try:
await bot.load_extension(cog)
logger.info(f"✅ {cog} 로드 완료")
except Exception as e:
logger.exception(f"❌ {cog} 로드 실패: {e}")
# -----------------------------
# 봇 이벤트
@bot.event
async def on_ready():
logger.info(f"봇 시작 완료: {bot.user}")
async def status_task():
while True:
try:
guild_count = len(bot.guilds)
member_count = sum(g.member_count for g in bot.guilds)
statuses = [
discord.Game(f"{guild_count}개의 서버에서 활동 ✨"),
discord.Game(f"{member_count}명의 유저와 함께 👥"),
discord.Game("🔥 따까리봇 업데이트 진행"),
]
for status in statuses:
await bot.change_presence(status=discord.Status.online, activity=status)
await asyncio.sleep(10)
except Exception as e:
logger.error(f"Presence 업데이트 중 오류: {e}")
await asyncio.sleep(10)
bot.loop.create_task(status_task())
# -----------------------------
# 메인 실행
async def main():
init_db()
await load_cogs()
threading.Thread(target=run_flask, daemon=True).start()
await bot.start(TOKEN)
if __name__ == "__main__":
asyncio.run(main())