import discord
import anthropic
from dotenv import load_dotenv
import os
# The following are used for debugging purposes, remove if you like
import time

release = "stable-0.1.1"

load_dotenv()

# Give your bot a name and a personality!
idName = os.getenv('NAME')
identity = os.getenv('IDENTITY')
# Use this variable to allow certain things that may be blocked. Useful for making coding assistants, writing assistants etc
allowedTopics = os.getenv('ALLOWED_TOPICS')
# Add your bot's response word here (set up an @mention one by mentioning your bot, then copying text and pasting it in the variable)
wakeWord = os.getenv('WAKE_WORD')
# Impose reasonable restrictions, delete these with caution!
restrictions = os.getenv('RESTRICTIONS')
intents = discord.Intents.default()
intents.message_content = True

aiclient = anthropic.Anthropic(
    # Put your Anthropic API key here. Get yours at https://console.anthropic.com/settings/keys
    api_key = os.getenv('ANTHROPIC_KEY'),
)

client = discord.Client(intents=intents)
@client.event
async def on_ready():
    print("Logged in as ", client.user)
@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if (wakeWord + " debug") in message.content:
        start = time.process_time()
        await message.reply(idName + " is currently on release " + release)
        aimessage = aiclient.messages.create(
                model="claude-3-haiku-20240307",
                max_tokens=250,
                temperature=0.5,
                system=identity,
                messages=[
                    {
                        "role": "user",
                        "content": "Can you introduce yourself?",
                    }
                ]
            )
        await message.reply(aimessage.content)
        end = time.process_time()
        totalTime = end - start
        await message.reply("Took about " + str(totalTime * 100) + " seconds to send message to Discord")
        return

    if wakeWord in message.content:
        print(message.content)
        print("Generating Anthropic message...")
        aimessage = aiclient.messages.create(
                # Change the model here
                model="claude-3-haiku-20240307",
                # Get longer or shorter responses
                max_tokens=250,
                # Change how creative the bot is
                temperature=0.5,
                # Change the personality with the variables above
                system=identity,
                messages=[
                    {
                        "role": "user",
                        "content": message.content,
                    }
                ]
            )
        print(aimessage)
        # Verify that your bot might have realistically said that
        aiverification = aiclient.messages.create(
                model="claude-3-haiku-20240307",
                max_tokens=50,
                temperature=0.0,
                system=("Do you think " + idName + " sent the following message? Respond with only True or False, don't say anything else." + identity + allowedTopics + "If any of the following rules are broken, return False: " + restrictions),
                messages=[
                    {
                        "role": "user",
                        "content": aimessage.content
                    }
                ]
        )
        print(aiverification.content)
        if str(aiverification.content) == "[TextBlock(text='True', type='text')]":
            print("Raw recieved content:", aimessage.content)
            print("Unfluffing...")
            untreated = str(aimessage.content)
            treatment1 = untreated.replace('[TextBlock(text="', '')
            treatment2 = treatment1.replace('"', '')
            treatment3 = treatment2.replace(", type='text')]", '')
            treatment4 = treatment3.replace("\n", "")
            print("Fluff removed. Sending...")
            print(treatment4)
            await message.reply(treatment4)
        else:
            print("Message not related to ", idName, ". Sending notification...")
            await message.reply("Hmmm, doesn't look like " + idName + " really wants to respond to this one")
# Put your Discord bot token here. Make a Discord bot at https://discord.dev
client.run(os.getenv('DISCORD_TOKEN'))