Proper handle room_id and asyncio event loop

This commit is contained in:
hibobmaster 2023-03-10 00:21:12 +08:00
parent cbc3396a2b
commit 2c0a225177
No known key found for this signature in database
GPG Key ID: 316B77D7914D713C
2 changed files with 14 additions and 14 deletions

12
bot.py
View File

@ -41,24 +41,28 @@ class Bot:
# message_callback event # message_callback event
async def message_callback(self, room: MatrixRoom, event: RoomMessageText) -> None: async def message_callback(self, room: MatrixRoom, event: RoomMessageText) -> None:
if self.room_id == '':
room_id = room.room_id
else:
room_id = self.room_id
# chatgpt # chatgpt
m = self.gpt_prog.match(event.body) m = self.gpt_prog.match(event.body)
if m: if m:
# sending typing state # sending typing state
await self.client.room_typing(self.room_id) await self.client.room_typing(room_id)
prompt = m.group(1) prompt = m.group(1)
text = await ask(prompt) text = await ask(prompt)
text = text.strip() text = text.strip()
await send_room_message(self.client, self.room_id, send_text=text) await send_room_message(self.client, room_id, send_text=text)
n = self.chat_prog.match(event.body) n = self.chat_prog.match(event.body)
if n: if n:
# sending typing state # sending typing state
await self.client.room_typing(self.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() text = self.chatbot.ask(prompt).strip()
await send_room_message(self.client, self.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

16
main.py
View File

@ -2,7 +2,6 @@
import json import json
import asyncio import asyncio
from bot import Bot from bot import Bot
import sys
async def main(): async def main():
@ -12,7 +11,7 @@ async def main():
user_id=config['user_id'], user_id=config['user_id'],
password=config['password'], password=config['password'],
device_id=config['device_id'], device_id=config['device_id'],
room_id=config['room_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['api_key'])
await matrix_bot.login() await matrix_bot.login()
await matrix_bot.sync_forever() await matrix_bot.sync_forever()
@ -20,11 +19,8 @@ async def main():
if __name__ == "__main__": if __name__ == "__main__":
try: try:
loop = asyncio.get_event_loop() loop = asyncio.get_running_loop()
task = loop.create_task(main()) except RuntimeError:
loop.run_until_complete(task) loop = asyncio.new_event_loop()
except KeyboardInterrupt: asyncio.set_event_loop(loop)
loop.close() asyncio.run(main())
sys.exit(0)
# asyncio.get_event_loop().run_until_complete(main())