def Run_ByThread(self, nSleep=0.1): try: #创建微信线程 self.thrd_Replay = threading.Thread(target=itchat.run) self.thrd_Replay.setDaemon(False) self.thrd_Replay.start() #创建消息队列 self.isRuning = True self.Init_MQ(bStart=True) #线程循环 while self.isRuning: try: #运行(监测, 用于线程内部) self.Run_Monitor() #命令监测--共享内存方式 if (self.useCmdMMap): self.Run_Monitor_Cmd_ByMMP() time.sleep(nSleep) except: myDebug.Error("Err:: Run_Monitor... ") except: myDebug.Error("Err:: Run_ByThread... Restart...") myDebug.Print('Thread is exiting...')
def OnHandleMsg_ByThread(self): try: #线程循环 while self.isRuning: try: #循环所有缓存进行处理 for x in self.usrMsgs_Buffer: bNeedSend = False time = x.get("timeLimit", "") if (time == "" and myData_Trans.Is_Numberic(time)): bNeedSend = True else: if (type(time) != datetime.datetime): time = myData_Trans.Tran_ToDatetime(time) time_N = datetime.datetime.now() if (time_N >= time): bNeedSend = True #消息发送 if (bNeedSend == False): continue x['timeLimit'] = "" self.OnHandleMsg(x, "") self.usrMsgs_Buffer.remove(x) # 延时 self.OnHandleMsg_ByThread_sleep(0.5) except: myDebug.Error("Err:: Run_OnHandleMsg_ByThread... ") except: myDebug.Error("Err:: Run_OnHandleMsg_ByThread... Restart...") myDebug.Print('Thread Run_OnHandleMsg_ByThread is exiting...')
def Get_User(self, usrID="", usrName=""): if (usrID[0:1] == "@"): pUsers = itchat.search_friends(userName=usrID) if (pUsers != None and len(pUsers) == 1): return pUsers[0] #统配查询所有 if (usrID != ""): pUsers = itchat.search_friends(name=usrID) if (pUsers != None and len(pUsers) == 1): return pUsers[0] if (usrName != ""): pUsers = itchat.search_friends(name=usrName) if (pUsers != None and len(pUsers) == 1): return pUsers[0] myDebug.Error("用户未找到::", usrID, usrName) return self.usrDefault
def Get_User_group(self, roupID="测试", groupName=""): if (roupID[0:2] == "@@"): pUsers = itchat.search_chatrooms(userName=roupID) if (pUsers != None and len(pUsers) == 1): return pUsers[0] #统配查询所有 if (roupID != ""): pUsers = itchat.search_chatrooms(name=roupID) if (pUsers != None and len(pUsers) == 1): return pUsers[0] if (groupName != ""): pUsers = itchat.search_chatrooms(name=groupName) if (pUsers != None and len(pUsers) == 1): return pUsers[0] myDebug.Error("用户群未找到::", roupID, groupName) return self.usrDefault
def _OnHandle_Iot_CmdsState_Monitorthread(self): # 循环所有执行中命令 try: # 延时2秒 time.sleep(2) #线程循环 while self.isRuning: try: # Iot命令状态校检-所有执行中 self._checkIot_CmdsState_doing() # 延时2秒 time.sleep(2) except: myDebug.Error( "Err:: Run_OnHandle_Iot_CmdsState_Monitor_ByThread... " ) except: myDebug.Error( "Err:: Run_OnHandle_Iot_CmdsState_Monitor_ByThread... Restart..." ) myDebug.Print( 'Thread Run_OnHandle_Iot_CmdsState_Monitor_ByThread is exiting...')
def query(self, checkTime=True, nReturn=0, parms=None): #组装参数 lstSets = self.paramsSet[self.type] time_s = int(myData_Trans.Tran_ToDatetime_str(None, "%S")) dtNow = myData_Trans.Tran_ToDatetime_str(None, "%Y-%m-%d %H:%M") #dtNow = "2020-06-29 14:00" #返回组 nNum = nReturn nResult = 0 lstReturn = [] #聚宽Stock接口查询 dtStart = dtNow + myData.iif(time_s < 10, F":0{time_s}", F":{time_s}") for x in lstSets: _values = self.pSource.getPrice(security=x.stockInfo.source_code, frequency='1m', start_date=dtStart, end_date=dtNow + ":59") if (len(_values) < 1): continue #转换数据 dataInfo = {'setInfo': x, "values": _values, "time": dtStart} qd = self.newData_ByInfo(dataInfo, checkTime) if (qd == None): continue #数据处理 try: if (nReturn <= 0): pDatas = self.setData(qd) if (pDatas != None): nResult += 1 else: if (nNum > 0): lstReturn.append(qd) nNum = nNum - 1 except Exception as e: myDebug.Error(str(e)) pass if (nReturn > 0): return lstReturn if (nResult > 0): print("") return True
def thrdDataSwap(self): nSleep = 0.5 sumSleep = 0 while (True): try: if (self.isSender): # 交换文件夹变化监测 lstData = self.SwapData_In(self.stepSwaps) # 触发变化事件 if (len(lstData) > 0): self.funChange(lstData) time.sleep(nSleep) sumSleep += nSleep # 保存输出 if (sumSleep > 1): sumSleep = 0 self.SwapData_OutFile() except Exception as ex: myDebug.Error(str(ex)) time.sleep(nSleep) pass
def query(self, checkTime = True, nReturn = 0, parms = None): #新浪Stock接口查询 host="http://hq.sinajs.cn/list=" strParams = "" if(parms != None): if(parms.get('queryIDs', None) != None): strParams = parms['queryIDs'] if(strParams == ""): strParams = self.params res = "" if(strParams != ""): print("\n查询ID列表:", strParams) url = host + strParams req = urllib.request.Request(url) res_data = urllib.request.urlopen(req) res = res_data.read().decode(encoding = "gbk") #返回组 nNum = nReturn lstReturn = [] if(res == ""): return lstReturn #解析所有返回数据 lines = res.split('\n') for line in lines: #数据处理 try: dataQuote = self.newData_ByInfo(line, checkTime) if(dataQuote == None): continue lstReturn.append(dataQuote) self.notifyListeners(dataQuote) except Exception as e: myDebug.Error(str(e)) pass return lstReturn
pMQ_Sender = myMQ_Rabbit.myMQ_Rabbit(True) pMQ_Sender.Init_Queue(nameMQ, True) gol._Set_Value('zxcMQ_Wx_Sender', pMQ_Sender, True) errStr = "创建消息队列失败." #测试 #users = ['茶叶一主号', '老婆'] #pAPI = myWeixin_Cmd.myAPI_Weixin_Cmd() #for i in range(0, 15): # for x in users: # strMsg = "Hello " + x # pAPI.get(x, strMsg) # time.sleep(1) #print() except: myDebug.Error(errStr) exit() # 创建新线程 pWeb = myWeb.myWeb("0.0.0.0", 8666) pWeb.add_API(myWeb.myAPI, '/test') pWeb.add_API(myWeb.myAPI_p, '/test1/<param>') myAPI_WeChat.add_APIs(pWeb) if (useCmdMMap): pWeb.add_API(myWeixin_Cmd.myAPI_Weixin_Cmd_ByMMP, '/zxcAPI/weixin/<user>/<text>/<type>') else: if (useMQ): pWeb.add_API(myWeixin_Cmd.myAPI_Weixin_Cmd_ByMQ, '/zxcAPI/weixin/<user>/<text>/<type>')
def Send_Msg(self, usrID, usrName="", msgInfo="", typeMsg="TEXT", typeUser=0): #用户检测(@开头为用户名,filehelper,其他需要检索实际用户名) userName = usrName if (usrID == None): usrID = "" if (userName != "filehelper"): if (typeUser == 0): pUser = self.Get_User(usrID, usrName) else: pUser = self.Get_User_group(usrID, usrName) userName = pUser['UserName'] if (userName == ""): return #发送消息 typeMsg = typeMsg.upper() if (typeMsg == "TEXT"): itchat.send('%s' % (msgInfo), userName) elif (typeMsg == "IMAGE"): itchat.send_image(msgInfo, userName) if (os.path.exists(msgInfo) == False): myDebug.Error("No this Image" + msgInfo + ".") elif (typeMsg == "FILE"): itchat.send_file(msgInfo, userName) if (os.path.exists(msgInfo) == False): myDebug.Error("No this File" + msgInfo + ".") elif (typeMsg == "VIDEO"): itchat.send_video(msgInfo, userName) if (os.path.exists(msgInfo) == False): myDebug.Error("No this File" + msgInfo + ".") elif (typeMsg == "CARD1"): #未实现 Content = "<?xml version=\"1.0\"?>\n<msg bigheadimgurl=\"http://wx.qlogo.cn/mmhead/ver_1/UuYfjibTFM2RFQsy5hvdojN8qeSqghGeONUBib34ucEWpztQOM18xFicVYK02lfNYLFdiaYZww71H6oDgiaBPhVm9vCgXXB1bP9XoPgE8jOibJcko/0\" smallheadimgurl=\"http://wx.qlogo.cn/mmhead/ver_1/UuYfjibTFM2RFQsy5hvdojN8qeSqghGeONUBib34ucEWpztQOM18xFicVYK02lfNYLFdiaYZww71H6oDgiaBPhVm9vCgXXB1bP9XoPgE8jOibJcko/132\" username=\"v1_cd9b652b5b54d225963c03833cef2f27e2a1e7b9b55f5659ac9210eb315cca20@stranger\" nickname=\"MlNA\" shortpy=\"MLNA\" alias=\"\" imagestatus=\"3\" scene=\"17\" province=\"广东\" city=\"广州\" sign=\"\" sex=\"2\" certflag=\"0\" certinfo=\"\" brandIconUrl=\"\" brandHomeUrl=\"\" brandSubscriptConfigUrl=\"\" brandFlags=\"0\" regionCode=\"CN_Guangdong_Guangzhou\" antispamticket=\"v2_2ced7b6604ee323f392d80574d0de3db9f4b52048d9bb0a3c231dc36f9285c02212ad1a52bcf0968b17bde1e4d8c167a153b52d5b9ff638a1cdf560d5f9d5e1a014792f12a7a6189768f049d47ca18ebb66e0bc34578bef58ce3602817a355f07c891384ee03a11f5639f39ba61ccac48bdaeaf0e3ebf06b707af8c6328d3de5834a7a89f03601ae0bc8fb5d0e8216acd0d50b8bd8e3fac6c9dad59253b829f74688d6fa701259f7ded3a108304cd7cd@stranger\" />\n" itchat.send_raw_msg(42, Content, userName) ''' MsgType: 42 FromUserName: 发送方ID ToUserName: 接收方ID Content: <?xml version="1.0"?> <msg bigheadimgurl="" smallheadimgurl="" username="" nickname="" shortpy="" alias="" imagestatus="3" scene="17" province="" city="" sign="" sex="1" certflag="0" certinfo="" brandIconUrl="" brandHomeUrl="" brandSubscriptConfigUrl="" brandFlags="0" regionCode="" /> RecommendInfo: { "UserName": "******", # ID "Province": "xxx", "City": "xxx", "Scene": 17, "QQNum": 0, "Content": "", "Alias": "xxx", # 微信号 "OpCode": 0, "Signature": "", "Ticket": "", "Sex": 0, # 1:男, 2:女 "NickName": "xxx", # 昵称 "AttrStatus": 4293221, "VerifyFlag": 0 } ''' elif (typeMsg == "SHARING1"): #未实现 Content = '<?xml version="1.0"?>\n<msg>\n\t<appmsg appid="" sdkver="0">\n\t\t<title>【生活·吃·01】叹茶,一盅两件!曾经,我们插肩而过。10年后的重逢,才发现,你是这样的广式早茶!</title>\n\t\t<des>为名忙,为利忙,忙里偷闲,饮杯茶去;劳心苦,劳力苦,苦中作乐,拿壶酒来。</des>\n\t\t<username />\n\t\t<action>view</action>\n\t\t<type>5</type>\n\t\t<showtype>0</showtype>\n\t\t<content />\n\t\t<url>http://mp.weixin.qq.com/s?__biz=MzAxMDQ3MTk4Nw==&mid=2247483741&idx=1&sn=8fb62dd901ca3f1eb1a89566af3abb53&chksm=9b4e9e01ac391717ed0c9d726f7a66d2d7ce1e84aa052995997cabf21fb6db96040a60747062&mpshare=1&scene=1&srcid=&sharer_sharetime=1575551329214&sharer_shareid=d369241c24472101fffbbbe1df71790e#rd</url>\n\t\t<lowurl />\n\t\t<dataurl />\n\t\t<lowdataurl />\n\t\t<contentattr>0</contentattr>\n\t\t<streamvideo>\n\t\t\t<streamvideourl />\n\t\t\t<streamvideototaltime>0</streamvideototaltime>\n\t\t\t<streamvideotitle />\n\t\t\t<streamvideowording />\n\t\t\t<streamvideoweburl />\n\t\t\t<streamvideothumburl />\n\t\t\t<streamvideoaduxinfo />\n\t\t\t<streamvideopublishid />\n\t\t</streamvideo>\n\t\t<canvasPageItem>\n\t\t\t<canvasPageXml><![CDATA[]]></canvasPageXml>\n\t\t</canvasPageItem>\n\t\t<appattach>\n\t\t\t<attachid />\n\t\t\t<cdnthumburl>305d0201000456305402010002044a17792502033d11fe020432f516d202045de90173042f6175706170706d73675f303961666430663738306163343663375f313537353535313334363837375f3236343734320204010400030201000400</cdnthumburl>\n\t\t\t<cdnthumbmd5>36cca8f5a144a3ef508a2d041b17237e</cdnthumbmd5>\n\t\t\t<cdnthumblength>32522</cdnthumblength>\n\t\t\t<cdnthumbheight>120</cdnthumbheight>\n\t\t\t<cdnthumbwidth>120</cdnthumbwidth>\n\t\t\t<cdnthumbaeskey>a8ff2b1290888ee1aa0653469b609ab8</cdnthumbaeskey>\n\t\t\t<aeskey>a8ff2b1290888ee1aa0653469b609ab8</aeskey>\n\t\t\t<encryver>1</encryver>\n\t\t\t<fileext />\n\t\t\t<islargefilemsg>0</islargefilemsg>\n\t\t</appattach>\n\t\t<extinfo />\n\t\t<androidsource>3</androidsource>\n\t\t<sourceusername></sourceusername>\n\t\t<sourcedisplayname>简易生活号</sourcedisplayname>\n\t\t<commenturl />\n\t\t<thumburl />\n\t\t<mediatagname />\n\t\t<messageaction><![CDATA[]]></messageaction>\n\t\t<messageext><![CDATA[]]></messageext>\n\t\t<emoticongift>\n\t\t\t<packageflag>0</packageflag>\n\t\t\t<packageid />\n\t\t</emoticongift>\n\t\t<emoticonshared>\n\t\t\t<packageflag>0</packageflag>\n\t\t\t<packageid />\n\t\t</emoticonshared>\n\t\t<designershared>\n\t\t\t<designeruin>0</designeruin>\n\t\t\t<designername>null</designername>\n\t\t\t<designerrediretcturl>null</designerrediretcturl>\n\t\t</designershared>\n\t\t<emotionpageshared>\n\t\t\t<tid>0</tid>\n\t\t\t<title>null</title>\n\t\t\t<desc>null</desc>\n\t\t\t<iconUrl>null</iconUrl>\n\t\t\t<secondUrl>null</secondUrl>\n\t\t\t<pageType>0</pageType>\n\t\t</emotionpageshared>\n\t\t<webviewshared>\n\t\t\t<shareUrlOriginal>http://mp.weixin.qq.com/s?__biz=MzAxMDQ3MTk4Nw==&mid=2247483741&idx=1&sn=8fb62dd901ca3f1eb1a89566af3abb53&chksm=9b4e9e01ac391717ed0c9d726f7a66d2d7ce1e84aa052995997cabf21fb6db96040a60747062&scene=0&xtrack=1&clicktime=1575551321&enterid=1575551321#rd</shareUrlOriginal>\n\t\t\t<shareUrlOpen>https://mp.weixin.qq.com/s?__biz=MzAxMDQ3MTk4Nw==&mid=2247483741&idx=1&sn=8fb62dd901ca3f1eb1a89566af3abb53&chksm=9b4e9e01ac391717ed0c9d726f7a66d2d7ce1e84aa052995997cabf21fb6db96040a60747062&scene=0&xtrack=1&clicktime=1575551321&enterid=1575551321&ascene=7&devicetype=android-27&version=27000934&nettype=WIFI&abtest_cookie=AAACAA%3D%3D&lang=zh_CN&exportkey=AUVRoLcGAshgpownvyOek%2Bg%3D&pass_ticket=H3X23ZwHOD05zFxqyys3F3YWCRWy5%2BRN%2B%2BFoP3lJfZW6PrO5vamVdlYXLm4XlGv2&wx_header=1</shareUrlOpen>\n\t\t\t<jsAppId />\n\t\t\t<publisherId>msg_8659705440921183578</publisherId>\n\t\t</webviewshared>\n\t\t<template_id />\n\t\t<md5>36cca8f5a144a3ef508a2d041b17237e</md5>\n\t\t<weappinfo>\n\t\t\t<username />\n\t\t\t<appid />\n\t\t\t<appservicetype>0</appservicetype>\n\t\t\t<videopageinfo>\n\t\t\t\t<thumbwidth>120</thumbwidth>\n\t\t\t\t<thumbheight>120</thumbheight>\n\t\t\t\t<fromopensdk>0</fromopensdk>\n\t\t\t</videopageinfo>\n\t\t</weappinfo>\n\t\t<statextstr />\n\t\t<mmreadershare>\n\t\t\t<itemshowtype>0</itemshowtype>\n\t\t</mmreadershare>\n\t\t<directshare>0</directshare>\n\t\t<websearch>\n\t\t\t<rec_category>0</rec_category>\n\t\t\t<channelId>0</channelId>\n\t\t</websearch>\n\t</appmsg>\n\t<fromusername></fromusername>\n\t<scene>0</scene>\n\t<appinfo>\n\t\t<version>1</version>\n\t\t<appname></appname>\n\t</appinfo>\n\t<commenturl></commenturl>\n</msg>\n' params = { "AppMsgType": 5, "Url": 'http://mp.weixin.qq.com/s?__biz=MzAxMDQ3MTk4Nw==&mid=2247483741&idx=1&sn=8fb62dd901ca3f1eb1a89566af3abb53&chksm=9b4e9e01ac391717ed0c9d726f7a66d2d7ce1e84aa052995997cabf21fb6db96040a60747062&mpshare=1&scene=1&srcid=&sharer_sharetime=1575551329214&sharer_shareid=d369241c24472101fffbbbe1df71790e#rd', "FileName": "【生活·吃·01】叹茶,一盅两件!........" } itchat.send_raw_msg(49, Content, userName, params) else: myDebug.Print("No this type.") return False return True
def Error(ex, bSave=True): pEx = myEx(ex) myDebug.Error(pEx.msg)
def query(self, checkTime=True, nReturn=0, parms=None): #组装参数 lstReturn = [] if (parms == None): return lstReturn #示例参数: {'dataFrequency': "1d", 'stockBars': 1, 'stockTag': "10003418.XSHG"} timeEnd = parms.get( 'datetimeEnd', myData_Trans.Tran_ToDatetime_str(None, "%Y-%m-%d %H:%M:%S")) timeStart = parms.get( 'datetimeStart', myData_Trans.Tran_ToDatetime_str(None, "%Y-%m-%d %H:%M:%S")) dataFrequency = parms.get( 'dataFrequency', "1d" ) # 查询周期价格信息,'1m', '5m', '15m', '30m', '60m', '120m', '1d', '1w', '1M' stockBars = parms.get('stockBars', 0) stockTag = parms.get('stockTag', None) if (stockTag == None): return lstReturn #校检标的信息 stockTemps = stockTag.split('.') stockInfo = self.setsStock._Find(code_id=stockTemps[0]) if (len(stockInfo) != 1): return lstReturn pStock = stockInfo[0] #调用接口 _values = [] _isBar = False if (stockBars <= 0): _values = self.pSource.getPrice(security=stockTag, frequency=dataFrequency, start_date=timeStart, end_date=timeEnd) else: _isBar = True _values = self.pSource.getPrice_bars(security=stockTag, count=stockBars, unit=dataFrequency, end_date=timeEnd, include_now=True) if (len(_values) < 1): return lstReturn #组装返回信息 nNum = nReturn nResult = 0 for x in range(0, len(_values)): #数据处理 try: dataInfo = { 'setInfo': pStock, "values": _values, "ind": x, "_isBar": _isBar, "dataFrequency": self.quoteTimes.get(dataFrequency, "none") } dataQuote = self.newData_ByInfo(dataInfo, checkTime) if (dataQuote == None): continue if (nNum > 0 or nReturn <= 0): lstReturn.append(dataQuote) nNum = nNum - 1 self.notifyListeners(dataQuote) except Exception as e: myDebug.Error(str(e)) pass return lstReturn