diff --git a/.gitignore b/.gitignore index 9b62ce0..1056747 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,7 @@ share/python-wheels/ *.egg MANIFEST bot +bot.log # PyInstaller # Usually these files are written by a python script from a template diff --git a/ask_gpt.py b/ask_gpt.py index 2c2ce2b..2edb302 100644 --- a/ask_gpt.py +++ b/ask_gpt.py @@ -1,6 +1,8 @@ import aiohttp import asyncio import json +from log import getlogger +logger = getlogger() async def ask(prompt: str, api_endpoint: str, headers: dict) -> str: @@ -21,6 +23,8 @@ async def ask(prompt: str, api_endpoint: str, headers: dict) -> str: json=jsons, headers=headers, timeout=10) as response: status_code = response.status if not status_code == 200: + # print failed reason + logger.warning(str(response.reason)) max_try = max_try - 1 # wait 2s await asyncio.sleep(2) @@ -30,5 +34,6 @@ async def ask(prompt: str, api_endpoint: str, headers: dict) -> str: await session.close() return json.loads(resp)['choices'][0]['message']['content'] except Exception as e: + logger.error("Error Exception", exc_info=True) print(e) pass diff --git a/bot.py b/bot.py index 3cbd0fe..31d3db1 100644 --- a/bot.py +++ b/bot.py @@ -8,7 +8,7 @@ from nio.store.database import SqliteStore from ask_gpt import ask from send_message import send_room_message from v3 import Chatbot - +from log import getlogger """ free api_endpoint from https://github.com/ayaka14732/ChatGPTAPIFree """ @@ -16,6 +16,7 @@ api_endpoint_list = { "free": "https://chatgpt-api.shn.hk/v1/", "paid": "https://api.openai.com/v1/chat/completions" } +logger = getlogger() class Bot: @@ -62,6 +63,12 @@ class Bot: # message_callback event async def message_callback(self, room: MatrixRoom, event: RoomMessageText) -> None: + # print info to console + print( + f"Message received in room {room.display_name}\n" + f"{room.user_name(event.sender)} | {event.body}" + ) + # remove newline character from event.body event.body = re.sub("\r\n|\r|\n", " ", event.body) if self.room_id == '': @@ -81,9 +88,11 @@ class Bot: text = text.strip() await send_room_message(self.client, room_id, send_text=text) except Exception as e: + logger.error("Error", exc_info=True) print(f"Error: {e}") pass else: + logger.warning("No API_KEY provided") await send_room_message(self.client, room_id, send_text="API_KEY not provided") m = self.gpt_prog.match(event.body) @@ -95,16 +104,12 @@ class Bot: # 默认等待30s text = await asyncio.wait_for(ask(prompt, self.api_endpoint, self.headers), timeout=30) except TimeoutError: - text = "出错了,任务超时" + logger.error("timeoutException", exc_info=True) + text = "Timeout error" text = text.strip() await send_room_message(self.client, room_id, send_text=text) - # print info to console - # print( - # f"Message received in room {room.display_name}\n" - # f"{room.user_name(event.sender)} | {event.body}" - # ) # bot login async def login(self) -> None: resp = await self.client.login(password=self.password) diff --git a/log.py b/log.py new file mode 100644 index 0000000..eb66833 --- /dev/null +++ b/log.py @@ -0,0 +1,26 @@ +import logging + + +def getlogger(): + # create a custom logger + logger = logging.getLogger(__name__) + + # create handlers + warn_handler = logging.StreamHandler() + error_handler = logging.FileHandler('bot.log', mode='a') + warn_handler.setLevel(logging.WARNING) + error_handler.setLevel(logging.ERROR) + + # create formatters + warn_format = logging.Formatter('%(name)s - %(funcName)s - %(levelname)s - %(message)s') + error_format = logging.Formatter('%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s') + + # set formatter + warn_handler.setFormatter(warn_format) + error_handler.setFormatter(error_format) + + # add handlers to logger + logger.addHandler(warn_handler) + logger.addHandler(error_handler) + + return logger diff --git a/main.py b/main.py index c20d7bc..448bf1e 100644 --- a/main.py +++ b/main.py @@ -19,6 +19,7 @@ async def main(): if __name__ == "__main__": + print("matrix chatgpt bot start.....") try: loop = asyncio.get_running_loop() except RuntimeError: