Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 610
bot.py
import logging
import os
from datetime import datetime, timezone
from pathlib import Path
import aiosqlite
import discord
from discord import app_commands
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("pumpgrief")
class Database:
def __init__(self, path: str):
self.path = Path(path)
self.connection: aiosqlite.Connection | None = None
async def connect(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
self.connection = await aiosqlite.connect(self.path)
self.connection.row_factory = aiosqlite.Row
await self.connection.executescript(
"""
CREATE TABLE IF NOT EXISTS warnings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
moderator_id INTEGER NOT NULL,
reason TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_warnings_member
ON warnings (guild_id, user_id);
CREATE TABLE IF NOT EXISTS guild_settings (
guild_id INTEGER PRIMARY KEY,
log_channel_id INTEGER
);
"""
)
await self.connection.commit()
async def close(self) -> None:
if self.connection is not None:
await self.connection.close()
async def add_warning(
self, guild_id: int, user_id: int, moderator_id: int, reason: str
) -> int:
assert self.connection is not None
cursor = await self.connection.execute(
"""
INSERT INTO warnings (guild_id, user_id, moderator_id, reason, created_at)
VALUES (?, ?, ?, ?, ?)
""",
(
guild_id,
user_id,
moderator_id,
reason,
datetime.now(timezone.utc).isoformat(),
),
)
await self.connection.commit()
return int(cursor.lastrowid)
async def get_warnings(self, guild_id: int, user_id: int) -> list[aiosqlite.Row]:
assert self.connection is not None
cursor = await self.connection.execute(
"""
SELECT id, moderator_id, reason, created_at
FROM warnings
WHERE guild_id = ? AND user_id = ?
ORDER BY id DESC
LIMIT 25
""",
(guild_id, user_id),
)
return await cursor.fetchall()
async def clear_warnings(self, guild_id: int, user_id: int) -> int:
assert self.connection is not None
cursor = await self.connection.execute(
"DELETE FROM warnings WHERE guild_id = ? AND user_id = ?",
(guild_id, user_id),
)
await self.connection.commit()
return cursor.rowcount
async def set_log_channel(self, guild_id: int, channel_id: int) -> None:
assert self.connection is not None
await self.connection.execute(
"""
INSERT INTO guild_settings (guild_id, log_channel_id)
VALUES (?, ?)
ON CONFLICT(guild_id) DO UPDATE SET log_channel_id = excluded.log_channel_id
""",
(guild_id, channel_id),
)
await self.connection.commit()
async def get_log_channel(self, guild_id: int) -> int | None:
assert self.connection is not None
cursor = await self.connection.execute(
"SELECT log_channel_id FROM guild_settings WHERE guild_id = ?",
(guild_id,),
)
row = await cursor.fetchone()
return None if row is None else row["log_channel_id"]
class PumpGriefBot(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.default()
intents.members = True
super().__init__(command_prefix="!", intents=intents)
self.db = Database(os.getenv("DATABASE_PATH", "data/pumpgrief.db"))
async def setup_hook(self) -> None:
await self.db.connect()
guild_id = os.getenv("GUILD_ID")
if guild_id:
guild = discord.Object(id=int(guild_id))
self.tree.copy_global_to(guild=guild)
await self.tree.sync(guild=guild)
logger.info("Slash-команды синхронизированы для сервера %s", guild_id)
else:
await self.tree.sync()
logger.info("Глобальные slash-команды синхронизированы")
async def close(self) -> None:
await self.db.close()
await super().close()
bot = PumpGriefBot()
def get_guild(interaction: discord.Interaction) -> discord.Guild:
if interaction.guild is None:
raise RuntimeError("Команда доступна только на сервере")
return interaction.guild
async def send_log(
guild: discord.Guild,
title: str,
description: str,
color: discord.Color = discord.Color.blurple(),
) -> None:
channel_id = await bot.db.get_log_channel(guild.id)
if channel_id is None:
return
channel = guild.get_channel(channel_id)
if not isinstance(channel, discord.TextChannel):
return
embed = discord.Embed(
title=title,
description=description,
color=color,
timestamp=datetime.now(timezone.utc),
)
try:
await channel.send(embed=embed)
except discord.Forbidden:
logger.warning("Нет доступа к log-каналу %s на сервере %s", channel_id, guild.id)
def target_is_manageable(interaction: discord.Interaction, member: discord.Member) -> bool:
guild = get_guild(interaction)
if member.id == interaction.user.id:
return False
if member.id == guild.owner_id:
return False
me = guild.me
return me is not None and member.top_role < me.top_role
@bot.event
async def on_ready() -> None:
if bot.user is not None:
logger.info("PumpGrief запущен как %s (%s)", bot.user, bot.user.id)
@bot.event
async def on_member_join(member: discord.Member) -> None:
await send_log(
member.guild,
"Участник вошёл",
f"{member.mention} присоединился к серверу.",
discord.Color.green(),
)