11# -*- coding: utf-8 -*-
22
3- import asyncio
4- import base64
53import os
6- import platform
7- import signal
84import sys
95import time
6+ import asyncio
7+ import signal
8+ import base64
9+ import yaml
1010import traceback
11- from dataclasses import dataclass
11+ import websockets
12+ import platform
13+ import httpx
1214from datetime import datetime
13- from typing import Any , Dict , List , Optional , Set , Union
15+ from typing import Optional , List , Dict , Any , Union , Set
1416
15- import httpx
16- import websockets
17- import yaml
18- from pymixin import log , utils
19- from pymixin . mixin_ws_api import MessageView , MixinWSApi
17+ from pymixin . mixin_ws_api import MixinWSApi , MessageView
18+ from pymixin import utils
19+ from pymixin import log
20+
21+ from dataclasses import dataclass
2022
2123logger = log .get_logger (__name__ )
2224logger .addHandler (log .handler )
@@ -142,13 +144,21 @@ def __init__(self, config_file):
142144 # openai_api_key
143145 self .bots = []
144146 self .standby_bots = []
147+ self ._paused = False
148+
149+ @property
150+ def paused (self ):
151+ return self ._paused
152+
153+ @paused .setter
154+ def paused (self , value ):
155+ self ._paused = value
145156
146157 async def init (self ):
147158 asyncio .create_task (self .handle_questions ())
148159
149160 if self .chatgpt_accounts :
150161 from playwright .async_api import async_playwright
151-
152162 from .chatgpt_browser import ChatGPTBot
153163 PLAY = await async_playwright ().start ()
154164 for account in self .chatgpt_accounts :
@@ -173,9 +183,14 @@ async def init(self):
173183
174184 async def handle_signal (self , signum ):
175185 logger .info ("+++++++handle signal: %s" , signum )
186+ for bot in self .bots :
187+ logger .info ("++close bot: %s" , bot )
188+ await bot .close ()
176189 loop = asyncio .get_running_loop ()
177- for task in asyncio .all_tasks (loop ):
178- task .cancel ()
190+ loop .remove_signal_handler (signal .SIGINT )
191+ loop .remove_signal_handler (signal .SIGTERM )
192+ sys .exit (0 )
193+ # os.kill(os.getpid(), signal.SIGINT)
179194
180195 def choose_bot (self , user_id ):
181196 bots = []
@@ -247,32 +262,26 @@ async def send_message_to_chat_gpt2(self, conversation_id, user_id, message):
247262
248263 async def handle_questions (self ):
249264 while True :
250- try :
251- await asyncio .sleep (15.0 )
252- handled_question = []
253- saved_questions = self .saved_questions .copy ()
254- for user_id , question in saved_questions .items ():
255- try :
256- logger .info ("++++++++handle question: %s" , question .data )
257- if await self .send_message_to_chat_gpt2 (question .conversation_id , question .user_id , question .data ):
258- handled_question .append (user_id )
259- except Exception as e :
260- logger .info ("%s" , str (e ))
261- continue
262- for question in handled_question :
263- del self .saved_questions [question ]
264- except asyncio .exceptions .CancelledError :
265- logger .info ("++++handle_questions received CancelledError exception, exit.." )
266- return
265+ await asyncio .sleep (15.0 )
266+ handled_question = []
267+ saved_questions = self .saved_questions .copy ()
268+ for user_id , question in saved_questions .items ():
269+ try :
270+ logger .info ("++++++++handle question: %s" , question .data )
271+ if await self .send_message_to_chat_gpt2 (question .conversation_id , question .user_id , question .data ):
272+ handled_question .append (user_id )
273+ except Exception as e :
274+ logger .info ("%s" , str (e ))
275+ continue
276+ for question in handled_question :
277+ del self .saved_questions [question ]
267278
268279 def save_question (self , conversation_id , user_id , data ):
269280 self .saved_questions [user_id ] = SavedQuestion (conversation_id , user_id , data )
270281
271- async def handle_message (self , conversation_id , user_id , message ):
282+ async def handle_user_message (self , conversation_id , user_id , message ):
272283 try :
273284 await self .send_message_to_chat_gpt (conversation_id , user_id , message )
274- except asyncio .exceptions .CancelledError :
275- logger .info ("++++handle_group_message received CancelledError, exit..." )
276285 except Exception as e :
277286 logger .exception (e )
278287 if self .developer_user_id :
@@ -305,10 +314,7 @@ async def get_web_result(self, message: str):
305314 querys .append (f"\n Instructions: Using the provided web search results, write a comprehensive reply to the given prompt. Make sure to cite results using [[number](URL)] notation after the reference. If the provided search results refer to multiple subjects with the same name, write separate answers for each subject.\n Prompt: { prompt } " )
306315 return "\n " .join (querys )
307316 async def handle_group_message (self , conversation_id , user_id , data ):
308- try :
309- await self .send_message_to_chat_gpt2 (conversation_id , user_id , data )
310- except asyncio .exceptions .CancelledError :
311- logger .info ("++++handle_group_message received CancelledError, exit..." )
317+ await self .send_message_to_chat_gpt2 (conversation_id , user_id , data )
312318
313319 async def on_message (self , id : str , action : str , msg : Optional [MessageView ]):
314320 if action not in ["ACKNOWLEDGE_MESSAGE_RECEIPT" , "CREATE_MESSAGE" , "LIST_PENDING_MESSAGES" ]:
@@ -358,19 +364,31 @@ async def on_message(self, id: str, action: str, msg: Optional[MessageView]):
358364 pass
359365
360366 if utils .unique_conversation_id (msg .user_id , self .client_id ) == msg .conversation_id :
361- asyncio .create_task (self .handle_message (msg .conversation_id , msg .user_id , data ))
367+ asyncio .create_task (self .handle_user_message (msg .conversation_id , msg .user_id , data ))
362368 else :
363369 asyncio .create_task (self .handle_group_message (msg .conversation_id , msg .user_id , data ))
364370
365371 async def run (self ):
366372 try :
367- await super ().run ()
373+ while not self .paused :
374+ try :
375+ await super ().run ()
376+ except websockets .exceptions .ConnectionClosedError as e :
377+ logger .exception (e )
378+ await asyncio .sleep (3.0 )
379+ self .ws = None
380+ #asyncio.exceptions.TimeoutError
381+ except Exception as e :
382+ #
383+ logger .exception (e )
384+ await asyncio .sleep (3.0 )
385+ self .ws = None
368386 except asyncio .CancelledError :
369387 if self .ws :
370388 await self .ws .close ()
371389 if self .web_client :
372390 await self .web_client .aclose ()
373- logger .info ("mixin websocket received CancelledError, exit... " )
391+ logger .info ("mixin websocket was cancelled! " )
374392
375393 async def close (self ):
376394 for bot in self .bots :
@@ -390,11 +408,7 @@ async def start(config_file):
390408 asyncio .create_task (bot .run ())
391409 print ('started' )
392410 while not bot .paused :
393- try :
394- await asyncio .sleep (1.0 )
395- except asyncio .CancelledError :
396- logger .info ("+++start received CancelledError, exit..." )
397- return
411+ await asyncio .sleep (1.0 )
398412
399413async def stop ():
400414 global bot
0 commit comments