import asyncio import json import logging import os import re import sys import time from threading import Thread from typing import Any, Dict, List, Literal, Optional, Tuple, Union import discord from discord.abc import Messageable from discord.ext import commands try: from flask import Flask except ImportError: Flask = None try: from dotenv import load_dotenv except ImportError: def load_dotenv(*_args: Any, **_kwargs: Any) -> bool: return False DURATION_PATTERN = re.compile(r"^(\d+)\s*([^\W\d_]+)$") UNIT_ALIASES: Dict[str, str] = { "s": "s", "sec": "s", "secs": "s", "second": "s", "seconds": "s", "giay": "s", "giây": "s", "m": "m", "min": "m", "mins": "m", "minute": "m", "minutes": "m", "phut": "m", "phút": "m", "h": "h", "hr": "h", "hrs": "h", "hour": "h", "hours": "h", "gio": "h", "giờ": "h", } ReminderKey = Tuple[int, str] ReminderRow = Dict[str, Union[int, str]] DeliveryResult = Literal["sent", "transient_failure", "permanent_failure"] LOCAL_CONFIG_PATH = "bot_config.json" LOCAL_CONFIG_KEYS = ( "DISCORD_BOT_TOKEN", "COMMAND_PREFIX", "STORAGE_PATH", "TRIGGER_DEBOUNCE_SECONDS", "REMINDER_RETRY_SECONDS", "RESTART_DELAY_SECONDS", "LOG_LEVEL", ) def get_env_int(name: str, default: int, min_value: Optional[int] = None) -> int: raw_value = os.getenv(name) if raw_value is None: return default try: value = int(raw_value) except ValueError: logging.warning("Invalid %s=%s. Using default=%s", name, raw_value, default) return default if min_value is not None and value < min_value: logging.warning( "%s=%s is below minimum %s. Using %s.", name, value, min_value, min_value, ) return min_value return value def get_env_float(name: str, default: float, min_value: Optional[float] = None) -> float: raw_value = os.getenv(name) if raw_value is None: return default try: value = float(raw_value) except ValueError: logging.warning("Invalid %s=%s. Using default=%s", name, raw_value, default) return default if min_value is not None and value < min_value: logging.warning( "%s=%s is below minimum %s. Using %s.", name, value, min_value, min_value, ) return min_value return value def should_start_keepalive_server() -> bool: raw_value = os.getenv("ENABLE_KEEPALIVE_SERVER", "1") return raw_value.strip().lower() not in {"0", "false", "no", "off"} def start_keepalive_server() -> None: if not should_start_keepalive_server(): logging.info("Keep-alive web server is disabled.") return if Flask is None: logging.warning( "Flask is not installed. Keep-alive web server is skipped. Install requirements to enable it." ) return host = os.getenv("KEEPALIVE_HOST", "0.0.0.0") port = get_env_int("PORT", default=7860, min_value=1) app = Flask("reminder_bot_keepalive") @app.get("/") def index() -> str: return "Reminder Discord Bot is running." @app.get("/health") def health() -> Dict[str, str]: return {"status": "ok", "service": "reminder-discord-bot"} def run_server() -> None: app.run(host=host, port=port, debug=False, use_reloader=False) Thread(target=run_server, name="keepalive-server", daemon=True).start() logging.info("Keep-alive web server started at http://%s:%s", host, port) def load_local_config(config_path: str) -> Dict[str, str]: if not os.path.exists(config_path): return {} try: with open(config_path, "r", encoding="utf-8") as file_handle: raw_config = json.load(file_handle) except (OSError, json.JSONDecodeError): logging.exception("Failed to read %s. Ignoring local config.", config_path) return {} if not isinstance(raw_config, dict): logging.warning("Invalid %s format. Expected a JSON object.", config_path) return {} normalized: Dict[str, str] = {} for key in LOCAL_CONFIG_KEYS: value = raw_config.get(key) if value is None: continue if isinstance(value, (str, int, float)): normalized[key] = str(value).strip() continue logging.warning("Ignoring %s in %s due to unsupported type.", key, config_path) return normalized def save_local_config(config_path: str, config_values: Dict[str, str]) -> None: config_dir = os.path.dirname(os.path.abspath(config_path)) if config_dir: os.makedirs(config_dir, exist_ok=True) payload = { key: value for key, value in config_values.items() if key in LOCAL_CONFIG_KEYS and value } temp_path = f"{config_path}.tmp" with open(temp_path, "w", encoding="utf-8") as file_handle: json.dump(payload, file_handle, ensure_ascii=True, indent=2) os.replace(temp_path, config_path) def apply_local_config(config_values: Dict[str, str]) -> None: for key, value in config_values.items(): if value: os.environ.setdefault(key, value) def resolve_bot_token(config_path: str, config_values: Dict[str, str]) -> str: token = os.getenv("DISCORD_BOT_TOKEN", "").strip() if token: return token if not sys.stdin or not sys.stdin.isatty(): return "" print("DISCORD_BOT_TOKEN chưa được cấu hình.") print(f"Nhập token để lưu vào {config_path} (chỉ cần 1 lần).") provided_token = input("Token: ").strip() if not provided_token: return "" config_values["DISCORD_BOT_TOKEN"] = provided_token save_local_config(config_path, config_values) os.environ["DISCORD_BOT_TOKEN"] = provided_token print(f"Đã lưu token vào {config_path}.") return provided_token def parse_duration(duration_text: str) -> int: normalized_input = duration_text.strip().lower() match = DURATION_PATTERN.match(normalized_input) if not match: raise ValueError( "Định dạng thời gian không hợp lệ. Ví dụ: 30s, 12m, 2h, 30 sec, 15 phút, 1 giờ" ) value = int(match.group(1)) raw_unit = match.group(2) unit = UNIT_ALIASES.get(raw_unit) if unit is None: raise ValueError( "Đơn vị thời gian không hợp lệ. Dùng s/sec/giây, m/min/phút, h/hr/giờ." ) if value <= 0: raise ValueError("Thời gian phải lớn hơn 0.") multiplier = {"s": 1, "m": 60, "h": 3600}[unit] return value * multiplier def format_duration(seconds: int) -> str: seconds = max(0, seconds) hours, remainder = divmod(seconds, 3600) minutes, sec = divmod(remainder, 60) parts: List[str] = [] if hours: parts.append(f"{hours}h") if minutes: parts.append(f"{minutes}m") if sec or not parts: parts.append(f"{sec}s") return " ".join(parts) class ReminderRepository: def __init__(self, storage_path: str) -> None: self.storage_path = storage_path self.is_memory_only = storage_path == ":memory:" self._lock = asyncio.Lock() self._initialized = False self._state: Dict[str, Dict[str, ReminderRow]] = self._default_state() @staticmethod def _default_state() -> Dict[str, Dict[str, ReminderRow]]: return {"configs": {}, "active_reminders": {}} @staticmethod def _make_key(user_id: int, trigger_word: str) -> str: return f"{user_id}:{trigger_word}" def _normalize_state(self, raw: Any) -> Dict[str, Dict[str, ReminderRow]]: normalized = self._default_state() if not isinstance(raw, dict): return normalized for bucket_name in ("configs", "active_reminders"): bucket_value = raw.get(bucket_name) if not isinstance(bucket_value, dict): continue for raw_key, raw_row in bucket_value.items(): if not isinstance(raw_key, str) or not isinstance(raw_row, dict): continue try: user_id = int(raw_row["user_id"]) trigger_word = str(raw_row["trigger_word"]) channel_id = int(raw_row["channel_id"]) row: ReminderRow = { "user_id": user_id, "trigger_word": trigger_word, "channel_id": channel_id, } if bucket_name == "configs": row["duration_seconds"] = int(raw_row["duration_seconds"]) else: row["due_at"] = int(raw_row["due_at"]) except (KeyError, TypeError, ValueError): continue normalized[bucket_name][raw_key] = row return normalized def _ensure_storage_dir(self) -> None: if self.is_memory_only: return directory = os.path.dirname(os.path.abspath(self.storage_path)) if directory: os.makedirs(directory, exist_ok=True) def _read_from_disk(self) -> None: if self.is_memory_only: self._state = self._default_state() return self._ensure_storage_dir() if not os.path.exists(self.storage_path): self._state = self._default_state() self._write_to_disk(self._state) return try: with open(self.storage_path, "r", encoding="utf-8") as file_handle: loaded = json.load(file_handle) except (OSError, json.JSONDecodeError): logging.exception("Failed to read storage file %s. Resetting state.", self.storage_path) self._state = self._default_state() self._write_to_disk(self._state) return self._state = self._normalize_state(loaded) def _write_to_disk(self, state: Dict[str, Dict[str, ReminderRow]]) -> None: if self.is_memory_only: return self._ensure_storage_dir() temp_path = f"{self.storage_path}.tmp" with open(temp_path, "w", encoding="utf-8") as file_handle: json.dump(state, file_handle, ensure_ascii=True, indent=2) os.replace(temp_path, self.storage_path) async def _ensure_initialized(self) -> None: if self._initialized: return async with self._lock: if self._initialized: return await asyncio.to_thread(self._read_from_disk) self._initialized = True async def _persist_locked(self) -> None: await asyncio.to_thread(self._write_to_disk, self._state) async def init_schema(self) -> None: await self._ensure_initialized() async def upsert_config( self, user_id: int, trigger_word: str, duration_seconds: int, channel_id: int ) -> None: await self._ensure_initialized() async with self._lock: key = self._make_key(user_id, trigger_word) self._state["configs"][key] = { "user_id": user_id, "trigger_word": trigger_word, "duration_seconds": duration_seconds, "channel_id": channel_id, } await self._persist_locked() async def get_config(self, user_id: int, trigger_word: str) -> Optional[ReminderRow]: await self._ensure_initialized() async with self._lock: key = self._make_key(user_id, trigger_word) row = self._state["configs"].get(key) if row is None: return None return dict(row) async def list_configs(self, user_id: int) -> List[ReminderRow]: await self._ensure_initialized() async with self._lock: rows = [ dict(row) for row in self._state["configs"].values() if int(row["user_id"]) == user_id ] rows.sort(key=lambda item: str(item["trigger_word"])) return rows async def delete_config(self, user_id: int, trigger_word: str) -> bool: await self._ensure_initialized() async with self._lock: key = self._make_key(user_id, trigger_word) removed = self._state["configs"].pop(key, None) is not None if removed: await self._persist_locked() return removed async def upsert_active_reminder( self, user_id: int, trigger_word: str, due_at: int, channel_id: int ) -> None: await self._ensure_initialized() async with self._lock: key = self._make_key(user_id, trigger_word) self._state["active_reminders"][key] = { "user_id": user_id, "trigger_word": trigger_word, "due_at": due_at, "channel_id": channel_id, } await self._persist_locked() async def get_active_reminder( self, user_id: int, trigger_word: str ) -> Optional[ReminderRow]: await self._ensure_initialized() async with self._lock: key = self._make_key(user_id, trigger_word) row = self._state["active_reminders"].get(key) if row is None: return None return dict(row) async def list_active_for_user(self, user_id: int) -> List[ReminderRow]: await self._ensure_initialized() async with self._lock: rows = [ dict(row) for row in self._state["active_reminders"].values() if int(row["user_id"]) == user_id ] rows.sort(key=lambda item: str(item["trigger_word"])) return rows async def list_all_active_reminders(self) -> List[ReminderRow]: await self._ensure_initialized() async with self._lock: rows = [dict(row) for row in self._state["active_reminders"].values()] rows.sort(key=lambda item: (int(item["due_at"]), str(item["trigger_word"]))) return rows async def delete_active_reminder(self, user_id: int, trigger_word: str) -> bool: await self._ensure_initialized() async with self._lock: key = self._make_key(user_id, trigger_word) removed = self._state["active_reminders"].pop(key, None) is not None if removed: await self._persist_locked() return removed class ReminderCog(commands.Cog): def __init__(self, bot: commands.Bot, repo: ReminderRepository) -> None: self.bot = bot self.repo = repo self.debounce_seconds = get_env_float( "TRIGGER_DEBOUNCE_SECONDS", default=1.0, min_value=0.0 ) self.retry_seconds = get_env_int( "REMINDER_RETRY_SECONDS", default=30, min_value=5 ) self.active_tasks: Dict[ReminderKey, asyncio.Task[None]] = {} self.last_trigger_seen: Dict[ReminderKey, float] = {} self.schedule_lock = asyncio.Lock() self._restored_once = False @commands.Cog.listener() async def on_ready(self) -> None: if not self._restored_once: await self.restore_pending_reminders() self._restored_once = True if self.bot.user is not None: logging.info("Bot is online as %s", self.bot.user) @commands.Cog.listener() async def on_message(self, message: discord.Message) -> None: if message.author.bot: return content = message.content.strip() if not content: return if self._is_command_message(content): return config = await self.repo.get_config(message.author.id, content) if config is None: return key = (message.author.id, content) now_mono = time.monotonic() last_seen = self.last_trigger_seen.get(key) if last_seen is not None and (now_mono - last_seen) < self.debounce_seconds: return self.last_trigger_seen[key] = now_mono duration_seconds = int(config["duration_seconds"]) channel_id = int(config["channel_id"]) await self.start_or_reset_reminder( user_id=message.author.id, trigger_word=content, duration_seconds=duration_seconds, channel_id=channel_id, ) def _is_command_message(self, content: str) -> bool: prefix = self.bot.command_prefix if isinstance(prefix, str): return content.startswith(prefix) if isinstance(prefix, (list, tuple)): return any(content.startswith(str(item)) for item in prefix) return False async def start_or_reset_reminder( self, user_id: int, trigger_word: str, duration_seconds: int, channel_id: int ) -> None: due_at = int(time.time()) + duration_seconds await self.repo.upsert_active_reminder( user_id=user_id, trigger_word=trigger_word, due_at=due_at, channel_id=channel_id, ) await self.schedule_task(user_id, trigger_word, due_at, channel_id) logging.info( "Reminder scheduled user=%s trigger=%s due_at=%s", user_id, trigger_word, due_at, ) async def schedule_task( self, user_id: int, trigger_word: str, due_at: int, channel_id: int ) -> None: key: ReminderKey = (user_id, trigger_word) task = asyncio.create_task( self.reminder_worker(user_id, trigger_word, due_at, channel_id) ) async with self.schedule_lock: old_task = self.active_tasks.get(key) self.active_tasks[key] = task if ( old_task is not None and old_task is not asyncio.current_task() and not old_task.done() ): old_task.cancel() async def cancel_task(self, key: ReminderKey) -> bool: async with self.schedule_lock: task = self.active_tasks.pop(key, None) if task is None: return False if not task.done(): task.cancel() return True async def shutdown(self) -> None: async with self.schedule_lock: tasks = list(self.active_tasks.values()) self.active_tasks.clear() for task in tasks: if not task.done(): task.cancel() if tasks: await asyncio.gather(*tasks, return_exceptions=True) async def process_due_reminder( self, user_id: int, trigger_word: str, channel_id: int ) -> Literal["resolved", "rescheduled"]: result = await self.send_reminder(user_id, trigger_word, channel_id) if result == "transient_failure": retry_due_at = int(time.time()) + self.retry_seconds await self.repo.upsert_active_reminder( user_id=user_id, trigger_word=trigger_word, due_at=retry_due_at, channel_id=channel_id, ) await self.schedule_task(user_id, trigger_word, retry_due_at, channel_id) logging.warning( "Transient reminder failure user=%s trigger=%s. Retry in %s seconds.", user_id, trigger_word, self.retry_seconds, ) return "rescheduled" await self.repo.delete_active_reminder(user_id, trigger_word) return "resolved" async def reminder_worker( self, user_id: int, trigger_word: str, due_at: int, channel_id: int ) -> None: key: ReminderKey = (user_id, trigger_word) try: wait_seconds = max(0, due_at - int(time.time())) await asyncio.sleep(wait_seconds) row = await self.repo.get_active_reminder(user_id, trigger_word) if row is None: return if int(row["due_at"]) != due_at: return await self.process_due_reminder(user_id, trigger_word, channel_id) except asyncio.CancelledError: return except Exception: logging.exception( "Unexpected error in reminder worker user=%s trigger=%s", user_id, trigger_word, ) finally: async with self.schedule_lock: current_task = self.active_tasks.get(key) if current_task is asyncio.current_task(): self.active_tasks.pop(key, None) async def send_reminder( self, user_id: int, trigger_word: str, channel_id: int ) -> DeliveryResult: channel = self.bot.get_channel(channel_id) if channel is None: try: channel = await self.bot.fetch_channel(channel_id) except (discord.NotFound, discord.Forbidden): logging.warning( "Cannot fetch channel=%s for user=%s trigger=%s", channel_id, user_id, trigger_word, ) return "permanent_failure" except discord.HTTPException: logging.exception( "Transient channel fetch error channel=%s user=%s trigger=%s", channel_id, user_id, trigger_word, ) return "transient_failure" if not isinstance(channel, Messageable): logging.warning( "Channel id=%s is not messageable for trigger=%s", channel_id, trigger_word ) return "permanent_failure" text = f"Alo em <@{user_id}> hả em, đến lúc [{trigger_word}] rồi!" try: await channel.send(text) return "sent" except (discord.NotFound, discord.Forbidden): logging.warning( "Cannot send reminder due to channel access user=%s trigger=%s channel=%s", user_id, trigger_word, channel_id, ) return "permanent_failure" except discord.HTTPException: logging.exception( "Failed to send reminder user=%s trigger=%s channel=%s", user_id, trigger_word, channel_id, ) return "transient_failure" async def restore_pending_reminders(self) -> None: rows = await self.repo.list_all_active_reminders() if not rows: return now = int(time.time()) resolved = 0 rescheduled = 0 retried = 0 for row in rows: user_id = int(row["user_id"]) trigger_word = str(row["trigger_word"]) due_at = int(row["due_at"]) channel_id = int(row["channel_id"]) if due_at <= now: outcome = await self.process_due_reminder( user_id, trigger_word, channel_id ) if outcome == "resolved": resolved += 1 else: retried += 1 continue await self.schedule_task(user_id, trigger_word, due_at, channel_id) rescheduled += 1 logging.info( "Restore finished resolved=%s rescheduled=%s retried=%s", resolved, rescheduled, retried, ) @commands.command(name="set_remind") async def set_remind( self, ctx: commands.Context[commands.Bot], trigger_word: str, duration_text: str ) -> None: if len(trigger_word) > 64: await ctx.send("Trigger quá dài. Giới hạn: 64 ký tự.") return try: duration_seconds = parse_duration(duration_text) except ValueError as exc: await ctx.send(str(exc)) return await self.repo.upsert_config( user_id=ctx.author.id, trigger_word=trigger_word, duration_seconds=duration_seconds, channel_id=ctx.channel.id, ) await ctx.send( "Đã thiết lập. Tôi sẽ nhắc bạn " f"{format_duration(duration_seconds)} sau khi bạn gõ '{trigger_word}'." ) @commands.command(name="list_remind") async def list_remind(self, ctx: commands.Context[commands.Bot]) -> None: configs = await self.repo.list_configs(ctx.author.id) if not configs: await ctx.send("Bạn chưa có reminder nào.") return active_rows = await self.repo.list_active_for_user(ctx.author.id) active_map = {str(row["trigger_word"]): int(row["due_at"]) for row in active_rows} now = int(time.time()) lines: List[str] = [] for item in configs: trigger_word = str(item["trigger_word"]) duration_seconds = int(item["duration_seconds"]) channel_id = int(item["channel_id"]) due_at = active_map.get(trigger_word) if due_at is None: status = "idle" else: remaining = max(0, due_at - now) status = f"active (còn {format_duration(remaining)})" lines.append( f"- [{trigger_word}] {format_duration(duration_seconds)} | {status} | channel <#{channel_id}>" ) await ctx.send("Danh sách reminder:\n" + "\n".join(lines)) @commands.command(name="remove_remind") async def remove_remind( self, ctx: commands.Context[commands.Bot], trigger_word: str ) -> None: config_removed = await self.repo.delete_config(ctx.author.id, trigger_word) active_removed = await self.repo.delete_active_reminder(ctx.author.id, trigger_word) await self.cancel_task((ctx.author.id, trigger_word)) self.last_trigger_seen.pop((ctx.author.id, trigger_word), None) if not config_removed and not active_removed: await ctx.send(f"Không tìm thấy trigger [{trigger_word}].") return if active_removed: await ctx.send(f"Đã xóa trigger [{trigger_word}] và hủy timer đang chạy.") return await ctx.send(f"Đã xóa trigger [{trigger_word}].") @commands.Cog.listener() async def on_command_error( self, ctx: commands.Context[commands.Bot], error: commands.CommandError ) -> None: if isinstance(error, commands.CommandNotFound): return if isinstance(error, commands.MissingRequiredArgument) and ctx.command is not None: usage = f"{ctx.prefix}{ctx.command.qualified_name} {ctx.command.signature}".strip() await ctx.send(f"Thiếu tham số. Cách dùng: {usage}") return if isinstance(error, commands.BadArgument): await ctx.send("Tham số không hợp lệ.") return logging.exception("Unhandled command error", exc_info=error) await ctx.send("Có lỗi xảy ra khi xử lý lệnh.") class TriggerReminderBot(commands.Bot): def __init__(self, command_prefix: str, storage_path: str, proxy_url: Optional[str] = None) -> None: intents = discord.Intents.default() intents.message_content = True # Thêm proxy=proxy_url vào super().__init__ super().__init__(command_prefix=command_prefix, intents=intents, proxy=proxy_url) self.repo = ReminderRepository(storage_path) self.reminder_cog = ReminderCog(self, self.repo) async def setup_hook(self) -> None: await self.repo.init_schema() await self.add_cog(self.reminder_cog) async def close(self) -> None: await self.reminder_cog.shutdown() await super().close() def main() -> None: load_dotenv() config_path = os.getenv("BOT_CONFIG_PATH", LOCAL_CONFIG_PATH) local_config = load_local_config(config_path) apply_local_config(local_config) token = resolve_bot_token(config_path, local_config) if not token: raise SystemExit( "Missing DISCORD_BOT_TOKEN. Set env/.env or run py bot.py in terminal to enter and save token." ) command_prefix = os.getenv("COMMAND_PREFIX", "!") storage_path = os.getenv("STORAGE_PATH", "data/reminder_data.json") log_level = os.getenv("LOG_LEVEL", "INFO").upper() restart_delay_seconds = get_env_int( "RESTART_DELAY_SECONDS", default=15, min_value=5 ) if storage_path != ":memory:": storage_dir = os.path.dirname(os.path.abspath(storage_path)) os.makedirs(storage_dir, exist_ok=True) logging.basicConfig( level=getattr(logging, log_level, logging.INFO), format="%(asctime)s [%(levelname)s] %(message)s", ) start_keepalive_server() while True: proxy_from_env = os.getenv("PROXY_URL") bot = TriggerReminderBot(command_prefix=command_prefix, storage_path=storage_path,proxy_url=proxy_from_env) try: bot.run(token, reconnect=True, log_handler=None) break except discord.LoginFailure as exc: raise SystemExit("Invalid DISCORD_BOT_TOKEN.") from exc except KeyboardInterrupt: logging.info("Shutdown requested by user.") break except Exception: logging.exception( "Bot crashed unexpectedly. Restarting in %s seconds.", restart_delay_seconds, ) time.sleep(restart_delay_seconds) if __name__ == "__main__": main()