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

View file

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