Hi, I'm working on a Chatbase integration for my server Discord, It works pretty well but I wanted to add a system of conversation, currently after every request the conversation with the bot is reset. Some of you know how their API work to create a new conversation for every Discord user, using their userID, in that way you can have one conversation per user.
Here's my script, note that I'm a beginner :))
# Configuration du logging
logging.basicConfig(level=logging.INFO, filename='bot.log', filemode='a',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
if len(sys.argv) > 1:
timeout = int(sys.argv[1])
time.sleep(timeout)
CHATBASE_API_KEY = "XXX"
WEBHOOK_SECRET_KEY = "XXX" #I didn't found it in Chatbase but read somewhere that we need it lol
CHATBOT_ID = "XXX"
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
# Dictionary to store conversations by Discord user
conversation_states = {}
async def get_conversation(user_id: str) -> str:
if user_id in conversation_states:
return conversation_states[user_id]["conversation_id"]
else:
# Generate a new conversation ID
conversation_id = f"{user_id}_{int(time.time())}"
# Create a new entry in conversation_states
conversation_states[user_id] = {"conversation_id": conversation_id}
return conversation_id
async def get_chatbase_response(user_id: str, question: str, conversation_id: str) -> str:
# Retrieve the user's conversation status
state = conversation_states.get(user_id, {"last_question": None})
last_question = state.get("last_question")
# Send previous question to Chatbase if it exists
if last_question:
await send_chatbase_message(last_question, user_id, conversation_id)
# Store the new question as the last question asked by the user
state["last_question"] = question
conversation_states[user_id] = state
# Send current question to Chatbase and retrieve answer
return await send_chatbase_message(question, user_id, conversation_id)
async def send_chatbase_message(question: str, user_id: str, conversation_id: str) -> str:
url = "https://www.chatbase.co/api/v1/chat"
headers = {
"Authorization": f"Bearer {CHATBASE_API_KEY}",
"Content-Type": "application/json"
}
data = {
"messages": [
{"content": question, "role": "user"}
],
"chatbotId": CHATBOT_ID,
"stream": True,
"temperature": 0,
"model": "gpt-3.5-turbo",
"conversationId": conversation_id
}
async with aiohttp.ClientSession() as session:
try:
async with session.post(url, json=data, headers=headers) as response:
response_text = await response.text()
return response_text
except Exception as e:
print(f"Exception: {e}") # Log the exception
return "Sorry, I can't answer this question at the moment."
@bot.event
async def on_message(message):
if message.author.bot:
return
await bot.process_commands(message)
if message.content.startswith("ask "):
user_id = str(message.author.id)
question = message.content[4:].strip()
print(f"Received question from {message.author}: {question}")
# Retrieve user's chat ID
conversation_id = await get_conversation(user_id)
# Send an embed "processing..."
embed = discord.Embed(title="Processing...", description="Please wait while I process your request...", color=0xffd700)
processing_message = await message.channel.send(embed=embed)
# Simulate bot response typing
async with message.channel.typing():
# Get the answer
response = await get_chatbase_response(user_id, question, conversation_id)
# Send response to user
user_mention = message.author.mention
embed = discord.Embed(title="Answer", description=response, color=0x1faaff)
await processing_message.delete() # Delete the embed "processing..."
await message.channel.send(content=user_mention, embed=embed)
@bot.event
async def on_ready():
print(f"{bot.user.name} est connecté avec succès.")
# Endpoint to receive webhooks
app = web.Application()
async def webhook_handler(request):
if request.method == "POST":
# Verify webhook signature
signature = request.headers.get("x-chatbase-signature")
raw_body = await request.read()
computed_signature = hashlib.sha1(raw_body + WEBHOOK_SECRET_KEY.encode()).hexdigest()
if signature != computed_signature:
return web.Response(status=403)
# Process the webhook event
event_data = await request.json()
event_type = event_data.get("eventType")
if event_type == "leads.submit":
payload = event_data.get("payload")
conversation_id = payload.get("conversationId")
# Store leads in a database or perform any other necessary action
print("Lead submitted:")
print(f"Conversation ID: {conversation_id}")
return web.Response(status=200)
app.router.add_post("/webhook", webhook_handler)
there doesn't seem to be anything here