Files
bot.py
community_commands.py
extra_commands.py
requirements.txt
Code
4 1,305
bot.py
import asyncio
import hashlib
import io
import logging
import os
import random
import re
import secrets
import sqlite3
import time
import discord
from discord import app_commands
from discord.ext import commands, tasks
from dotenv import load_dotenv
from extra_commands import setup_extra_commands
from community_commands import setup_community_commands
load_dotenv()
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("freepvt")
db = sqlite3.connect("freepvt.db")
db.executescript("""
CREATE TABLE IF NOT EXISTS accounts (guild INTEGER, user INTEGER, balance INTEGER DEFAULT 0, bank INTEGER DEFAULT 0, daily INTEGER DEFAULT 0, PRIMARY KEY(guild,user));
CREATE TABLE IF NOT EXISTS settings (guild INTEGER, key TEXT, value TEXT, PRIMARY KEY(guild,key));
CREATE TABLE IF NOT EXISTS warnings (id INTEGER PRIMARY KEY AUTOINCREMENT, guild INTEGER, user INTEGER, moderator INTEGER, reason TEXT);
CREATE TABLE IF NOT EXISTS giveaways (message INTEGER PRIMARY KEY, guild INTEGER, channel INTEGER, prize TEXT, ends INTEGER, ended INTEGER DEFAULT 0);
CREATE TABLE IF NOT EXISTS entries (message INTEGER, user INTEGER, PRIMARY KEY(message,user));
CREATE TABLE IF NOT EXISTS tickets (channel INTEGER PRIMARY KEY, guild INTEGER, owner INTEGER);
CREATE TABLE IF NOT EXISTS services (guild INTEGER, name TEXT, tier TEXT, PRIMARY KEY(guild,name));
CREATE TABLE IF NOT EXISTS stock (id INTEGER PRIMARY KEY AUTOINCREMENT, guild INTEGER, service TEXT, item TEXT);
CREATE TABLE IF NOT EXISTS gen_blacklist (guild INTEGER, user INTEGER, PRIMARY KEY(guild,user));
CREATE TABLE IF NOT EXISTS redeem_codes (guild INTEGER, code_hash TEXT, payload BLOB, PRIMARY KEY(guild,code_hash));
""")
db.commit()
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
bot = commands.Bot(command_prefix=commands.when_mentioned_or("$", ".", "?", "!", "-", ":", ";", "("), intents=intents, help_command=None)
def setting(guild, key, default=None):
row = db.execute("SELECT value FROM settings WHERE guild=? AND key=?", (guild, key)).fetchone()
return row[0] if row else default
def set_setting(guild, key, value):
db.execute("INSERT OR REPLACE INTO settings VALUES (?,?,?)", (guild, key, str(value)))
db.commit()
def account(guild, user):
db.execute("INSERT OR IGNORE INTO accounts (guild,user) VALUES (?,?)", (guild, user))
db.commit()
return db.execute("SELECT balance,bank,daily FROM accounts WHERE guild=? AND user=?", (guild, user)).fetchone()
def update_account(guild, user, balance, bank, daily):
db.execute("UPDATE accounts SET balance=?,bank=?,daily=? WHERE guild=? AND user=?", (balance, bank, daily, guild, user))
db.commit()
async def respond(interaction, text, ephemeral=True):
if interaction.response.is_done():
await interaction.followup.send(text, ephemeral=ephemeral, allowed_mentions=discord.AllowedMentions.none())
else:
await interaction.response.send_message(text, ephemeral=ephemeral, allowed_mentions=discord.AllowedMentions.none())
def staff(interaction, permission):
return getattr(interaction.user.guild_permissions, permission, False)
async def finish_giveaway(message_id):
row = db.execute("SELECT channel,prize,ended FROM giveaways WHERE message=?", (message_id,)).fetchone()
if not row or row[2]:
return None
entrants = [x[0] for x in db.execute("SELECT user FROM entries WHERE message=?", (message_id,))]
winner = random.choice(entrants) if entrants else None
db.execute("UPDATE giveaways SET ended=1 WHERE message=?", (message_id,))
db.commit()
channel = bot.get_channel(row[0])
if channel:
try:
await channel.send(f"Giveaway **{discord.utils.escape_markdown(row[1])}** ended: " + (f"winner <@{winner}>!" if winner else "no entries."), allowed_mentions=discord.AllowedMentions(users=True))
except discord.HTTPException:
log.exception("Could not announce giveaway %s", message_id)
return winner
@tasks.loop(seconds=15)
async def giveaway_clock():
for (message_id,) in db.execute("SELECT message FROM giveaways WHERE ended=0 AND ends<=?", (int(time.time()),)).fetchall():
await finish_giveaway(message_id)
@bot.event
async def on_ready():
if not giveaway_clock.is_running():
giveaway_clock.start()
try:
await bot.tree.sync()
except discord.HTTPException:
log.exception("Command synchronization failed")
print("KODARI_READY", flush=True)
@bot.tree.error
async def command_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
log.error("Command error", exc_info=(type(error), error, error.__traceback__))
if isinstance(error, app_commands.CommandOnCooldown):
await respond(interaction, f"Try again in {error.retry_after:.1f} seconds.")
else:
await respond(interaction, "That command failed. Check my permissions and try again.")
def owner_role(member):
return any(role.name == "👑-Owner" for role in member.roles)
def tier_access(member, tier):
names = {role.name.casefold() for role in member.roles}
if tier == "free":
return "free" in names or "premium" in names or "booster" in names or member.premium_since is not None
if tier == "booster":
return "booster" in names or member.premium_since is not None
return "premium" in names
async def read_text_file(attachment):
if not attachment.filename.lower().endswith(".txt") or attachment.size > 1_000_000:
raise ValueError("Upload a .txt file no larger than 1 MB.")
data = await attachment.read()
if len(data) > 1_000_000:
raise ValueError("File is too large.")
try:
text = data.decode("utf-8-sig")
except UnicodeDecodeError:
raise ValueError("The file must be UTF-8 text.")
if not text.strip():
raise ValueError("The file is empty.")
return text
def blocked(guild_id, user_id):
return db.execute("SELECT 1 FROM gen_blacklist WHERE guild=? AND user=?", (guild_id, user_id)).fetchone() is not None
async def status_for(member):
guild = member.guild
role = discord.utils.find(lambda r: r.name.casefold() == "free", guild.roles)
if role and role not in member.roles:
if role.is_default() or role.managed or role >= guild.me.top_role or role.permissions.value:
return "The Free role must have no server permissions and be below my highest role. Ask an administrator to fix it."
try:
await member.add_roles(role, reason="Free generator access")
except discord.HTTPException:
return "I could not assign the Free role. Check my role hierarchy and permissions."
if not role:
return "No Free role exists. Ask an administrator to create one."
return f"Free access active. Premium: {'yes' if tier_access(member, 'premium') else 'no'}; booster: {'yes' if tier_access(member, 'booster') else 'no'}." + (" You are blacklisted from generating." if blocked(guild.id, member.id) else "")
@bot.command(name="cstatus")
@commands.guild_only()
@commands.cooldown(1, 5, commands.BucketType.user)
async def prefix_cstatus(ctx):
await ctx.send(await status_for(ctx.author), allowed_mentions=discord.AllowedMentions.none())
@bot.tree.command(name="cstatus", description="Check access and receive the Free role")
@app_commands.guild_only()
async def cstatus(interaction: discord.Interaction):
await respond(interaction, await status_for(interaction.user))
@bot.tree.command(name="addservice", description="Add a generator service")
@app_commands.guild_only()
@app_commands.choices(tier=[app_commands.Choice(name=x.title(), value=x) for x in ("free", "premium", "booster")])
async def addservice(interaction: discord.Interaction, name: str, tier: app_commands.Choice[str]):
if not owner_role(interaction.user):
return await respond(interaction, "The 👑-Owner role is required.")
name = name.lower().strip()
if not re.fullmatch(r"[a-z0-9_-]{1,40}", name):
return await respond(interaction, "Use 1–40 letters, digits, hyphens or underscores.")
try:
db.execute("INSERT INTO services VALUES (?,?,?)", (interaction.guild_id, name, tier.value))
db.commit()
except sqlite3.IntegrityError:
return await respond(interaction, "That service already exists.")
await respond(interaction, f"Added {name} ({tier.value}).")
@bot.tree.command(name="restock", description="Import one stock item per line")
@app_commands.guild_only()
async def restock(interaction: discord.Interaction, service: str, file: discord.Attachment):
if not owner_role(interaction.user):
return await respond(interaction, "The 👑-Owner role is required.")
service = service.lower().strip()