class WeixinBot(Thread): def __init__(self, logger, groups): super(WeixinBot, self).__init__() AutoReportGlobals.WeixinBot = self self.logger = logger self.groups = groups self._groups = [] self.path = "datas/tmps/weixin" self.cachePath = self.path + "/wx.pkl" self.qrcodePath = "datas/web/static/qr.png" self.puidPath = self.path + "/wx_puid.pkl" os.makedirs(self.path, exist_ok=True) def onQrCall(self, uuid, status, qrcode): self.logger.debug("uuid: %s, status: %s, qrcode: %s" % (uuid, status, len(qrcode))) with open(self.qrcodePath, "wb") as fp: fp.write(qrcode) self.logger.debug("save qrcode ok") def onLogin(self, *args, **kwargs): try: os.unlink(self.qrcodePath) except Exception as e: self.logger.warn(str(e)) def onLogout(self, *args, **kwargs): self._groups.clear() AutoReportGlobals.WeixinBot = None self.logger.debug("the weixin bot is logout") def sendText(self, text): try: for group in self._groups: group.send(text) except Exception as e: self.logger.warn(str(e)) return -1 return 1 def sendImage(self, image): try: if not os.path.isfile(image): self.logger.warn("%s 不是文件或不存在" % image) return -1 for group in self._groups: group.send_image(image) except Exception as e: self.logger.warn(str(e)) return -1 return 1 def sendImages(self, images): try: for image in images: if not os.path.isfile(image): self.logger.warn("%s 不是文件或不存在" % image) return -1 self.sendImage(image) except Exception as e: self.logger.warn(str(e)) return -1 return 1 def dealWithMMS(self, group, results): ver, eid, _, whichs = results[0] whichs = [w for w in whichs.split(",") if w != ""] self.logger.debug("ver:{0}, eid:{1},whichs:{2}".format(ver, eid, whichs)) # print(AutoReportGlobals.EmailIds) emailInfo = AutoReportGlobals.EmailIds.get(eid) if not emailInfo: return group.send("未找到该缓存 id: {0}".format(eid)) subject = emailInfo.get("subject") # 获取主题 dataDir = emailInfo.get("dataDir") # 获取数据目录 peoples = emailInfo.get("formalSend") # 获取正式发送人 if ver == "日报发送": self.logger.debug("eid:{0}, subject:{1}, dataDir:{2}, peoples:{3}, whichs:{4}".format(eid, subject, dataDir, peoples, whichs)) result = sendMms(subject, dataDir, peoples, whichs, "") group.send("日报控制-" + ("成功" if result == 1 else "失败")) del AutoReportGlobals.EmailIds[eid] # 删除 def run(self): self.bot = Bot( cache_path=self.cachePath, # 会话缓存路径 # console_qr=True, # 终端中显示二维码需要pillow qr_path=self.qrcodePath, # 二维码保存路径 qr_callback=self.onQrCall, # 二维码回调函数 login_callback=self.onLogin, # 登录成功回调函数 logout_callback=self.onLogout # 退出时回调函数 ) # 图灵机器人 tuling = Tuling(api_key="11212cbfcbdd532351ebd13118e768e1") # puid 是 wxpy 特有的聊天对象/用户ID # 居右唯一性 self.bot.enable_puid(self.puidPath) # 启用聊天对象的puid属性 groups = self.bot.groups(update=True) self.logger.debug("groups len: %s" % (len(groups))) count = 0 for g in self.groups: group = groups.search(g) if not group: count += 1 self.logger.warn("无法找到所监控的群") continue group = group[0] self._groups.append(group) self.logger.debug("find monitor group") # 机器人回复 @self.bot.register(group) def replay(msg): if not msg.is_at: return # 如果没有被at则忽略 # 彩信日报命令解析 # print(msg.text) results = MMSPATTERN.findall(msg.text) # print(results) if results and len(results) >= 1: # 发现控制命令 self.dealWithMMS(group, results) return # 机器人业务 tuling.do_reply(msg) # 使用图灵机器人回复 if count == len(self.groups): # 如果计数器和所监控的群个数相同 return self.bot.logout() # 自己的群 try: mygroup = groups.search("开发交流")[0] @self.bot.register(mygroup) def rMygroup(msg): tuling.do_reply(msg) # 使用图灵机器人回复 except:pass # 阻塞当前线程 self.bot.join()
class ServerController(object): def __init__(self, init=False): #初始化机器人 self.bot = Bot(init) self.bot.enable_puid("wxpy_puid.pkl") self.friend_manager = friends.FriendManager() self.common = function.CommonFn() #存储所有朋友 self.friends = [] #获取朋友列表 self._get_friend() def _get_friend(self): friends = self.bot.friends() friendpUid = set() friendInfo = [] for friend in friends: #判断重复的puid if friend.puid in friendpUid: continue friendpUid.add(friend.puid) tmpFriends = self.bot.friends().search(puid=friend.puid) for tmpFriend in tmpFriends: #打印所有对象集合 #self.common.prn_obj(tmpFriend) friendInfo.append({ "user_name": tmpFriend.raw["UserName"], "nick_name": tmpFriend.raw["NickName"], "puid": tmpFriend.puid, "remark_name": tmpFriend.raw["RemarkName"] }) self.friends.append(tmpFriend) self.friend_manager.saveFriends(friendInfo) def start(self): print("【" + self.bot.self.raw["NickName"] + "】登录成功") listen(self.bot, self.friends) self.bot.join() def replay(self): @self.bot.register() def print_others(msg): print(msg) @self.bot.register(self.friends) def reply_my_friend(msg): if msg.type != "Text": return "暂时支持文本格式的" #连接斗鱼数据查询 douyuSer = douyuServer.DouyuServer(msg) #根据roomID号爬取斗鱼直播情况 return douyuSer.liveDataByRoomId() @self.bot.register(msg_types="Friends") def auto_accept_friends(msg): if msg.text == "top": new_friend = msg.card.accept() #更新朋友列表 self._get_friend() new_friend.send( '您好,已经接受好友请求了\n访问 https://github.com/Topthinking/wxPython 查看更多' )
class ServerController(object): def __init__(self, init=False): # 初始化机器人 self.bot = Bot(init) self.bot.enable_puid("wxpy_puid.pkl") self.common = function.CommonFn() self.userdbser = userDb.User() self.textmsg = TextMsgHandle.TextMsg() # 存储所有朋友 self.friends = [] # 获取朋友列表 self._get_friend() def _get_friend(self): friends = self.bot.friends() # 遍历所有好友,进行存储和更新好友信息 friendpuid = set() for friend in friends: # 判断重复的puid if friend.puid in friendpuid: continue friendpuid.add(friend.puid) tmp_friends = self.bot.friends().search(puid=friend.puid) for tmp_friend in tmp_friends: # 机器人自己不加入 if tmp_friend.raw["UserName"] == self.bot.self.raw["UserName"]: continue # 刷新当前数据库好友信息 self._actionUserInfo(tmp_friend) def start(self): print("【" + self.bot.self.raw["NickName"] + "】登录成功") listen(self.bot, self.friends) self.bot.join() def replay(self): @self.bot.register() def print_others(msg): print(msg) @self.bot.register(self.friends) def reply_my_friend(msg): # 添加好友的提示 if msg.type == "Note": return '' if msg.type != "Text": return "暂时支持文本格式的" # 发送的文本信息 if msg.type == "Text": self.textmsg.start(msg) @self.bot.register(msg_types="Friends") def auto_accept_friends(msg): if "top" in msg.text.lower(): new_friend = msg.card.accept() # 对添加的用户进行保存 self._actionUserInfo(new_friend) new_friend.send( '您好,已经接受好友请求了\n访问 https://github.com/Topthinking/wxPython 查看更多' ) def _actionUserInfo(self, friend): """ 添加用户 nick_name,user_name,puid,add_time 更新用户 nick_name,user_name,puid,update_time,id """ curTime = int(time.mktime(datetime.datetime.now().timetuple())) # 判定该添加的朋友之前是否存在备注 if friend.raw["RemarkName"] == '': # 添加新的朋友到数据库 param = (friend.raw["NickName"], friend.raw["UserName"], friend.puid, curTime) remarkName = self.userdbser.insertUserGetInertId(param) self.bot.core.set_alias(userName=friend.raw["UserName"], alias=remarkName) else: # 更新 # 1.先查询是否存在该用户 存在就更新 否则就添加 param = (friend.raw["RemarkName"], ) info = self.userdbser.isExistUser(param) if info is None: # 添加新的朋友到数据库 param = (friend.raw["NickName"], friend.raw["UserName"], friend.puid, curTime) remarkName = self.userdbser.insertUserGetInertId(param) self.bot.core.set_alias(userName=friend.raw["UserName"], alias=remarkName) else: param = (friend.raw["NickName"], friend.raw["UserName"], friend.puid, curTime, friend.raw["RemarkName"]) self.userdbser.updateUserInfo(param) self.friends.append(friend)