Properly handle when there is no api_key
This commit is contained in:
parent
eceb2bfaaf
commit
4c6133f9a8
2 changed files with 20 additions and 12 deletions
11
bot.py
11
bot.py
|
@ -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(
|
||||
|
|
3
main.py
3
main.py
|
@ -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()
|
||||
|
||||
|
|
Loading…
Reference in a new issue