Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 212
bot.py
import asyncio
import logging
import os
import random
from contextlib import suppress
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("thang-sapper-nao-do")
def env_list(name: str, default: str) -> list[str]:
value = os.getenv(name, default)
return [item.strip() for item in value.split("|") if item.strip()]
def env_int(name: str, default: int) -> int:
try:
return int(os.getenv(name, str(default)))
except ValueError:
logger.warning("%s is not a valid number; using %s", name, default)
return default
TOKEN = os.getenv("DISCORD_TOKEN")
BOT_NAME = os.getenv("BOT_NAME", "thằng sapper nào đó")
AUTO_CHAT_CHANNEL_ID = env_int("AUTO_CHAT_CHANNEL_ID", 0)
AUTO_CHAT_INTERVAL = max(env_int("AUTO_CHAT_INTERVAL_SECONDS", 3600), 60)
AUTO_CHAT_MESSAGES = env_list(
"AUTO_CHAT_MESSAGES",
"Có ai chơi Minecraft không?|thằng sapper nào đó đã xuất hiện đây!|Mọi người đang làm gì đó?",
)
MENTION_REPLIES = env_list(
"MENTION_REPLIES",
"Gọi mình đó hả? 😎|Có chuyện gì không?|Mình nghe đây!",
)
REPLY_COOLDOWN_SECONDS = max(env_int("REPLY_COOLDOWN_SECONDS", 5), 0)
if not TOKEN:
raise RuntimeError("DISCORD_TOKEN is missing. Add it to your .env file.")
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.guilds = True
bot = commands.Bot(
command_prefix="!",
intents=intents,
help_command=None,
case_insensitive=True,
)
last_replies: dict[int, float] = {}
auto_chat_task: asyncio.Task | None = None
def can_reply(user_id: int) -> bool:
now = asyncio.get_running_loop().time()
last_reply = last_replies.get(user_id, 0)
if now - last_reply < REPLY_COOLDOWN_SECONDS:
return False
last_replies[user_id] = now
return True
async def is_reply_to_bot(message: discord.Message) -> bool:
reference = message.reference
if reference is None or reference.message_id is None:
return False
if isinstance(reference.resolved, discord.Message):
return reference.resolved.author.id == bot.user.id
try:
referenced_message = await message.channel.fetch_message(reference.message_id)
except (discord.NotFound, discord.Forbidden, discord.HTTPException):
return False
return referenced_message.author.id == bot.user.id
async def send_auto_chat() -> None:
if not AUTO_CHAT_CHANNEL_ID:
return
channel = bot.get_channel(AUTO_CHAT_CHANNEL_ID)
if channel is None:
try:
channel = await bot.fetch_channel(AUTO_CHAT_CHANNEL_ID)
except (discord.NotFound, discord.Forbidden, discord.HTTPException) as error:
logger.warning("Could not access auto-chat channel: %s", error)
return
if not isinstance(channel, discord.TextChannel):
logger.warning("AUTO_CHAT_CHANNEL_ID is not a text channel")
return
try:
await channel.send(random.choice(AUTO_CHAT_MESSAGES))
except (discord.Forbidden, discord.HTTPException) as error:
logger.warning("Could not send auto-chat message: %s", error)
async def auto_chat_loop() -> None:
await bot.wait_until_ready()
while not bot.is_closed():
await asyncio.sleep(AUTO_CHAT_INTERVAL)
await send_auto_chat()
@bot.event
async def on_ready() -> None:
global auto_chat_task
logger.info("Logged in as %s (%s)", bot.user, bot.user.id)
await bot.change_presence(
activity=discord.Game(name=f"{BOT_NAME} | !help"),
)
if auto_chat_task is None or auto_chat_task.done():
auto_chat_task = asyncio.create_task(auto_chat_loop())
@bot.event
async def on_message(message: discord.Message) -> None:
if message.author.bot:
return
mentioned = bot.user is not None and bot.user in message.mentions
replied_to_bot = await is_reply_to_bot(message)
if (mentioned or replied_to_bot) and can_reply(message.author.id):
await message.reply(
random.choice(MENTION_REPLIES),
mention_author=False,
)
await bot.process_commands(message)
@bot.command(name="help")
async def help_command(ctx: commands.Context) -> None:
await ctx.send(
"Mình sẽ trả lời khi được ping hoặc khi bạn reply tin nhắn của mình. "
"Auto-chat được cấu hình bằng AUTO_CHAT_CHANNEL_ID."
)
@bot.command(name="ping")
async def ping_command(ctx: commands.Context) -> None:
await ctx.send(f"Pong! {round(bot.latency * 1000)}ms")
async def shutdown() -> None:
if auto_chat_task is not None:
auto_chat_task.cancel()
with suppress(asyncio.CancelledError):
await auto_chat_task
try:
bot.run(TOKEN)
finally:
if not bot.is_closed():
asyncio.run(shutdown())