Skip to content

Commit

Permalink
track cost and post to activity status
Browse files Browse the repository at this point in the history
  • Loading branch information
fredsmith committed Dec 4, 2024
1 parent 82002b1 commit 6c7ef4e
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from discord.ext import commands
from anthropic import Anthropic
from dotenv import load_dotenv
from datetime import datetime, date
import asyncio

# Load environment variables
load_dotenv()
Expand All @@ -28,6 +30,37 @@
# Store channel-specific conversations
channel_conversations = {}

# API cost tracking
daily_cost = 0.0
last_reset_date = date.today()
COST_PER_INPUT_TOKEN = 0.003 # $3 per million tokens
COST_PER_OUTPUT_TOKEN = 0.015 # $15 per million tokens

async def update_activity_status():
"""Update bot's activity status with current daily API cost"""
activity = discord.Activity(
type=discord.ActivityType.watching,
name=f"${daily_cost:.2f}"
)
await bot.change_presence(activity=activity)

async def reset_daily_cost():
"""Reset daily cost if it's a new day"""
global daily_cost, last_reset_date
current_date = date.today()
if current_date > last_reset_date:
daily_cost = 0.0
last_reset_date = current_date
await update_activity_status()

async def update_cost(input_tokens, output_tokens):
"""Update daily cost based on token usage"""
global daily_cost
input_cost = (input_tokens * COST_PER_INPUT_TOKEN) / 1_000_000
output_cost = (output_tokens * COST_PER_OUTPUT_TOKEN) / 1_000_000
daily_cost += input_cost + output_cost
await update_activity_status()

async def get_system_prompt(channel):
"""Get system prompt by concatenating all pinned messages in the channel"""
pinned_messages = await channel.pins()
Expand Down Expand Up @@ -68,13 +101,17 @@ async def on_ready():
print(f'Using Claude model: {MODEL}')
for guild in bot.guilds:
print(f'- {guild.name} (id: {guild.id})')
await update_activity_status()

@bot.event
async def on_message(message):
# Ignore messages from the bot itself
if message.author == bot.user:
return

# Check if it's a new day and reset costs if needed
await reset_daily_cost()

# Process commands first
await bot.process_commands(message)

Expand Down Expand Up @@ -126,6 +163,12 @@ async def on_message(message):
messages=messages
)

# Update costs based on token usage
await update_cost(
response.usage.input_tokens,
response.usage.output_tokens
)

assistant_message = response.content[0].text
conversation['messages'].append({
'role': 'assistant',
Expand Down Expand Up @@ -171,6 +214,11 @@ async def refresh_system_prompt(ctx):
else:
await ctx.send("No conversation found for this channel.")

@bot.command(name='cost')
async def show_cost(ctx):
"""Show the current daily API cost"""
await ctx.send(f"Current daily API cost: ${daily_cost:.2f}")

# Run the bot
if __name__ == "__main__":
bot.run(os.getenv('DISCORD_TOKEN'))

0 comments on commit 6c7ef4e

Please sign in to comment.