Chore: improve
This commit is contained in:
parent
7314517b6a
commit
09596c1990
4 changed files with 29 additions and 15 deletions
|
@ -20,7 +20,7 @@ async def ask(prompt: str, api_endpoint: str, headers: dict) -> str:
|
||||||
while max_try > 0:
|
while max_try > 0:
|
||||||
try:
|
try:
|
||||||
async with session.post(url=api_endpoint,
|
async with session.post(url=api_endpoint,
|
||||||
json=jsons, headers=headers, timeout=10) as response:
|
json=jsons, headers=headers, timeout=30) as response:
|
||||||
status_code = response.status
|
status_code = response.status
|
||||||
if not status_code == 200:
|
if not status_code == 200:
|
||||||
# print failed reason
|
# print failed reason
|
||||||
|
|
33
bot.py
33
bot.py
|
@ -44,9 +44,10 @@ class Bot:
|
||||||
self.config = AsyncClientConfig(store=SqliteStore,
|
self.config = AsyncClientConfig(store=SqliteStore,
|
||||||
store_name="bot",
|
store_name="bot",
|
||||||
store_sync_tokens=True,
|
store_sync_tokens=True,
|
||||||
|
encryption_enabled=True,
|
||||||
)
|
)
|
||||||
self.client = AsyncClient(self.homeserver, user=self.user_id, device_id=self.device_id,
|
self.client = AsyncClient(self.homeserver, user=self.user_id, device_id=self.device_id,
|
||||||
config=self.config, store_path=self.store_path)
|
config=self.config, store_path=self.store_path,)
|
||||||
if access_token != '':
|
if access_token != '':
|
||||||
self.client.access_token = access_token
|
self.client.access_token = access_token
|
||||||
# regular expression to match keyword [!gpt {prompt}] [!chat {prompt}]
|
# regular expression to match keyword [!gpt {prompt}] [!chat {prompt}]
|
||||||
|
@ -75,6 +76,17 @@ class Bot:
|
||||||
|
|
||||||
# message_callback event
|
# message_callback event
|
||||||
async def message_callback(self, room: MatrixRoom, event: RoomMessageText) -> None:
|
async def message_callback(self, room: MatrixRoom, event: RoomMessageText) -> None:
|
||||||
|
if self.room_id == '':
|
||||||
|
room_id = room.room_id
|
||||||
|
else:
|
||||||
|
# if event room id does not match the room id in config, return
|
||||||
|
if room.room_id != self.room_id:
|
||||||
|
return
|
||||||
|
room_id = self.room_id
|
||||||
|
|
||||||
|
# reply event_id
|
||||||
|
reply_to_event_id = event.event_id
|
||||||
|
|
||||||
# print info to console
|
# print info to console
|
||||||
print(
|
print(
|
||||||
f"Message received in room {room.display_name}\n"
|
f"Message received in room {room.display_name}\n"
|
||||||
|
@ -83,10 +95,6 @@ class Bot:
|
||||||
|
|
||||||
# remove newline character from event.body
|
# remove newline character from event.body
|
||||||
event.body = re.sub("\r\n|\r|\n", " ", event.body)
|
event.body = re.sub("\r\n|\r|\n", " ", event.body)
|
||||||
if self.room_id == '':
|
|
||||||
room_id = room.room_id
|
|
||||||
else:
|
|
||||||
room_id = self.room_id
|
|
||||||
|
|
||||||
# chatgpt
|
# chatgpt
|
||||||
n = self.chat_prog.match(event.body)
|
n = self.chat_prog.match(event.body)
|
||||||
|
@ -99,7 +107,8 @@ class Bot:
|
||||||
# run synchronous function in different thread
|
# run synchronous function in different thread
|
||||||
text = await asyncio.to_thread(self.chatbot.ask, prompt)
|
text = await asyncio.to_thread(self.chatbot.ask, prompt)
|
||||||
text = text.strip()
|
text = text.strip()
|
||||||
await send_room_message(self.client, room_id, send_text=text)
|
await send_room_message(self.client, room_id, send_text=text,
|
||||||
|
reply_to_event_id=reply_to_event_id)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error("Error", exc_info=True)
|
logger.error("Error", exc_info=True)
|
||||||
print(f"Error: {e}")
|
print(f"Error: {e}")
|
||||||
|
@ -114,14 +123,15 @@ class Bot:
|
||||||
await self.client.room_typing(room_id)
|
await self.client.room_typing(room_id)
|
||||||
prompt = m.group(1)
|
prompt = m.group(1)
|
||||||
try:
|
try:
|
||||||
# timeout 30s
|
# timeout 60s
|
||||||
text = await asyncio.wait_for(ask(prompt, self.chatgpt_api_endpoint, self.headers), timeout=30)
|
text = await asyncio.wait_for(ask(prompt, self.chatgpt_api_endpoint, self.headers), timeout=60)
|
||||||
except TimeoutError:
|
except TimeoutError:
|
||||||
logger.error("timeoutException", exc_info=True)
|
logger.error("timeoutException", exc_info=True)
|
||||||
text = "Timeout error"
|
text = "Timeout error"
|
||||||
|
|
||||||
text = text.strip()
|
text = text.strip()
|
||||||
await send_room_message(self.client, room_id, send_text=text)
|
await send_room_message(self.client, room_id, send_text=text,
|
||||||
|
reply_to_event_id=reply_to_event_id)
|
||||||
|
|
||||||
# bing ai
|
# bing ai
|
||||||
if self.bing_api_endpoint != '':
|
if self.bing_api_endpoint != '':
|
||||||
|
@ -131,13 +141,14 @@ class Bot:
|
||||||
await self.client.room_typing(room_id)
|
await self.client.room_typing(room_id)
|
||||||
prompt = b.group(1)
|
prompt = b.group(1)
|
||||||
try:
|
try:
|
||||||
# timeout 30s
|
# timeout 120s
|
||||||
text = await asyncio.wait_for(self.bingbot.ask_bing(prompt), timeout=120)
|
text = await asyncio.wait_for(self.bingbot.ask_bing(prompt), timeout=120)
|
||||||
except TimeoutError:
|
except TimeoutError:
|
||||||
logger.error("timeoutException", exc_info=True)
|
logger.error("timeoutException", exc_info=True)
|
||||||
text = "Timeout error"
|
text = "Timeout error"
|
||||||
text = text.strip()
|
text = text.strip()
|
||||||
await send_room_message(self.client, room_id, send_text=text)
|
await send_room_message(self.client, room_id, send_text=text,
|
||||||
|
reply_to_event_id=reply_to_event_id)
|
||||||
|
|
||||||
# bot login
|
# bot login
|
||||||
async def login(self) -> None:
|
async def login(self) -> None:
|
||||||
|
|
4
main.py
4
main.py
|
@ -9,9 +9,9 @@ async def main():
|
||||||
config = json.load(fp)
|
config = json.load(fp)
|
||||||
matrix_bot = Bot(homeserver=config['homeserver'],
|
matrix_bot = Bot(homeserver=config['homeserver'],
|
||||||
user_id=config['user_id'],
|
user_id=config['user_id'],
|
||||||
password=config.get('password', ''),
|
password=config.get('password', ''), # provide a default value when the key does not exist
|
||||||
device_id=config['device_id'],
|
device_id=config['device_id'],
|
||||||
room_id=config.get('room_id', ''), # provide a default value when the key does not exist
|
room_id=config.get('room_id', ''),
|
||||||
api_key=config.get('api_key', ''),
|
api_key=config.get('api_key', ''),
|
||||||
bing_api_endpoint=config.get('bing_api_endpoint', ''),
|
bing_api_endpoint=config.get('bing_api_endpoint', ''),
|
||||||
access_token=config.get('access_token', '')
|
access_token=config.get('access_token', '')
|
||||||
|
|
|
@ -3,10 +3,13 @@ from nio import AsyncClient
|
||||||
|
|
||||||
async def send_room_message(client: AsyncClient,
|
async def send_room_message(client: AsyncClient,
|
||||||
room_id: str,
|
room_id: str,
|
||||||
|
reply_to_event_id: str,
|
||||||
send_text: str) -> None:
|
send_text: str) -> None:
|
||||||
await client.room_send(
|
await client.room_send(
|
||||||
room_id,
|
room_id,
|
||||||
message_type="m.room.message",
|
message_type="m.room.message",
|
||||||
content={"msgtype": "m.text", "body": f"{send_text}"},
|
content={"msgtype": "m.text", "body": f"{send_text}",
|
||||||
|
"m.relates_to": {"m.in_reply_to": {"event_id": reply_to_event_id}}},
|
||||||
|
ignore_unverified_devices=True,
|
||||||
)
|
)
|
||||||
await client.room_typing(room_id, typing_state=False)
|
await client.room_typing(room_id, typing_state=False)
|
||||||
|
|
Loading…
Reference in a new issue