1+ import os
12import sys
23import json
34import uuid
45import asyncio
56import base64
67import logging
8+ import signal
79from typing import Optional
810
911logging .basicConfig (level = logging .INFO , format = '%(asctime)s %(levelname)s %(module)s %(lineno)d %(message)s' )
1012logger = logging .getLogger (__name__ )
1113
1214from pymixin .mixin_ws_api import MixinWSApi , MessageView , Category , MessageStatus
1315
16+ print (os .getpid ())
17+
1418bot_config = None
1519
1620with open (sys .argv [1 ]) as f :
@@ -22,6 +26,25 @@ class MixinBot(MixinWSApi):
2226 def __init__ (self ):
2327 super ().__init__ (bot_config , on_message = self .on_message )
2428
29+ def init (self ):
30+ loop = asyncio .get_running_loop ()
31+ loop .add_signal_handler (signal .SIGINT , lambda : asyncio .create_task (self .handle_signal (signal .SIGINT )))
32+ loop .add_signal_handler (signal .SIGTERM , lambda : asyncio .create_task (self .handle_signal (signal .SIGTERM )))
33+
34+ async def handle_signal (self , signum ):
35+ logger .info ("+++++++handle signal: %s" , signum )
36+ loop = asyncio .get_running_loop ()
37+ for task in asyncio .all_tasks (loop ):
38+ task .cancel ()
39+
40+ async def run (self ):
41+ self .init ()
42+ try :
43+ await super ().run ()
44+ except asyncio .CancelledError :
45+ await self .ws .close ()
46+ print ('CancelledError' )
47+
2548 async def on_message (self , id : str , action : str , msg : Optional [MessageView ]) -> None :
2649 logger .info ("on_message: %s %s %s" , id , action , msg )
2750
@@ -62,6 +85,7 @@ async def on_message(self, id: str, action: str, msg: Optional[MessageView]) ->
6285bot = MixinBot ()
6386
6487async def start ():
88+ bot .init ()
6589 await bot .run ()
6690
6791if __name__ == '__main__' :
0 commit comments