set timeout for coroutine job

This commit is contained in:
hibobmaster 2023-03-10 19:19:49 +08:00
parent fab7a36bc4
commit 87c560a30e
Signed by: bobmaster
GPG key ID: 316B77D7914D713C

24
bot.py
View file

@ -69,15 +69,6 @@ class Bot:
else: else:
room_id = self.room_id room_id = self.room_id
# chatgpt # chatgpt
m = self.gpt_prog.match(event.body)
if m:
# sending typing state
await self.client.room_typing(room_id)
prompt = m.group(1)
text = await ask(prompt, self.api_endpoint, self.headers)
text = text.strip()
await send_room_message(self.client, room_id, send_text=text)
n = self.chat_prog.match(event.body) n = self.chat_prog.match(event.body)
if n: if n:
if self.api_key != '': if self.api_key != '':
@ -95,12 +86,25 @@ class Bot:
else: else:
await send_room_message(self.client, room_id, send_text="API_KEY not provided") await send_room_message(self.client, room_id, send_text="API_KEY not provided")
m = self.gpt_prog.match(event.body)
if m:
# sending typing state
await self.client.room_typing(room_id)
prompt = m.group(1)
try:
# 默认等待30s
text = await asyncio.wait_for(ask(prompt, self.api_endpoint, self.headers), timeout=30)
except TimeoutError:
text = "出错了,任务超时"
text = text.strip()
await send_room_message(self.client, room_id, send_text=text)
# 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"
# f"{room.user_name(event.sender)} | {event.body}" # f"{room.user_name(event.sender)} | {event.body}"
# ) # )
# bot login # bot login
async def login(self) -> None: async def login(self) -> None:
resp = await self.client.login(password=self.password) resp = await self.client.login(password=self.password)