add basic logging function

This commit is contained in:
hibobmaster 2023-03-10 21:43:18 +08:00
parent 87c560a30e
commit 69dd8ff81c
Signed by: bobmaster
GPG key ID: 316B77D7914D713C
5 changed files with 45 additions and 7 deletions

1
.gitignore vendored
View file

@ -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

View file

@ -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

19
bot.py
View file

@ -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)

26
log.py Normal file
View file

@ -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

View file

@ -19,6 +19,7 @@ async def main():
if __name__ == "__main__":
print("matrix chatgpt bot start.....")
try:
loop = asyncio.get_running_loop()
except RuntimeError: