Files
bot.py
requirements.txt
Code
2 333
bot.py
import logging
import os
import random
from datetime import timedelta
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("kodari_bot")
class AllInOneBot(commands.Bot):
def __init__(self) -> None:
super().__init__(command_prefix=commands.when_mentioned, intents=discord.Intents.default())
async def setup_hook(self) -> None:
synced = await self.tree.sync()
logger.info("Synced %s application commands", len(synced))
bot = AllInOneBot()
@bot.event
async def on_ready() -> None:
logger.info("Logged in as %s", bot.user)
print("KODARI_READY", flush=True)
async def send_command_error(interaction: discord.Interaction, message: str) -> None:
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
@bot.tree.error
async def on_app_command_error(
interaction: discord.Interaction,
error: app_commands.AppCommandError,
) -> None:
if isinstance(error, app_commands.MissingPermissions):
await send_command_error(interaction, "You don't have permission to use that command.")
elif isinstance(error, app_commands.BotMissingPermissions):
await send_command_error(interaction, "I don't have the permissions needed for that command.")
elif isinstance(error, app_commands.CommandOnCooldown):
await send_command_error(interaction, f"Try again in {error.retry_after:.1f} seconds.")
elif isinstance(error, app_commands.CommandInvokeError):
cause = error.original
if isinstance(cause, discord.Forbidden):
await send_command_error(
interaction,
"Discord blocked that action. Check my permissions and role position.",
)
elif isinstance(cause, discord.HTTPException):
logger.warning("Discord API error in /%s: %s", interaction.command, cause)
await send_command_error(interaction, "Discord couldn't complete that action. Please try again.")
else:
logger.exception("Unexpected error in /%s", interaction.command, exc_info=cause)
await send_command_error(interaction, "Something went wrong while running that command.")
else:
logger.warning("Application command error: %s", error)
await send_command_error(interaction, "That command couldn't be completed.")
@bot.tree.command(name="help", description="Show the bot's commands")
async def help_command(interaction: discord.Interaction) -> None:
embed = discord.Embed(
title="All-in-One Bot Commands",
color=discord.Color.blurple(),
description="Use these slash commands to get started.",
)
embed.add_field(
name="Useful",
value="`/ping` · `/userinfo` · `/serverinfo` · `/avatar` · `/poll` · `/announce`",
inline=False,
)
embed.add_field(
name="Fun",
value="`/choose` · `/coinflip` · `/8ball`",
inline=False,
)
embed.add_field(
name="Moderation",
value="`/purge` · `/kick` · `/ban` · `/timeout` · `/untimeout` · `/slowmode` · `/lock` · `/unlock` · `/role_add` · `/role_remove`",
inline=False,
)
await interaction.response.send_message(embed=embed, ephemeral=True)
@bot.tree.command(name="ping", description="Check the bot's response time")
async def ping(interaction: discord.Interaction) -> None:
latency_ms = round(bot.latency * 1000)
await interaction.response.send_message(f"Pong! `{latency_ms} ms`")
@bot.tree.command(name="userinfo", description="Show information about a server member")
@app_commands.guild_only()
async def userinfo(
interaction: discord.Interaction,
member: discord.Member | None = None,
) -> None:
target = member or interaction.user
embed = discord.Embed(title=f"User info: {target}", color=discord.Color.blurple())
embed.set_thumbnail(url=target.display_avatar.url)
embed.add_field(name="User ID", value=target.id, inline=True)
embed.add_field(name="Account created", value=discord.utils.format_dt(target.created_at, style="D"), inline=True)
embed.add_field(name="Joined server", value=discord.utils.format_dt(target.joined_at, style="D") if target.joined_at else "Unknown", inline=True)
embed.add_field(name="Top role", value=target.top_role.mention, inline=True)
await interaction.response.send_message(embed=embed)
@bot.tree.command(name="serverinfo", description="Show information about this server")
@app_commands.guild_only()
async def serverinfo(interaction: discord.Interaction) -> None:
guild = interaction.guild
if guild is None:
await send_command_error(interaction, "This command can only be used in a server.")
return
embed = discord.Embed(title=guild.name, color=discord.Color.blurple())
if guild.icon:
embed.set_thumbnail(url=guild.icon.url)
embed.add_field(name="Server ID", value=guild.id, inline=True)
embed.add_field(name="Owner", value=guild.owner.mention if guild.owner else "Unknown", inline=True)
embed.add_field(name="Members", value=guild.member_count or "Unknown", inline=True)
embed.add_field(name="Created", value=discord.utils.format_dt(guild.created_at, style="D"), inline=True)
await interaction.response.send_message(embed=embed)
@bot.tree.command(name="avatar", description="Show a user's avatar")
async def avatar(
interaction: discord.Interaction,
user: discord.User | None = None,
) -> None:
target = user or interaction.user
embed = discord.Embed(title=f"{target.display_name}'s avatar", color=discord.Color.blurple())
embed.set_image(url=target.display_avatar.url)
await interaction.response.send_message(embed=embed)
@bot.tree.command(name="poll", description="Create a reaction poll with 2 to 10 choices")
@app_commands.describe(question="What are you asking?", choices="Separate 2–10 choices with |")
async def poll(interaction: discord.Interaction, question: str, choices: str) -> None:
options = [choice.strip() for choice in choices.split("|") if choice.strip()]
if not 2 <= len(options) <= 10:
await send_command_error(interaction, "Provide between 2 and 10 choices, separated with `|`.")
return
number_emojis = ("1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟")
description = "\n".join(f"{number_emojis[index]} {choice}" for index, choice in enumerate(options))
embed = discord.Embed(title=question, description=description, color=discord.Color.blurple())
embed.set_footer(text=f"Poll by {interaction.user.display_name}")
await interaction.response.send_message(embed=embed)
message = await interaction.original_response()
for emoji in number_emojis[:len(options)]:
await message.add_reaction(emoji)
@bot.tree.command(name="announce", description="Post an announcement in a text channel")
@app_commands.checks.has_permissions(manage_messages=True)
@app_commands.describe(channel="Where to post", message="Announcement text")
async def announce(
interaction: discord.Interaction,
channel: discord.TextChannel,
message: str,
) -> None:
await channel.send(message, allowed_mentions=discord.AllowedMentions.none())
await interaction.response.send_message(f"Announcement posted in {channel.mention}.", ephemeral=True)
@bot.tree.command(name="choose", description="Pick one option at random")
@app_commands.describe(options="Separate options with | (for example: tea | coffee | water)")
async def choose(interaction: discord.Interaction, options: str) -> None:
items = [item.strip() for item in options.split("|") if item.strip()]
if len(items) < 2:
await send_command_error(interaction, "Give me at least two options separated with `|`.")
return
await interaction.response.send_message(f"🎯 I choose: **{random.choice(items)}**")
@bot.tree.command(name="coinflip", description="Flip a coin")
async def coinflip(interaction: discord.Interaction) -> None:
await interaction.response.send_message(f"🪙 It's **{random.choice(('Heads', 'Tails'))}!**")
@bot.tree.command(name="8ball", description="Ask the magic 8-ball a question")
@app_commands.describe(question="Your question")
async def eight_ball(interaction: discord.Interaction, question: str) -> None:
answers = (
"It is certain.", "Without a doubt.", "Yes, definitely.", "You may rely on it.",
"Ask again later.", "Cannot predict now.", "Don't count on it.", "My sources say no.",
)