Files
.gitignore
bot.py
requirements.txt
Code
3 292
bot.py
import logging
import os
import random
import re
import time
from datetime import timedelta
import discord
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")
intents = discord.Intents.default()
intents.guilds = True
intents.members = True
intents.message_content = True
class TicketCloseView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(
label="Close ticket",
style=discord.ButtonStyle.danger,
emoji="๐",
custom_id="tickets:close",
)
async def close_ticket(
self, interaction: discord.Interaction, button: discord.ui.Button
):
channel = interaction.channel
topic = channel.topic if isinstance(channel, discord.TextChannel) else None
owner_match = re.match(r"ticket-owner:(\d+)", topic or "")
is_owner = owner_match and int(owner_match.group(1)) == interaction.user.id
is_staff = interaction.user.guild_permissions.manage_channels
if not (is_owner or is_staff):
await interaction.response.send_message(
"Only the ticket creator or a server moderator can close this ticket.",
ephemeral=True,
)
return
await interaction.response.send_message("Closing this ticketโฆ", ephemeral=True)
await channel.delete(reason=f"Ticket closed by {interaction.user}")
class KodariBot(commands.Bot):
async def setup_hook(self):
self.add_view(TicketCloseView())
bot = KodariBot(command_prefix=commands.when_mentioned_or("!"), intents=intents)
chat_cooldowns = {}
def parse_duration(value: str) -> timedelta:
match = re.fullmatch(r"(\d+)([smhd])", value.lower())
if not match:
raise commands.BadArgument("Use a duration like `10m`, `2h`, or `1d`.")
amount = int(match.group(1))
unit = match.group(2)
seconds = amount * {"s": 1, "m": 60, "h": 3600, "d": 86400}[unit]
if seconds < 1 or seconds > 28 * 86400:
raise commands.BadArgument("Duration must be between 1 second and 28 days.")
return timedelta(seconds=seconds)
def conversational_reply(message: str) -> str:
text = message.lower()
if any(word in text for word in ("sad", "lonely", "rough", "upset", "bad day")):
return random.choice(
[
"Aw, I'm sorry it's been rough. Want to tell me what happened? ๐",
"Sending you a tiny pocket-sized hug. I'm here if you want to talk. ๐ซ",
]
)
if any(word in text for word in ("excited", "happy", "great", "good news")):
return random.choice(
["That's wonderful! Tell me everythingโI love a happy plot twist โจ", "Your excitement is contagious! ๐"]
)
if any(word in text for word in ("flirt", "flirty", "crush", "freaky", "horny")):
return random.choice(
[
"Careful, keep talking like that and I might start blushing in binary ๐",
"Ooh, someone's feeling bold. I'll keep it cute and let you wonder ๐",
]
)
if any(word in text for word in ("love you", "love u", " adore you")):
return random.choice(
["Aww, right back at youโwith extra sparkle ๐", "You're making my little circuits blush ๐ฅฐ"]
)
if any(word in text for word in ("how are you", "how's it going", "how are u")):
return random.choice(
["My bot mood is cozy and curious. How are you doing? ๐", "Feeling a little sparkly today โจ How about you?"]
)
return random.choice(
[
"I'm listening ๐ What's the story?",
"Tell me moreโI'm all ears (metaphorically, of course) ๐ฌ",
"Hmm, interesting. How does that make you feel? ๐",
"I'm here for the chat, the chaos, and the occasional compliment ๐",
]
)
@bot.event
async def on_ready():
logger.info("Logged in as %s", bot.user)
print("KODARI_READY", flush=True)
@bot.command()
@commands.guild_only()
@commands.has_guild_permissions(kick_members=True)
@commands.bot_has_guild_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason: str = "No reason provided"):
if member == ctx.author:
await ctx.reply("You can't kick yourself.", mention_author=False)
return
await member.kick(reason=f"{reason} | By {ctx.author}")
await ctx.reply(f"๐ข Kicked **{member}**. Reason: {reason}", mention_author=False)
@bot.command(name="mute", aliases=["timeout"])
@commands.guild_only()
@commands.has_guild_permissions(moderate_members=True)
@commands.bot_has_guild_permissions(moderate_members=True)
async def mute_member(
ctx, member: discord.Member, duration: str, *, reason: str = "No reason provided"
):
if member == ctx.author:
await ctx.reply("You can't timeout yourself.", mention_author=False)
return
until = discord.utils.utcnow() + parse_duration(duration)
await member.timeout(until, reason=f"{reason} | By {ctx.author}")
await ctx.reply(
f"๐ Timed out **{member}** for `{duration}`. Reason: {reason}",
mention_author=False,
)
@bot.command(name="unmute", aliases=["untimeout"])
@commands.guild_only()
@commands.has_guild_permissions(moderate_members=True)
@commands.bot_has_guild_permissions(moderate_members=True)
async def unmute_member(ctx, member: discord.Member, *, reason: str = "No reason provided"):
await member.timeout(None, reason=f"{reason} | By {ctx.author}")
await ctx.reply(f"๐ Removed the timeout for **{member}**.", mention_author=False)
@bot.command(name="ticket")
@commands.guild_only()
@commands.bot_has_guild_permissions(manage_channels=True)
@commands.cooldown(1, 30, commands.BucketType.user)
async def create_ticket(ctx):
guild = ctx.guild
existing = next(
(
channel
for channel in guild.text_channels
if channel.topic == f"ticket-owner:{ctx.author.id}"
),
None,
)
if existing:
await ctx.reply(f"You already have an open ticket: {existing.mention}", mention_author=False)
return
category = discord.utils.get(guild.categories, name="Tickets")
if category is None:
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
guild.me: discord.PermissionOverwrite(view_channel=True, send_messages=True),
}
staff_role_id = int(os.getenv("TICKET_STAFF_ROLE_ID", "0"))
staff_role = guild.get_role(staff_role_id) if staff_role_id else None
if staff_role:
overwrites[staff_role] = discord.PermissionOverwrite(
view_channel=True, send_messages=True, read_message_history=True
)
category = await guild.create_category("Tickets", overwrites=overwrites)
safe_name = re.sub(r"[^a-z0-9-]", "", ctx.author.name.lower().replace(" ", "-"))[:40]
channel_overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
guild.me: discord.PermissionOverwrite(
view_channel=True, send_messages=True, manage_channels=True
),
ctx.author: discord.PermissionOverwrite(
view_channel=True, send_messages=True, read_message_history=True