Files
sounds
.gitignore
bot.py
README.md
requirements.txt
Code
5 420
bot.py
import logging
import os
import random
import re
from datetime import timedelta
from pathlib import Path
from typing import Optional
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("bobgoblin")
TOKEN = os.getenv("DISCORD_TOKEN")
DEV_GUILD_ID = os.getenv("DEV_GUILD_ID")
SOUNDS_DIR = Path(__file__).parent / "sounds"
SOUNDS_DIR.mkdir(exist_ok=True)
intents = discord.Intents.default()
intents.members = True
intents.voice_states = True
bot = commands.Bot(command_prefix="!", intents=intents, help_command=None)
PHRASES = [
"Bobgoblin says: Snick-snack, let's make some mischief!",
"A goblin-sized hello with a very big grin!",
"Keep your socks safe. Bobgoblin is feeling especially sneaky today.",
"By the power of perfectly lumpy potatoes, I summon fun!",
"Psst... your awesomeness is showing. Don't let the grown-ups notice.",
]
JOKES = [
"Why did the goblin bring a ladder? To climb the social scale!",
"What do you call a goblin who tells tall tales? A big fib-lin!",
"Why was the magic spell so calm? It had excellent spell-f-control.",
"What is a goblin's favorite kind of music? Anything with a good beet!",
"Why did the potion go to school? It wanted to improve its chemistry!",
]
SPELLS = {
"goblin-glitter": "A glitter cloud explodes! Everyone sparkles, especially the turnips.",
"mud-meteor": "A tiny mud meteor lands with a satisfying splat. No socks are safe.",
"sock-summon": "A mysterious sock appears. Its matching partner remains legendary.",
"snicker-spark": "A snicker-spark zaps through the room and makes everyone giggle.",
}
def custom_emoji(name: str, fallback: str) -> str:
emoji_id = os.getenv(f"{name.upper()}_EMOJI_ID", "").strip()
if emoji_id.isdigit():
return f"<:{name.lower()}:{emoji_id}>"
return fallback
BOB = custom_emoji("BOB", "๐บ")
MAGIC = custom_emoji("MAGIC", "๐ช")
SPARKLE = custom_emoji("SPARKLE", "โจ")
async def respond(interaction: discord.Interaction, content: str, *, ephemeral: bool = False) -> None:
if interaction.response.is_done():
await interaction.followup.send(content, ephemeral=ephemeral)
else:
await interaction.response.send_message(content, ephemeral=ephemeral)
class BobgoblinView(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout=180)
@discord.ui.button(label="Tell me a joke", emoji="๐", style=discord.ButtonStyle.primary)
async def joke_button(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
await interaction.response.send_message(f"{BOB} {random.choice(JOKES)}", view=BobgoblinView())
@discord.ui.button(label="Cast a spell", emoji="๐ช", style=discord.ButtonStyle.success)
async def magic_button(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
spell_name, result = random.choice(list(SPELLS.items()))
await interaction.response.send_message(
f"{MAGIC} **{spell_name.replace('-', ' ').title()}!** {result}",
view=BobgoblinView(),
)
@bot.event
async def on_ready() -> None:
if bot.user is not None:
logger.info("Logged in as %s (%s)", bot.user, bot.user.id)
@bot.tree.command(name="say", description="Hear one of Bobgoblin's playful phrases.")
@app_commands.describe(mood="Choose the kind of phrase Bobgoblin should use")
@app_commands.choices(
mood=[
app_commands.Choice(name="mischievous", value="mischievous"),
app_commands.Choice(name="friendly", value="friendly"),
app_commands.Choice(name="random", value="random"),
]
)
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: interaction.user.id)
async def say_command(
interaction: discord.Interaction,
mood: Optional[app_commands.Choice[str]] = None,
) -> None:
if mood and mood.value == "friendly":
phrase = "Bobgoblin says: You are doing brilliantly today!"
elif mood and mood.value == "mischievous":
phrase = random.choice(PHRASES[1:])
else:
phrase = random.choice(PHRASES)
await interaction.response.send_message(f"{BOB} {phrase}")
@bot.tree.command(name="joke", description="Ask Bobgoblin for a silly joke.")
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: interaction.user.id)
async def joke_command(interaction: discord.Interaction) -> None:
await interaction.response.send_message(f"{BOB} {random.choice(JOKES)}", view=BobgoblinView())
@bot.tree.command(name="magic", description="Cast a playful Bobgoblin spell.")
@app_commands.describe(spell="Select a spell, or leave it blank for a surprise")
@app_commands.choices(
spell=[app_commands.Choice(name=name.replace("-", " ").title(), value=name) for name in SPELLS]
)
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: interaction.user.id)
async def magic_command(
interaction: discord.Interaction,
spell: Optional[app_commands.Choice[str]] = None,
) -> None:
spell_name = spell.value if spell else random.choice(list(SPELLS))
await interaction.response.send_message(
f"{MAGIC} **{spell_name.replace('-', ' ').title()}!** {SPELLS[spell_name]}"
)
@bot.tree.command(name="playground", description="Open an interactive Bobgoblin joke and magic playground.")
async def playground_command(interaction: discord.Interaction) -> None:
embed = discord.Embed(
title=f"{BOB} Bobgoblin's Playground",
description="Press a button and see what sort of trouble we can make.",
color=discord.Color.green(),
)
embed.set_footer(text="Buttons expire after three minutes.")
await interaction.response.send_message(embed=embed, view=BobgoblinView())
@bot.tree.command(name="emoji", description="Show Bobgoblin's emoji spellbook.")
async def emoji_command(interaction: discord.Interaction) -> None:
await interaction.response.send_message(
f"{BOB} Bobgoblin | {MAGIC} Magic | {SPARKLE} Sparkles\n"
"Add your server's custom emoji IDs to `.env` to replace the fallback emojis."
)
def sound_file(name: str) -> Optional[Path]:
candidate = (SOUNDS_DIR / name).resolve()
if candidate.parent != SOUNDS_DIR.resolve() or candidate.suffix.lower() not in {".mp3", ".wav", ".ogg"}:
return None
return candidate if candidate.is_file() else None
@bot.tree.command(name="sound", description="List or play a sound effect in your voice channel.")
@app_commands.describe(action="Choose whether to list, play, or stop a sound", sound_name="A file in the sounds folder")
@app_commands.choices(
action=[
app_commands.Choice(name="list sounds", value="list"),
app_commands.Choice(name="play sound", value="play"),
app_commands.Choice(name="stop sound", value="stop"),
]
)
async def sound_command(
interaction: discord.Interaction,
action: app_commands.Choice[str],
sound_name: Optional[str] = None,
) -> None:
if action.value == "list":
sounds = sorted(path.name for path in SOUNDS_DIR.iterdir() if path.suffix.lower() in {".mp3", ".wav", ".ogg"})
message = "Available sound effects: " + (", ".join(f"`{name}`" for name in sounds) if sounds else "none yet")
await interaction.response.send_message(message, ephemeral=True)
return
if interaction.guild is None:
await respond(interaction, "Sound effects can only be used inside a server.", ephemeral=True)
return
voice_state = getattr(interaction.user, "voice", None)
if voice_state is None or voice_state.channel is None:
await respond(interaction, "Join a voice channel first, you marvelous little goblin.", ephemeral=True)
return
voice_client = interaction.guild.voice_client