Properly handle when there is no api_key

This commit is contained in:
hibobmaster 2023-03-10 08:29:12 +08:00
parent eceb2bfaaf
commit 4c6133f9a8
Signed by: bobmaster
GPG key ID: 316B77D7914D713C
2 changed files with 20 additions and 12 deletions

11
bot.py
View file

@ -1,4 +1,5 @@
import sys
import asyncio
import re
import os
from typing import Optional
@ -16,7 +17,7 @@ class Bot:
user_id: str,
password: str,
device_id: str,
api_key: str = "",
api_key: Optional[str] = "",
room_id: Optional[str] = '',
):
self.homeserver = homeserver
@ -37,6 +38,7 @@ class Bot:
self.gpt_prog = re.compile(r"^\s*!gpt\s*(.+)$")
self.chat_prog = re.compile(r"^\s*!chat\s*(.+)$")
# initialize chatbot
if self.api_key != '':
self.chatbot = Chatbot(api_key=self.api_key)
# message_callback event
@ -57,15 +59,20 @@ class Bot:
n = self.chat_prog.match(event.body)
if n:
if self.api_key != '':
# sending typing state
await self.client.room_typing(room_id)
prompt = n.group(1)
try:
text = self.chatbot.ask(prompt).strip()
# run synchronous function in different thread
text = await asyncio.to_thread(self.chatbot.ask, prompt)
text = text.strip()
await send_room_message(self.client, room_id, send_text=text)
except Exception as e:
print(f"Error: {e}")
pass
else:
await send_room_message(self.client, room_id, send_text="API_KEY not provided")
# print info to console
# print(

View file

@ -12,7 +12,8 @@ async def main():
password=config['password'],
device_id=config['device_id'],
room_id=config.get('room_id', ''), # provide a default value when the key does not exist
api_key=config['api_key'])
api_key=config.get('api_key', ''),
)
await matrix_bot.login()
await matrix_bot.sync_forever()