Skip to content

Instantly share code, notes, and snippets.

@tobySolutions
Last active February 11, 2025 19:36
Show Gist options
  • Save tobySolutions/8f7a06f75bad1c030df065549b1c5d63 to your computer and use it in GitHub Desktop.
Save tobySolutions/8f7a06f75bad1c030df065549b1c5d63 to your computer and use it in GitHub Desktop.
import discord
from discord.ext import commands
import json
import aiohttp
import os
import logging
from datetime import datetime
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('gaia_agent.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger('gaia_agent')
# Configuration
TOKEN = ''
API_ENDPOINT = 'http://localhost:8080/v1/chat/completions'
SYSTEM_PROMPT = """You are the Gaia DevRel Agent, an AI-powered assistant designed to provide technical support
for developers working with Gaia. You help with integrating Gaia, running nodes, creating agents, and
troubleshooting issues. You're knowledgeable about ElizaOS and aim to lower the barrier of entry for builders
in the Gaia ecosystem."""
intents = discord.Intents.default()
intents.message_content = True
intents.guild_messages = True
intents.guilds = True
intents.dm_messages = True
bot = commands.Bot(command_prefix='!', intents=intents)
class GaiaDevRelBot:
def __init__(self):
self.conversation_history = {}
self.session = None
async def initialize(self):
self.session = aiohttp.ClientSession()
logger.info("Initialized aiohttp session")
async def cleanup(self):
if self.session:
await self.session.close()
logger.info("Cleaned up aiohttp session")
async def get_ai_response(self, thread_id: str, user_message: str) -> str:
logger.info(f"Processing request for thread {thread_id}")
if thread_id not in self.conversation_history:
logger.info(f"Creating new conversation history for thread {thread_id}")
self.conversation_history[thread_id] = [
{"role": "system", "content": SYSTEM_PROMPT}
]
self.conversation_history[thread_id].append({
"role": "user",
"content": user_message
})
headers = {
'accept': 'application/json',
'Content-Type': 'application/json'
}
try:
request_start_time = datetime.now()
logger.info(f"Sending request to API endpoint")
async with self.session.post(
API_ENDPOINT,
headers=headers,
json={"messages": self.conversation_history[thread_id]}
) as response:
request_duration = (datetime.now() - request_start_time).total_seconds()
logger.info(f"API request completed in {request_duration:.2f} seconds")
if response.status == 200:
data = await response.json()
ai_response = data['choices'][0]['message']['content']
logger.info("Received successful response from API")
self.conversation_history[thread_id].append({
"role": "assistant",
"content": ai_response
})
return ai_response
else:
error_data = await response.text()
logger.error(f"API error: Status {response.status}, Details: {error_data}")
return f"Error: API returned status {response.status}. Details: {error_data}"
except Exception as e:
logger.error(f"Error communicating with AI service: {str(e)}", exc_info=True)
return f"Error communicating with AI service: {str(e)}"
devrel_bot = GaiaDevRelBot()
@bot.event
async def on_ready():
logger.info(f"Bot {bot.user} is online and ready!")
await devrel_bot.initialize()
try:
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.watching,
name="for Gaia dev questions 🤖"
))
logger.info("Bot presence updated successfully")
except Exception as e:
logger.error(f"Failed to set presence: {e}")
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if bot.user.mentioned_in(message) or isinstance(message.channel, discord.DMChannel):
logger.info(f"Received message from {message.author} in {message.channel}")
try:
if isinstance(message.channel, discord.TextChannel):
logger.info(f"Creating new thread for message")
thread = await message.create_thread(
name=f"Gaia Support - {message.author.name}",
auto_archive_duration=60
)
response = await devrel_bot.get_ai_response(
str(thread.id),
message.content.replace(f'<@{bot.user.id}>', '').strip()
)
await thread.send(response)
logger.info(f"Sent response in thread {thread.name}")
else:
response = await devrel_bot.get_ai_response(
str(message.channel.id),
message.content.replace(f'<@{bot.user.id}>', '').strip()
)
await message.channel.send(response)
logger.info(f"Sent response in channel {message.channel}")
except Exception as e:
error_msg = f"Error processing request: {str(e)}"
logger.error(error_msg, exc_info=True)
await message.channel.send(error_msg)
await bot.process_commands(message)
@bot.command(name='gaia-help')
async def gaia_help_command(ctx):
logger.info(f"Help command requested by {ctx.author}")
help_text = """
**Gaia DevRel Agent Help**
I'm here to help you with:
• Technical support for Gaia integration
• Node setup and maintenance
• Agent creation and deployment
• ElizaOS-related questions
• General troubleshooting
You can interact with me by:
1. Mentioning me in any channel
2. DMing me directly
3. Using commands like `!gaia-help`
I'll create dedicated threads for our conversations to keep things organized!
"""
try:
await ctx.send(help_text)
logger.info(f"Help message sent to {ctx.author}")
except Exception as e:
logger.error(f"Error sending help message: {e}")
@bot.event
async def on_guild_join(guild):
logger.info(f"Bot joined new guild: {guild.name} (ID: {guild.id})")
welcome_message = """
👋 Hello! I'm the **Gaia DevRel Agent**, your AI-powered technical support assistant!
I'm here to help with:
• Gaia integration support
• Node operations
• Agent creation
• Technical troubleshooting
Just mention me in any channel or DM me to get started. I'll create dedicated threads for our conversations!
Type `!gaia-help` for more information about what I can do.
This is an open-source project - contributions welcome at [GitHub repo link]!
"""
try:
channel = discord.utils.get(guild.text_channels, name='general') or guild.text_channels[0]
await channel.send(welcome_message)
logger.info(f"Sent welcome message in {channel.name}")
except Exception as e:
logger.error(f"Error sending welcome message: {e}")
@bot.event
async def on_thread_create(thread):
try:
if thread.owner_id == bot.user.id:
await thread.send("🤖 Thread created! I'll keep our conversation here to stay organized. One moment, I will respond to your questions.")
logger.info(f"Created new thread: {thread.name}")
except Exception as e:
logger.error(f"Error in thread creation: {e}")
def main():
logger.info("Starting Gaia DevRel Bot")
try:
bot.run(TOKEN)
except Exception as e:
logger.error(f"Error running bot: {e}")
finally:
import asyncio
asyncio.run(devrel_bot.cleanup())
logger.info("Bot shutdown complete")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment