ai-bot/bot.py

65 lines
1.6 KiB
Python
Raw Normal View History

2023-04-11 15:41:34 -04:00
#!/bin/python3.10
2023-04-11 17:44:26 -04:00
import sys
2023-04-11 15:35:23 -04:00
import os
2023-04-11 17:44:26 -04:00
import random
import re
2023-04-11 17:44:26 -04:00
2023-04-11 15:35:23 -04:00
import discord
from ollama import AsyncClient
2023-04-11 17:44:26 -04:00
from discord.ext import commands
2023-04-11 15:35:23 -04:00
from dotenv import load_dotenv
2023-04-11 17:44:26 -04:00
description = """
An example bot to showcase the discord.ext.commands extension module.
There are a number of utility commands being showcased here.
"""
2023-04-11 15:35:23 -04:00
2023-04-11 17:44:26 -04:00
load_dotenv()
client = AsyncClient()
2023-04-11 15:35:23 -04:00
2023-04-11 17:44:26 -04:00
bot = commands.Bot(
command_prefix=commands.when_mentioned_or("!"),
description=description,
intents=discord.Intents.all(),
)
2023-04-11 15:35:23 -04:00
2023-04-11 17:44:26 -04:00
@bot.event
async def on_ready():
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
2023-04-11 15:35:23 -04:00
def extract_response(input_string):
# Find the position of the closing tag
end_index = input_string.find('</think>')
if end_index == -1:
raise ValueError("Closing tag </think> not found")
# Extract the response part of the string
response = input_string[end_index + len('</think>'):].strip()
return response
2023-04-11 15:35:23 -04:00
2023-04-11 17:44:26 -04:00
@bot.event
async def on_message(message: discord.Message):
msg = ""
# Make sure we won't be replying to ourselves.
if message.author.id == bot.user.id:
return
2023-04-11 15:35:23 -04:00
2023-04-11 17:44:26 -04:00
if f"""<@{bot.user.id}>""" in message.content:
async with message.channel.typing():
messages = [
{
'role':'user',
'content': message.content
}
]
response = await client.chat('marx', messages=messages)
print(response['message']['content'])
msg = extract_response(response['message']['content'])
2023-04-11 17:44:26 -04:00
await message.channel.send(msg)
bot.run(os.environ.get("DISCORD_TOKEN"))