From 2c0a225177948fc5c5349c29f2c1949f55650ce0 Mon Sep 17 00:00:00 2001 From: hibobmaster Date: Fri, 10 Mar 2023 00:21:12 +0800 Subject: [PATCH] Proper handle room_id and asyncio event loop --- bot.py | 12 ++++++++---- main.py | 16 ++++++---------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/bot.py b/bot.py index 6e58a7d..f30c84f 100644 --- a/bot.py +++ b/bot.py @@ -41,24 +41,28 @@ class Bot: # message_callback event 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 m = self.gpt_prog.match(event.body) if m: # sending typing state - await self.client.room_typing(self.room_id) + await self.client.room_typing(room_id) prompt = m.group(1) text = await ask(prompt) 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) if n: # sending typing state - await self.client.room_typing(self.room_id) + await self.client.room_typing(room_id) prompt = n.group(1) try: 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: print(f"Error: {e}") pass diff --git a/main.py b/main.py index 5e5f0e8..d8e2c95 100644 --- a/main.py +++ b/main.py @@ -2,7 +2,6 @@ import json import asyncio from bot import Bot -import sys async def main(): @@ -12,7 +11,7 @@ async def main(): user_id=config['user_id'], password=config['password'], 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']) await matrix_bot.login() await matrix_bot.sync_forever() @@ -20,11 +19,8 @@ async def main(): if __name__ == "__main__": try: - loop = asyncio.get_event_loop() - task = loop.create_task(main()) - loop.run_until_complete(task) - except KeyboardInterrupt: - loop.close() - sys.exit(0) - - # asyncio.get_event_loop().run_until_complete(main()) + loop = asyncio.get_running_loop() + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + asyncio.run(main())