Files
main.py
requirements.txt
Code
2 115
main.py
import discord
from discord.ext import commands
import os
import asyncio
import google.generativeai as genai
from google.api_core.exceptions import ResourceExhausted
from dotenv import load_dotenv
load_dotenv()
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
MODELS = ["gemini-2.0-flash-lite", "gemini-2.0-flash", "gemini-1.5-pro-latest"]
async def generate_with_fallback(prompt: str) -> str:
for model_name in MODELS:
for attempt in range(3):
try:
model = genai.GenerativeModel(model_name)
response = await asyncio.to_thread(model.generate_content, prompt)
return response.text.strip()
except ResourceExhausted:
if attempt < 2:
await asyncio.sleep(5 * (attempt + 1))
else:
break
except Exception as e:
raise e
raise RuntimeError(
"All available Gemini models have exceeded their quota. "
"Please check your billing at https://ai.dev/rate-limit or try again later."
)
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print(f"Bot is online! Logged in as {bot.user}")
@bot.command(name="start")
async def start(ctx, member: discord.Member = None):
if member is None:
error_embed = discord.Embed(
title="β οΈ Unable to Connect",
description=(
"**Error β** You didn't specify what user to talk to!\n\n"
"**Usage:** `!start @user`\n"
"Please mention a valid server member to begin the AI conversation."
),
color=discord.Color.red()
)
error_embed.set_footer(text="AiChatBot β’ Connection Failed")
await ctx.send(embed=error_embed)
return
thinking_embed = discord.Embed(
title="π€ AI is connecting...",
description=f"Generating a message for {member.mention}, please wait...",
color=discord.Color.blurple()
)
thinking_msg = await ctx.send(embed=thinking_embed)
try:
prompt = (
f"You are an AI assistant in a Discord server. "
f"You are directly addressing a Discord user named '{member.display_name}'. "
f"Write a friendly, engaging, and conversational opening message to them as if you are starting a chat. "
f"Keep it natural, warm, and around 2-4 sentences."
)
ai_text = await generate_with_fallback(prompt)
result_embed = discord.Embed(
title="π€ AI Message",
color=discord.Color.green()
)
result_embed.add_field(
name=f"Talking to {member.display_name}",
value=f"{member.mention}\n\n{ai_text}",
inline=False
)
result_embed.set_thumbnail(url=member.display_avatar.url)
result_embed.set_footer(text=f"AI conversation started by {ctx.author.display_name} β’ AiChatBot")
await thinking_msg.edit(embed=result_embed)
except Exception as e:
err_embed = discord.Embed(
title="β AI Error",
description=f"Something went wrong while generating a response.\n```{e}```",
color=discord.Color.dark_red()
)
err_embed.set_footer(text="AiChatBot β’ Error")
await thinking_msg.edit(embed=err_embed)
@start.error
async def start_error(ctx, error):
if isinstance(error, commands.BadArgument):
bad_embed = discord.Embed(
title="β οΈ Invalid User",
description=(
"**Error β** The user you mentioned could not be found!\n\n"
"Make sure you are **@mentioning** a valid member of this server.\n"
"**Usage:** `!start @user`"
),
color=discord.Color.orange()
)
bad_embed.set_footer(text="AiChatBot β’ Connection Failed")
await ctx.send(embed=bad_embed)
bot.run(os.getenv("DISCORD_TOKEN"))