start on moderation stuff
This commit is contained in:
1 parent
b538da6033
commit
53e0daac1e
6 files changed
+271
-15
No files matched your search
+26
-1
@@ -1,29 +1,54 @@
|
|||||||
|
import traceback
|
||||||
|
|
||||||
import discord
|
import discord
|
||||||
|
from discord import app_commands
|
||||||
from discord.ext import commands
|
from discord.ext import commands
|
||||||
|
|
||||||
import config
|
import config
|
||||||
|
from db import Database
|
||||||
|
|
||||||
EXTENSIONS = [
|
EXTENSIONS = [
|
||||||
|
"cogs.settings",
|
||||||
"cogs.roles",
|
"cogs.roles",
|
||||||
"cogs.channels",
|
"cogs.channels",
|
||||||
"cogs.countdown",
|
"cogs.countdown",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
async def on_tree_error(interaction: discord.Interaction, error):
|
||||||
|
if isinstance(error, app_commands.CheckFailure):
|
||||||
|
message = str(error) or "You can't use this command."
|
||||||
|
else:
|
||||||
|
traceback.print_exception(type(error), error, error.__traceback__)
|
||||||
|
message = "Something went wrong. The error has been logged."
|
||||||
|
|
||||||
|
if interaction.response.is_done():
|
||||||
|
await interaction.followup.send(message, ephemeral=True)
|
||||||
|
else:
|
||||||
|
await interaction.response.send_message(message, ephemeral=True)
|
||||||
|
|
||||||
|
|
||||||
class Bot(commands.Bot):
|
class Bot(commands.Bot):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super().__init__(
|
super().__init__(
|
||||||
command_prefix=commands.when_mentioned,
|
command_prefix=commands.when_mentioned,
|
||||||
intents=discord.Intents.default(),
|
intents=discord.Intents.default(),
|
||||||
)
|
)
|
||||||
|
self.db = Database(config.DB_PATH)
|
||||||
|
self.tree.on_error = on_tree_error
|
||||||
|
|
||||||
async def setup_hook(self):
|
async def setup_hook(self):
|
||||||
|
await self.db.connect()
|
||||||
for ext in EXTENSIONS:
|
for ext in EXTENSIONS:
|
||||||
await self.load_extension(ext)
|
await self.load_extension(ext)
|
||||||
await self.tree.sync(guild=config.GUILD)
|
await self.tree.sync(guild=config.GUILD)
|
||||||
|
|
||||||
|
async def close(self):
|
||||||
|
await super().close()
|
||||||
|
await self.db.close()
|
||||||
|
|
||||||
async def on_ready(self):
|
async def on_ready(self):
|
||||||
print(f"Logged in as {self.user} (id {self.user.id})", flush=True)
|
print(f"Logged in as {self.user} (id {self.user.id})", flush=True)
|
||||||
|
|
||||||
|
|
||||||
Bot().run(config.TOKEN)
|
Bot().run(config.TOKEN)
|
||||||
+8
-14
@@ -90,11 +90,10 @@ class Countdown(commands.Cog):
|
|||||||
"""Posts once per day during the 9:00-9:04 Central window."""
|
"""Posts once per day during the 9:00-9:04 Central window."""
|
||||||
try:
|
try:
|
||||||
now = datetime.now(CENTRAL)
|
now = datetime.now(CENTRAL)
|
||||||
if (
|
today = now.date().isoformat()
|
||||||
now.hour != DAILY_HOUR
|
if now.hour != DAILY_HOUR or now.minute >= 5:
|
||||||
or now.minute >= 5
|
return
|
||||||
or self.last_posted == now.date()
|
if await self.bot.db.get_setting("countdown_last_posted") == today:
|
||||||
):
|
|
||||||
return
|
return
|
||||||
|
|
||||||
embed = countdown_embed()
|
embed = countdown_embed()
|
||||||
@@ -102,19 +101,14 @@ class Countdown(commands.Cog):
|
|||||||
return
|
return
|
||||||
|
|
||||||
guild = self.bot.get_guild(config.GUILD.id)
|
guild = self.bot.get_guild(config.GUILD.id)
|
||||||
channel = (
|
channel = (discord.utils.get(guild.text_channels, name=DAILY_CHANNEL)
|
||||||
discord.utils.get(guild.text_channels, name=DAILY_CHANNEL)
|
if guild else None)
|
||||||
if guild
|
|
||||||
else None
|
|
||||||
)
|
|
||||||
if channel is None:
|
if channel is None:
|
||||||
print(
|
print(f"daily_countdown: no channel named {DAILY_CHANNEL!r}", flush=True)
|
||||||
f"daily_countdown: no channel named {DAILY_CHANNEL!r}", flush=True
|
|
||||||
)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
await channel.send(embed=embed)
|
await channel.send(embed=embed)
|
||||||
self.last_posted = now.date()
|
await self.bot.db.set_setting("countdown_last_posted", today)
|
||||||
print(f"daily_countdown: posted in #{DAILY_CHANNEL}", flush=True)
|
print(f"daily_countdown: posted in #{DAILY_CHANNEL}", flush=True)
|
||||||
except discord.HTTPException as e:
|
except discord.HTTPException as e:
|
||||||
print(f"daily_countdown: could not post: {e}", flush=True)
|
print(f"daily_countdown: could not post: {e}", flush=True)
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import discord
|
||||||
|
from discord import app_commands
|
||||||
|
from discord.ext import commands
|
||||||
|
|
||||||
|
import config
|
||||||
|
import guildconf
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(commands.Cog):
|
||||||
|
def __init__(self, bot):
|
||||||
|
self.bot = bot
|
||||||
|
|
||||||
|
group = app_commands.Group(
|
||||||
|
name="config",
|
||||||
|
description="Configure the bot",
|
||||||
|
guild_ids=[config.GUILD.id],
|
||||||
|
guild_only=True,
|
||||||
|
default_permissions=discord.Permissions(manage_guild=True),
|
||||||
|
)
|
||||||
|
|
||||||
|
@group.command(name="modlog", description="Set the mod-log channel")
|
||||||
|
@app_commands.describe(channel="Channel where moderation actions are logged")
|
||||||
|
@app_commands.checks.has_permissions(manage_guild=True)
|
||||||
|
async def modlog(self, interaction: discord.Interaction,
|
||||||
|
channel: discord.TextChannel):
|
||||||
|
perms = channel.permissions_for(interaction.guild.me)
|
||||||
|
if not (perms.view_channel and perms.send_messages and perms.embed_links):
|
||||||
|
await interaction.response.send_message(
|
||||||
|
f"I need View Channel, Send Messages and Embed Links in {channel.mention}.",
|
||||||
|
ephemeral=True)
|
||||||
|
return
|
||||||
|
await self.bot.db.set_setting(guildconf.MOD_LOG, channel.id)
|
||||||
|
await interaction.response.send_message(
|
||||||
|
f"Mod log set to {channel.mention}.", ephemeral=True)
|
||||||
|
|
||||||
|
@group.command(name="modrole", description="Set the moderator role")
|
||||||
|
@app_commands.checks.has_permissions(manage_guild=True)
|
||||||
|
async def modrole(self, interaction: discord.Interaction, role: discord.Role):
|
||||||
|
await self._set_role(interaction, guildconf.MOD_ROLE, role, "Moderator")
|
||||||
|
|
||||||
|
@group.command(name="adminrole", description="Set the admin role")
|
||||||
|
@app_commands.checks.has_permissions(manage_guild=True)
|
||||||
|
async def adminrole(self, interaction: discord.Interaction, role: discord.Role):
|
||||||
|
await self._set_role(interaction, guildconf.ADMIN_ROLE, role, "Admin")
|
||||||
|
|
||||||
|
@group.command(name="show", description="Show the current configuration")
|
||||||
|
@app_commands.checks.has_permissions(manage_guild=True)
|
||||||
|
async def show(self, interaction: discord.Interaction):
|
||||||
|
def fmt(value, prefix):
|
||||||
|
return f"<{prefix}{value}>" if value else "not set"
|
||||||
|
|
||||||
|
modlog = await guildconf.get_id(self.bot, guildconf.MOD_LOG)
|
||||||
|
modrole = await guildconf.get_id(self.bot, guildconf.MOD_ROLE)
|
||||||
|
adminrole = await guildconf.get_id(self.bot, guildconf.ADMIN_ROLE)
|
||||||
|
await interaction.response.send_message(
|
||||||
|
f"Mod log: {fmt(modlog, '#')}\n"
|
||||||
|
f"Moderator role: {fmt(modrole, '@&')}\n"
|
||||||
|
f"Admin role: {fmt(adminrole, '@&')}",
|
||||||
|
ephemeral=True)
|
||||||
|
|
||||||
|
async def _set_role(self, interaction, key, role, label):
|
||||||
|
if role.is_default():
|
||||||
|
await interaction.response.send_message(
|
||||||
|
"@everyone can't be used here.", ephemeral=True)
|
||||||
|
return
|
||||||
|
await self.bot.db.set_setting(key, role.id)
|
||||||
|
await interaction.response.send_message(
|
||||||
|
f"{label} role set to {role.mention}.", ephemeral=True)
|
||||||
|
|
||||||
|
|
||||||
|
async def setup(bot):
|
||||||
|
await bot.add_cog(Settings(bot))
|
||||||
@@ -5,4 +5,6 @@ import discord
|
|||||||
TOKEN = os.environ["DISCORD_BOT_TOKEN"]
|
TOKEN = os.environ["DISCORD_BOT_TOKEN"]
|
||||||
GUILD = discord.Object(id=int(os.environ["DISCORD_GUILD_ID"]))
|
GUILD = discord.Object(id=int(os.environ["DISCORD_GUILD_ID"]))
|
||||||
|
|
||||||
|
DB_PATH = os.path.join(os.environ.get("STATE_DIRECTORY", "data"), "bot.db")
|
||||||
|
|
||||||
LIGHT_BLUE = 0x87CEEB
|
LIGHT_BLUE = 0x87CEEB
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import time
|
||||||
|
|
||||||
|
# Append only. Each entry runs once, in order, and the index is stored in
|
||||||
|
# PRAGMA user_version. Never edit an entry that has already shipped.
|
||||||
|
MIGRATIONS = [
|
||||||
|
"""
|
||||||
|
CREATE TABLE settings (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE cases (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
user_id INTEGER NOT NULL,
|
||||||
|
moderator_id INTEGER NOT NULL,
|
||||||
|
action TEXT NOT NULL,
|
||||||
|
reason TEXT,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER,
|
||||||
|
active INTEGER NOT NULL DEFAULT 1
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_cases_user ON cases (user_id);
|
||||||
|
""",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class Database:
|
||||||
|
def __init__(self, path):
|
||||||
|
self.path = path
|
||||||
|
self.conn = None
|
||||||
|
self.lock = asyncio.Lock()
|
||||||
|
|
||||||
|
async def connect(self):
|
||||||
|
os.makedirs(os.path.dirname(self.path) or ".", exist_ok=True)
|
||||||
|
self.conn = await asyncio.to_thread(self._open)
|
||||||
|
|
||||||
|
def _open(self):
|
||||||
|
conn = sqlite3.connect(self.path, check_same_thread=False)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
conn.execute("PRAGMA journal_mode=WAL")
|
||||||
|
conn.execute("PRAGMA foreign_keys=ON")
|
||||||
|
version = conn.execute("PRAGMA user_version").fetchone()[0]
|
||||||
|
for i, sql in enumerate(MIGRATIONS[version:], start=version + 1):
|
||||||
|
conn.executescript(sql)
|
||||||
|
conn.execute(f"PRAGMA user_version={i}")
|
||||||
|
conn.commit()
|
||||||
|
return conn
|
||||||
|
|
||||||
|
async def close(self):
|
||||||
|
if self.conn:
|
||||||
|
await asyncio.to_thread(self.conn.close)
|
||||||
|
self.conn = None
|
||||||
|
|
||||||
|
def _run(self, sql, params, fetch):
|
||||||
|
cur = self.conn.execute(sql, params)
|
||||||
|
rows = cur.fetchall() if fetch else None
|
||||||
|
self.conn.commit()
|
||||||
|
return rows, cur.lastrowid
|
||||||
|
|
||||||
|
async def _exec(self, sql, params=(), fetch=False):
|
||||||
|
async with self.lock:
|
||||||
|
return await asyncio.to_thread(self._run, sql, params, fetch)
|
||||||
|
|
||||||
|
async def execute(self, sql, *params):
|
||||||
|
"""Run a write and return the new row id."""
|
||||||
|
_, rowid = await self._exec(sql, params)
|
||||||
|
return rowid
|
||||||
|
|
||||||
|
async def fetchall(self, sql, *params):
|
||||||
|
rows, _ = await self._exec(sql, params, fetch=True)
|
||||||
|
return rows
|
||||||
|
|
||||||
|
async def fetchone(self, sql, *params):
|
||||||
|
rows = await self.fetchall(sql, *params)
|
||||||
|
return rows[0] if rows else None
|
||||||
|
|
||||||
|
async def get_setting(self, key, default=None):
|
||||||
|
row = await self.fetchone("SELECT value FROM settings WHERE key = ?", key)
|
||||||
|
return row["value"] if row else default
|
||||||
|
|
||||||
|
async def set_setting(self, key, value):
|
||||||
|
await self.execute(
|
||||||
|
"INSERT INTO settings (key, value) VALUES (?, ?) "
|
||||||
|
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||||
|
key, str(value))
|
||||||
|
|
||||||
|
async def add_case(self, user_id, moderator_id, action, reason=None,
|
||||||
|
expires_at=None):
|
||||||
|
return await self.execute(
|
||||||
|
"INSERT INTO cases (user_id, moderator_id, action, reason, "
|
||||||
|
"created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
user_id, moderator_id, action, reason, int(time.time()), expires_at)
|
||||||
|
|
||||||
|
async def get_cases(self, user_id):
|
||||||
|
return await self.fetchall(
|
||||||
|
"SELECT * FROM cases WHERE user_id = ? ORDER BY id DESC", user_id)
|
||||||
|
|
||||||
|
async def count_active_cases(self, user_id, action):
|
||||||
|
row = await self.fetchone(
|
||||||
|
"SELECT COUNT(*) AS n FROM cases "
|
||||||
|
"WHERE user_id = ? AND action = ? AND active = 1",
|
||||||
|
user_id, action)
|
||||||
|
return row["n"]
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import discord
|
||||||
|
from discord import app_commands
|
||||||
|
|
||||||
|
MOD_LOG = "mod_log_channel"
|
||||||
|
MOD_ROLE = "mod_role"
|
||||||
|
ADMIN_ROLE = "admin_role"
|
||||||
|
|
||||||
|
|
||||||
|
async def get_id(bot, key):
|
||||||
|
value = await bot.db.get_setting(key)
|
||||||
|
return int(value) if value else None
|
||||||
|
|
||||||
|
|
||||||
|
async def mod_log_channel(bot, guild):
|
||||||
|
channel_id = await get_id(bot, MOD_LOG)
|
||||||
|
return guild.get_channel(channel_id) if channel_id else None
|
||||||
|
|
||||||
|
|
||||||
|
async def send_mod_log(bot, guild, **kwargs):
|
||||||
|
"""Send to the mod-log channel. Returns the message, or None if unavailable."""
|
||||||
|
channel = await mod_log_channel(bot, guild)
|
||||||
|
if channel is None:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return await channel.send(**kwargs)
|
||||||
|
except discord.HTTPException:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def is_admin(bot, member):
|
||||||
|
if member.guild_permissions.administrator:
|
||||||
|
return True
|
||||||
|
admin_role = await get_id(bot, ADMIN_ROLE)
|
||||||
|
return admin_role is not None and any(r.id == admin_role for r in member.roles)
|
||||||
|
|
||||||
|
|
||||||
|
async def is_mod(bot, member):
|
||||||
|
if await is_admin(bot, member):
|
||||||
|
return True
|
||||||
|
mod_role = await get_id(bot, MOD_ROLE)
|
||||||
|
return mod_role is not None and any(r.id == mod_role for r in member.roles)
|
||||||
|
|
||||||
|
|
||||||
|
def mod_only():
|
||||||
|
async def predicate(interaction):
|
||||||
|
if await is_mod(interaction.client, interaction.user):
|
||||||
|
return True
|
||||||
|
raise app_commands.CheckFailure("You need to be a moderator to use this.")
|
||||||
|
return app_commands.check(predicate)
|
||||||
|
|
||||||
|
|
||||||
|
def admin_only():
|
||||||
|
async def predicate(interaction):
|
||||||
|
if await is_admin(interaction.client, interaction.user):
|
||||||
|
return True
|
||||||
|
raise app_commands.CheckFailure("You need to be an admin to use this.")
|
||||||
|
return app_commands.check(predicate)
|
||||||
Reference in new issue
Block a user