Proper handle room_id and asyncio event loop
This commit is contained in:
parent
cbc3396a2b
commit
2c0a225177
2 changed files with 14 additions and 14 deletions
12
bot.py
12
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
|
||||
|
|
16
main.py
16
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())
|
||||
|
|
Loading…
Reference in a new issue