From 774038581fe47ee6810b89b023ff16ee5215ac42 Mon Sep 17 00:00:00 2001 From: hibobmaster Date: Sun, 12 Mar 2023 23:24:05 +0800 Subject: [PATCH] Support login via access_token --- bot.py | 15 +++++++++++---- config.json.sample | 2 +- main.py | 6 ++++-- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/bot.py b/bot.py index b2987a4..3b68270 100644 --- a/bot.py +++ b/bot.py @@ -30,6 +30,7 @@ class Bot: api_key: Optional[str] = "", room_id: Optional[str] = '', bing_api_endpoint: Optional[str] = '', + access_token: Optional[str] = '', ): self.homeserver = homeserver self.user_id = user_id @@ -46,6 +47,8 @@ class Bot: ) self.client = AsyncClient(self.homeserver, user=self.user_id, device_id=self.device_id, config=self.config, store_path=self.store_path) + if access_token != '': + self.client.access_token = access_token # regular expression to match keyword [!gpt {prompt}] [!chat {prompt}] self.gpt_prog = re.compile(r"^\s*!gpt\s*(.+)$") self.chat_prog = re.compile(r"^\s*!chat\s*(.+)$") @@ -138,10 +141,14 @@ class Bot: # bot login async def login(self) -> None: - resp = await self.client.login(password=self.password) - if not isinstance(resp, LoginResponse): - print(f"Login Failed: {resp}") - sys.exit(1) + try: + resp = await self.client.login(password=self.password) + if not isinstance(resp, LoginResponse): + logger.error("Login Failed") + print(f"Login Failed: {resp}") + sys.exit(1) + except Exception as e: + logger.error("Error Exception", exc_info=True) # sync messages in the room async def sync_forever(self, timeout=30000): diff --git a/config.json.sample b/config.json.sample index d8ade41..04ea8fb 100644 --- a/config.json.sample +++ b/config.json.sample @@ -5,5 +5,5 @@ "device_id": "ECYEOKVPLG", "room_id": "!FYCmBSkCRUNvZDBaDQ:matrix.qqs.tw", "api_key": "xxxxxxxxxxxxxxxxxxxxxxxx", - "bing_api_endpoint": "" + "access_token": "xxxxxxx" } \ No newline at end of file diff --git a/main.py b/main.py index 056c131..0534555 100644 --- a/main.py +++ b/main.py @@ -9,13 +9,15 @@ async def main(): config = json.load(fp) matrix_bot = Bot(homeserver=config['homeserver'], user_id=config['user_id'], - password=config['password'], + password=config.get('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.get('api_key', ''), bing_api_endpoint=config.get('bing_api_endpoint', ''), + access_token=config.get('access_token', '') ) - await matrix_bot.login() + if config.get('access_token', '') == '': + await matrix_bot.login() await matrix_bot.sync_forever()