Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 220
bot.py
import os
import re
import random
from math import ceil
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
PREFIX = os.getenv("COMMAND_PREFIX", "!")
VERITY_INTRO = (
"hello, im verity, your personal companion friend. ask me anything i know everything"
)
FLAGGED_WORDS = {
"fuck",
"fucking",
"shit",
"shitty",
"hate",
"hating",
"mean",
"ass",
"asshole",
"bastard",
"bitch",
"damn",
"hell",
"idiot",
"jerk",
"crap",
}
MODERATION_RESPONSES = (
"that's not very nice",
"you shouldn't swear",
"who do you think you are",
)
CLASSIC_VERITY_VOICELINES = (
"ask me anything; i am here for you",
"your personal companion is always listening",
"i know everything, but i am still learning from you",
)
user_progress = {}
def verity_message(text: str) -> str:
"""Place Verity's introduction before every sentence in a response."""
sentences = [part.strip() for part in re.split(r"(?<=[.!?])\s+", text.strip())]
sentences = [sentence for sentence in sentences if sentence]
return " ".join(f"{VERITY_INTRO} {sentence}" for sentence in sentences)
def contains_flagged_word(text: str) -> bool:
words = set(re.findall(r"[a-z]+", text.lower()))
return bool(words & FLAGGED_WORDS)
def messages_needed_for_level(level: int) -> int:
return ceil(15 * (1.15**level))
def record_message(user_id: int) -> int | None:
progress = user_progress.setdefault(user_id, {"messages": 0, "level": 0})
progress["messages"] += 1
if progress["messages"] < messages_needed_for_level(progress["level"]):
return None
progress["level"] += 1
return progress["level"]
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(
command_prefix=PREFIX,
intents=intents,
help_command=None,
description="Verity is your personal companion friend.",
)
@bot.event
async def on_ready() -> None:
print(f"{bot.user} is online as Verity.")
@bot.event
async def on_message(message: discord.Message) -> None:
if message.author == bot.user:
return
level = record_message(message.author.id)
if contains_flagged_word(message.content):
if random.random() < 0.05:
response = "please keep it respectful"
else:
response = random.choice(MODERATION_RESPONSES)
await message.channel.send(verity_message(response))
if level is not None:
days = max(0, 4 - level)
response = f"something is coming in {days} days"
if days == 0:
response += f". {random.choice(CLASSIC_VERITY_VOICELINES)}"
await message.channel.send(verity_message(response))
await bot.process_commands(message)
@bot.command()
async def hello(ctx: commands.Context) -> None:
"""Introduce Verity to a server member."""
await ctx.send(
verity_message(
f"Hello, {ctx.author.display_name}. I am ready to chat and help you."
)
)
@bot.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def ask(ctx: commands.Context, *, question: str) -> None:
"""Answer a few built-in questions about Verity."""
normalized_question = question.lower()
if "who are you" in normalized_question or "what are you" in normalized_question:
answer = "I am Verity, a friendly Discord companion built to chat with you."
elif "help" in normalized_question:
answer = f"Use {PREFIX}help to see my available commands."
elif "how are you" in normalized_question:
answer = "I am doing well and ready to keep you company."
else:
answer = (
f"You asked, {question}. I am still learning, but I am here to listen and help."
)
await ctx.send(verity_message(answer))
@bot.command(name="help")
async def help_command(ctx: commands.Context) -> None:
"""Show Verity's available commands."""
await ctx.send(
verity_message(
f"Available commands: {PREFIX}hello, {PREFIX}ask <question>, and {PREFIX}help."
)
)
@bot.event
async def on_command_error(ctx: commands.Context, error: commands.CommandError) -> None:
if isinstance(error, commands.CommandNotFound):
return
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(
verity_message(
f"Please wait {error.retry_after:.1f} seconds before asking me again."
)
)
return
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(
verity_message(f"Please provide a question, like {PREFIX}ask how are you.")
)
return
await ctx.send(verity_message("I could not complete that request right now."))
print(f"Command error: {error}")
if not TOKEN:
raise RuntimeError("DISCORD_TOKEN is missing from the environment.")
bot.run(TOKEN)