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()
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 __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_receiver(receiver=None): if isinstance(receiver, Chat): return receiver elif isinstance(receiver, Bot): return receiver.file_helper elif receiver in (None, True) or isinstance(receiver, str): return Bot(cache_path=receiver).file_helper else: raise TypeError('expected Chat, Bot, str, True or None')
def get_receiver(receiver=None): if isinstance(receiver, Chat): return receiver elif isinstance(receiver, Bot): return receiver.file_helper elif receiver is None: bot = Bot() return bot.file_helper else: raise TypeError('expected Chat, Bot or None')
def __init__(self, cache_path=True, console_qr=True,): ''' 'from wxpy import *'' only allowed at module level, so ''' import sys import logging from wxpy.api.bot import Bot from wxpy.api.chats import Chat, Chats, Friend, Group, Groups, MP, Member, User from wxpy.api.consts import ATTACHMENT, CARD, FRIENDS, MAP, NOTE, PICTURE, RECORDING, SHARING, SYSTEM, TEXT, VIDEO from wxpy.api.consts import FEMALE, MALE from wxpy.api.messages import Article, Message, Messages, SentMessage from wxpy.exceptions import ResponseError from wxpy.ext import Tuling, WeChatLoggingHandler, XiaoI, get_wechat_logger, sync_message_in_groups from wxpy.utils import BaseRequest, detect_freq_limit, dont_raise_response_error, embed, ensure_one, mutual_friends self.bot = Bot(conf.cache_path, conf.console_qr) self.bot.enable_puid() return
class WXHandler(): bot = None def login(self): self.bot = Bot(cache_path=True) # 搜索名称含有 "游否" 的男性深圳好友 def sendFriend(self,msg,friendName): my_friend = self.bot.friends().search(unicode( '文件传输助手' )) # # 发送文本给好友 # my_friend[0].send('Hello WeChat!') # print my_friend # for i in range(1,101): # my_friend[0].send('宝儿'+str(i)) # time.sleep(0.5) my_groups = bot.groups().search(unicode( 'wxpy' )) print my_groups for i in range(1,101): my_groups[0].send(i) time.sleep(0.5)
def get_receiver(receiver=None): """ 获得作为接收者的聊天对象 :param receiver: * 当为 `None`, `True` 或字符串时,将以该值作为 `cache_path` 参数启动一个新的机器人,并返回该机器人的"文件传输助手" * 当为 :class:`机器人 <Bot>` 时,将返回该机器人的"文件传输助手" * 当为 :class:`聊天对象 <Chat>` 时,将返回该聊天对象 :return: 作为接收者的聊天对象 """ from wxpy.api.chats import Chat from wxpy.api.bot import Bot if isinstance(receiver, Chat): return receiver elif isinstance(receiver, Bot): return receiver.file_helper elif receiver in (None, True) or isinstance(receiver, str): return Bot(cache_path=receiver).file_helper else: raise TypeError('expected Chat, Bot, str, True or None')
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 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.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)
'nonce_str': nonce_str, #随机字符串,都一样 #'sign':'' #签名不参与鉴权计算,只是列出来示意 } sort_dict = sorted(params.items(), key=lambda item: item[0], reverse=False) #字典排序 sort_dict.append(('app_key', app_key)) #尾部添加appkey rawtext = urlencode(sort_dict).encode() #urlencod编码 sha = hashlib.md5() sha.update(rawtext) md5text = sha.hexdigest().upper() #MD5加密计算 params['sign'] = md5text #将签名赋值到sign return params #返回请求包 bot = Bot(cache_path=True) tuling = Tuling(api_key='b55df5a8642c40058c9306eed9cef651') @bot.register([Friend]) def reply_my_friend(msg): resm = client2.sentimentClassify(msg.text) ressent = resm['items'][0]['sentiment'] respositive = resm['items'][0]['positive_prob'] ressentt = '' if ressent == 2: ressentt = '情感偏正向\n' elif ressent == 1: ressentt = '情感偏中性\n' else:
def login(self): self.bot = Bot(cache_path=True)