Files
bot.py
requirements.txt
Code
2 598
bot.py
import asyncio
import json
import logging
import os
import random
import shlex
import shutil
import sqlite3
import time
from collections import deque
from datetime import datetime, timezone
from urllib.parse import urlparse
from xml.etree import ElementTree
import aiohttp
import discord
import yt_dlp
from discord import app_commands
from discord.ext import commands, tasks
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("fbk_python")
db = sqlite3.connect("bot_data.sqlite3")
db.row_factory = sqlite3.Row
db.executescript("""
CREATE TABLE IF NOT EXISTS feeds (
id INTEGER PRIMARY KEY, guild_id INTEGER NOT NULL, channel_id INTEGER NOT NULL,
kind TEXT NOT NULL, source TEXT NOT NULL, last_item TEXT,
UNIQUE(guild_id, channel_id, kind, source)
);
CREATE TABLE IF NOT EXISTS reminders (
id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, channel_id INTEGER NOT NULL,
due REAL NOT NULL, message TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS custom_commands (
guild_id INTEGER NOT NULL, name TEXT NOT NULL, response TEXT NOT NULL,
PRIMARY KEY(guild_id, name)
);
CREATE TABLE IF NOT EXISTS welcome (
guild_id INTEGER PRIMARY KEY, channel_id INTEGER NOT NULL, message TEXT NOT NULL,
role_id INTEGER
);
CREATE TABLE IF NOT EXISTS livestreams (
id INTEGER PRIMARY KEY, guild_id INTEGER NOT NULL, channel_id INTEGER NOT NULL,
youtube_channel_id TEXT NOT NULL,
UNIQUE(guild_id, channel_id, youtube_channel_id)
);
CREATE TABLE IF NOT EXISTS livestream_announcements (
subscription_id INTEGER NOT NULL, video_id TEXT NOT NULL,
PRIMARY KEY(subscription_id, video_id)
);
""")
db.commit()
class Bot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.members = True
super().__init__(command_prefix=commands.when_mentioned, intents=intents)
self.http_session = None
self.music_queues = {}
self.music_locks = {}
async def setup_hook(self):
self.http_session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=20))
await self.tree.sync()
check_reminders.start()
check_feeds.start()
check_livestreams.start()
async def close(self):
check_reminders.cancel()
check_feeds.cancel()
check_livestreams.cancel()
if self.http_session:
await self.http_session.close()
await super().close()
db.close()
bot = Bot()
@bot.event
async def on_ready():
log.info("Connected as %s", bot.user)
print("KODARI_READY", flush=True)
@bot.event
async def on_member_join(member: discord.Member):
row = db.execute("SELECT * FROM welcome WHERE guild_id = ?", (member.guild.id,)).fetchone()
if not row:
return
if row["role_id"]:
role = member.guild.get_role(row["role_id"])
if role:
try:
await member.add_roles(role, reason="Configured join role")
except discord.HTTPException:
log.exception("Could not add join role in guild %s", member.guild.id)
channel = member.guild.get_channel(row["channel_id"])
if channel:
try:
text = row["message"].replace("{user}", member.mention).replace("{server}", member.guild.name)
await channel.send(text, allowed_mentions=discord.AllowedMentions(users=[member]))
except discord.HTTPException:
log.exception("Could not send welcome in guild %s", member.guild.id)
@bot.tree.error
async def on_app_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.MissingPermissions):
message = "You don't have permission to use this command."
elif isinstance(error, app_commands.CommandOnCooldown):
message = f"Try again in {error.retry_after:.1f} seconds."
else:
log.error("Command failed", exc_info=(type(error), error, error.__traceback__))
message = "Something went wrong while running that command."
try:
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
except discord.HTTPException:
log.exception("Could not report command error")
@bot.tree.command(name="help", description="Show available commands")
async def help_command(interaction: discord.Interaction):
embed = discord.Embed(title="Bot commands", color=discord.Color.blurple())
embed.description = (
"`/feed add`, `/feed list`, `/feed remove` — YouTube and Bluesky notifications\n"
"`/live add`, `/live list`, `/live remove` — YouTube livestream alerts\n"
"`/music play`, `/music skip`, `/music stop`, `/music queue` — voice playback\n"
"`/remind`, `/reminders`, `/cancel_reminder` — personal reminders\n"
"`/welcome set`, `/welcome disable` — welcome messages and optional join role\n"
"`/custom set`, `/custom run`, `/custom remove`, `/custom list` — custom responses\n"
"`/avatar`, `/server`, `/rps`, `/purge` — utilities and games"
)
await interaction.response.send_message(embed=embed, ephemeral=True)
feed = app_commands.Group(name="feed", description="Manage notification feeds", guild_only=True)
bot.tree.add_command(feed)
async def latest_feed_item(kind: str, source: str):
if kind == "youtube":
url = "https://www.youtube.com/feeds/videos.xml"
async with bot.http_session.get(url, params={"channel_id": source}) as response:
response.raise_for_status()
root = ElementTree.fromstring(await response.text())
entry = root.find("{http://www.w3.org/2005/Atom}entry")
if entry is None:
return None
video_id = entry.findtext("{http://www.youtube.com/xml/schemas/2015}videoId")
title = entry.findtext("{http://www.w3.org/2005/Atom}title") or "New video"
if not video_id:
return None
return video_id, f"**{discord.utils.escape_markdown(title)}**\nhttps://www.youtube.com/watch?v={video_id}"
url = "https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed"
async with bot.http_session.get(url, params={"actor": source, "limit": 10, "filter": "posts_no_replies"}) as response:
response.raise_for_status()
data = await response.json()
for item in data.get("feed", []):
post = item.get("post", {})
if item.get("reason") or post.get("author", {}).get("did") != data.get("feed", [{}])[0].get("post", {}).get("author", {}).get("did"):
continue
uri = post.get("uri", "")
author = post.get("author", {}).get("handle", source)
if uri.startswith("at://"):
text = post.get("record", {}).get("text", "")[:300]
return uri, f"New Bluesky post from **{discord.utils.escape_markdown(author)}**:\n{discord.utils.escape_mentions(text)}\nhttps://bsky.app/profile/{author}/post/{uri.rsplit('/', 1)[-1]}"
return None
@feed.command(name="add", description="Add a YouTube channel ID or Bluesky handle to this channel")
@app_commands.checks.has_permissions(manage_guild=True)
@app_commands.choices(kind=[app_commands.Choice(name="YouTube", value="youtube"), app_commands.Choice(name="Bluesky", value="bluesky")])
async def feed_add(interaction: discord.Interaction, kind: app_commands.Choice[str], source: str):
source = source.strip().lstrip("@")
if not source or len(source) > 200 or any(c.isspace() for c in source):
return await interaction.response.send_message("Enter a valid YouTube channel ID or Bluesky handle.", ephemeral=True)
await interaction.response.defer(ephemeral=True, thinking=True)
try:
item = await latest_feed_item(kind.value, source)
except (aiohttp.ClientError, asyncio.TimeoutError, ElementTree.ParseError, ValueError):
log.exception("Could not fetch feed %s", source)
return await interaction.followup.send("Could not fetch that feed. Check the channel ID or handle and try again.", ephemeral=True)
if item is None:
return await interaction.followup.send("No posts found; the feed may be empty or the account invalid. Try again after its first post.", ephemeral=True)
try:
db.execute("INSERT INTO feeds (guild_id, channel_id, kind, source, last_item) VALUES (?, ?, ?, ?, ?)",
(interaction.guild_id, interaction.channel_id, kind.value, source, item[0]))
db.commit()




