-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared.py
More file actions
153 lines (126 loc) · 4.89 KB
/
Copy pathshared.py
File metadata and controls
153 lines (126 loc) · 4.89 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
import asyncio
import os
import threading
import time
import discord
import sentry_sdk
from flask import Flask
from flask_cors import CORS
from notion_client import Client
from sentry_sdk.integrations.flask import FlaskIntegration
# Import custom BotFork class
from modules.bot.discord_modules.bot import BotFork
from modules.utils.base import Base
from modules.utils.config import Config
from modules.utils.db import DBConnect
from modules.utils.logging_config import logger
from modules.utils.TokenManager import TokenManager
# Initialize Flask app
app = Flask(
"SoDA internal API",
static_folder=os.path.join(os.path.dirname(os.path.dirname(__file__)), "web/build"),
template_folder=os.path.join(os.path.dirname(os.path.dirname(__file__)), "web/build"),
)
CORS(
app,
resources={
r"/*": {
"origins": [
"http://localhost:3000",
"http://127.0.0.1:3000",
"http://localhost:5173",
"http://127.0.0.1:5173",
"https://thesoda.io",
"https://admin.thesoda.io",
],
"methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
"allow_headers": ["Content-Type", "Authorization", "X-Organization-ID", "X-Organization-Prefix"],
"supports_credentials": True,
}
},
)
# Initialize configuration
config = Config()
# Initialize Sentry
if config.SENTRY_DSN:
sentry_sdk.init(
dsn=config.SENTRY_DSN,
integrations=[FlaskIntegration()],
traces_sample_rate=1.0,
profiles_sample_rate=1.0,
# Enable logs to be sent to Sentry
enable_logs=True,
)
logger.info("Sentry initialized with logging enabled.")
else:
logger.warning("SENTRY_DSN not found in environment. Sentry not initialized.")
# Initialize database connections
db_connect = DBConnect("sqlite:///./data/user.db")
# Initialize TokenManager
tokenManager = TokenManager()
# Import models so their tables are registered with Base.metadata before create_all
import modules.auth.models # noqa: F401, E402
# Ensure all tables are created after all models are imported
Base.metadata.create_all(bind=db_connect.engine)
# Periodic cleanup of expired refresh tokens
def cleanup_expired_tokens():
"""Clean up expired refresh tokens periodically"""
try:
tokenManager.cleanup_expired_refresh_tokens()
logger.info("Cleaned up expired refresh tokens")
except Exception as e:
logger.error(f"Error cleaning up expired tokens: {e}")
# Schedule cleanup every hour
def run_cleanup_scheduler():
"""Run the cleanup scheduler in a separate thread"""
while True:
cleanup_expired_tokens()
time.sleep(3600)
# Start cleanup scheduler in background thread
cleanup_thread = threading.Thread(target=run_cleanup_scheduler, daemon=True)
cleanup_thread.start()
def create_auth_bot(loop: asyncio.AbstractEventLoop) -> BotFork:
"""Create and configure the auth bot (BotFork) instance with a specific event loop."""
logger.info("Creating auth bot instance (BotFork)...")
intents = discord.Intents.default()
intents.members = True
intents.guilds = True
auth_bot_instance = BotFork(intents=intents, loop=loop)
try:
from modules.bot.discord_modules.cogs.GameCog import GameCog
from modules.bot.discord_modules.cogs.HelperCog import HelperCog
from modules.bot.discord_modules.cogs.LeetCodeCog import LeetCodeCog
auth_bot_instance.add_cog(HelperCog(auth_bot_instance))
auth_bot_instance.add_cog(GameCog(auth_bot_instance))
lc_channel_id: int | None = None
lc_role_ping: int | None = None
if config.LEETCODE_CHANNEL_ID:
try:
lc_channel_id = int(config.LEETCODE_CHANNEL_ID)
except ValueError:
logger.warning(
f"Invalid LEETCODE_CHANNEL_ID '{config.LEETCODE_CHANNEL_ID}', daily task will be skipped"
)
if config.LEETCODE_ROLE_PING:
try:
lc_role_ping = int(config.LEETCODE_ROLE_PING)
except ValueError:
logger.warning(f"Invalid LEETCODE_ROLE_PING '{config.LEETCODE_ROLE_PING}', role ping will be skipped")
auth_bot_instance.add_cog(
LeetCodeCog(
bot=auth_bot_instance,
db_connect=db_connect,
channel_id=lc_channel_id,
role_ping=lc_role_ping,
daily_time=config.LEETCODE_DAILY_TIME,
timezone=config.TIMEZONE,
)
)
logger.info("Auth bot cogs (HelperCog, GameCog, LeetCodeCog) registered with BotFork instance.")
except Exception as e:
logger.error(f"Error registering auth bot cogs: {e}", exc_info=True)
return auth_bot_instance
# Initialize Notion client
notion = Client(auth=config.NOTION_API_KEY)
# Initialize bot instance
bot = create_auth_bot(asyncio.get_event_loop())