def main(): if len(sys.argv) < 2: show_help() sys.exit(1) if ('list' not in sys.argv) and ('send' not in sys.argv): show_help() sys.exit(1) bot = wxpy.Bot(cache_path=True, console_qr=False) bot.enable_puid() if 'list' in sys.argv: greetings = Greetings() for friend in bot.friends(): greetings.append(Greeting( name=friend.name, puid=friend.puid, )) with open('friends.json', 'w', encoding='utf8') as f: f.write(greetings.toJSON()) if 'send' in sys.argv: greetings = Greetings() with open('friends.json', encoding='utf8') as f: greetings.fromJSON(f.read()) for i in greetings: try: send_greeting(bot, i) except Exception as e: print(e) sleep(0.5) wxpy.embed()
def run(self): """Run wechat components using configs""" self._enabled_tools = [] self._working_components = [] self._setup_tools() self._setup_bot() for _t in self._enabled_tools: _comp = WechatComponents.get_wechat_util(util_type_=_t['type'], bot_=self._bot, path_=self._path, config_=_t['config']) self._working_components.append(_comp) _comp.run() self._logger.info('wechat component <{}> is activated.'.format( _t['type'])) self._logger.info('all components activated successfully.') if self._sub_thread: while not self._terminated: sleep(1) else: embed() self._logger.info('all components are stopped.')
def main(): try: with open(CONF_PATH, 'rb') as conf: robot = pickle.load(conf) robot.load_config() except: robot = Group_robot() wxpy.embed()
def WXRobot(): bot = init_bot() friends_stat(bot) #auto_repeat(bot) auto_reply(bot) # 进入Python命令行阻塞线程,让程序保持运行 wxpy.embed()
def main(): bot = Bot() #登录微信的命令 my_friend = bot.friends() #发给所有好友 @bot.register(my_friend) def SHARING_Msg(msg): if msg.type == 'Sharing': msg.reply(msg.url) else: print('waiting......') embed() #保持监听状态
def main(): bot = Bot(cache_path=True)#扫描二维码登陆微信 #issue1195 avoiding scanning again shortly my_friend = bot.friends()#回复对象为所有好友 @bot.register(my_friend) @bot.register(msg_types='Sharing')#监听好友分享的消息 why 'Sharing'expression? SHARING got errors why oh why? input distinguish problems again? def auto_reply(msg): response = requests.get(msg.url)#msg.url为分享的网址 document = PyQuery(response.text) content = document('#js_content').text() #像d11一样处理文本 result = sw.stats_text_cn(content,count=10) wechat_word = ''.join(str(i)for i in result) # seems better str this type in case causing trouble in reading return wechat_word#将结果返回给好友 embed()#d堵塞线程,保持监听
def main(): bot = Bot() #登录微信的命令 my_friend = bot.friends() #发给所有好友 @bot.register(my_friend) def SHARING_Msg(msg): if msg.type == 'Sharing': response = requests.get(msg.url) document = PyQuery(response.text) contect = document('#js_content').text() c = str(stats_word.stats_text(content, 10)) msg.reply(c) else: print('waiting......') embed() #保持监听状态 print(msg)
def login(self): # 初始化机器人,扫码登陆 bot = Bot(cache_path=True) friends = [] messageSendDao = MessageSendDao() wxpersons = messageSendDao.getPersonName(MessageSendDao.send_type_wx_user) for wxperson in wxpersons: friends.extend(bot.friends().search(wxperson)) wxgroups = messageSendDao.getPersonName(MessageSendDao.send_type_wx_group) for wxgroup in wxgroups: friends.extend(bot.groups().search(wxgroup)) friends.append(bot.file_helper) now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") print('微信开始监听咯----',now) listen(bot, token='wx-1', receivers=friends) # listen(bot, token='wx-1') wxpy.embed()
def main(): bot = Bot(cache_path=True)#扫描二维码登陆微信 #issue1195 avoiding scanning again shortly my_friend = bot.friends()#回复对象为所有好友 @bot.register(my_friend) @bot.register(msg_types='Sharing')#监听好友分享的消息 why 'Sharing'expression? SHARING got errors why oh why? input distinguish problems again? def reply_my_friend(msg): wechat = requests.get(msg.url) document = PyQuery(wechat.text) content = document('#js_content').text() # result = sw.stats_text_cn(content,count=100) # wechat_word = ''.join(str(i)for i in result) # seems better str this type in case causing trouble in reading # return list_a = sw.stats_text_cn(content,100)#接收发来的分享链接的文字,并处理成词频统计结果 msg.reply_image(chartImg(list_a)) #回复刚才保存的图片给好友 return embed()#让程序执行到这里后返回,以便于重新执行
def main(): bot = Bot() #登录微信的命令 my_friend = bot.friends() #发给所有好友 @bot.register(my_friend) def SHARING_Msg(msg): print(msg) if msg.type == 'Sharing': response = requests.get(msg.url) document = PyQuery(response.text) content = document('#js_content').text() print('line 21 ==>',stats_word.stats_text(content,10)) c=stats_word.stats_text(content,10) np_list=np.array(c) word_list=[] number_list=[] for i in range(len(np_list)): word_list+=[np_list[i][0]] number_list+=[int(np_list[i][1])] #为了能在matplotlib中显示中文,需要中文字体的支持 font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc",size=8) plt.rcdefaults() fig,ax=plt.subplots() y_pos=np.arange(len(word_list)) ax.barh(y_pos,number_list,align='center',color='green',ecolor='black') ax.set_yticks(y_pos) ax.set_yticklabels(word_list,fontproperties=font) ax.invert_yaxis() ax.set_xlabel('词频',fontproperties=font) ax.set_title('词频统计',fontproperties=font) plt.savefig("stats.png") msg.reply_image("stats.png") else: print('waiting......') embed() #保持监听状态
def run(self): bot = self.win.bot print('') # while True: @bot.register(except_self=False) def auto_reply(msg): print(msg) # 如果是群聊,但没有被 @,则不回复 print(msg.sender, msg.receiver) if msg.sender == bot.self: return bot.self.send_msg('收到消息111: {} ({})'.format( msg.text, msg.type)) if msg.sender == self.win.now_msg_friend: # if isinstance(msg.chat, self.win.now_msg_friend): # and not msg.is_at # # 回复消息内容和类型 return msg.reply_msg('收到消息: {} ({})'.format( msg.text, msg.type)) # self.exec() wxpy.embed()
def wxbot_main(): embed()
a = raw_input("press any key to continue") def send_message(content): elem = browser.find_element_by_id("editArea") elem.clear() elem.send_keys(content) elem.send_keys(Keys.RETURN) browser = webdriver.Chrome() browser.get("http://web.wechat.com/") b = raw_input("press any key to continue") send_message("oj") wxpy.embed() if True: sys.exit(0) browser.maximize_window() # 窗口最大化 browser.find_element_by_name('wd').send_keys('Apple') # 按name查找.传字符串 browser.find_element_by_id('su').click() # 按id查找.单击 time.sleep(2) actions = ActionChains(browser) # 创建事件链 element = browser.find_element_by_id('result_logo') # 找到元素 actions.move_to_element_with_offset(element, 210, 180) # 相对位置移动鼠标 actions.click() # 单击 actions.perform() # 执行以上步骤
@author: Snailclimb @description使用图灵机器人自动与指定好友聊天 """ from wxpy import Bot, Tuling, embed, ensure_one bot = Bot() my_friend = ensure_one(bot.search('郑凯')) #想和机器人聊天的好友的备注 tuling = Tuling(api_key='你申请的apikey') @bot.register(my_friend) # 使用图灵机器人自动与指定好友聊天 def reply_my_friend(msg): tuling.do_reply(msg) embed() ''' # -*- coding: utf-8 -*- """ Created on Tue Mar 13 18:55:04 2018 @author: Administrator """ from wxpy import Bot,Tuling,embed bot = Bot(cache_path=True) my_group = bot.groups().search('群聊名称')[0] # 记得把名字改成想用机器人的群 tuling = Tuling(api_key='你申请的apikey') # 一定要添加,不然实现不了 @bot.register(my_group, except_self=False) # 使用图灵机器人自动在指定群聊天 def reply_my_friend(msg):
replier = Replier(bot) # === main process === if __name__ == '__main__': @bot.register() def reply_message(msg): logger.info(msg.sender) """消息回复""" if type(msg.sender) == Group: # 所有群组消息 if msg.sender.puid in ["1f423133", "4193b4db"]: # 限定群组 logger.info("=== start ===") replier.set_group(msg.sender.puid) # 获取群信息 logger.info(msg.member.puid) if msg.type == "Note": replier.update_user_info(msg) typ, content1, content2 = replier.handle_group_msg(msg) if typ == 'text': msg.reply_msg(content1) elif typ == 'img': msg.reply_image(content1) elif typ == 'both': msg.reply_image(content1) sleep(1) msg.reply_msg(content2) # else: # todo 私聊消息 # replier.handle_solo_msg(msg) # logger.info(msg) embed() # 阻塞线程不退出'
def run(self): self.bot = wxpy.Bot(cache_path=True, console_qr=False) self.bot.messages.max_history = MAX_HISTORY self.bot.enable_puid('wxpy_puid.pkl') self.friends = self.bot.friends() self.groups = self.bot.groups() print('登录成功!') target_friend = self.friends.search(MONITOR_FRIEND_LIST)[0] # current_friend = self.friends.search(u'好友昵称', sex=FEMALE, city="好友信息中的城市")[0] print('监控对象:', target_friend) # todo # ==================================================================================== # 找到好友列表中昵称为“我说”的好友,监控聊天,打印该好友发来的文本消息 # @self.bot.register(chats=target_friend, except_self=False, msg_types=wxpy.TEXT) # def reply_friend(msg): # print('header reply_friend:', msg) # # ['_get_chat_by_user_name', '_receive_time', # # 'articles', 'bot', 'card', 'chat', 'create_time', 'file_name', 'file_size', 'forward', 'get_file', 'id', # # 'img_height', 'img_width', 'is_at', 'latency', 'location', 'media_id', 'member', 'play_length', 'raw', # # 'receive_time', 'receiver', 'reply', 'reply_file', 'reply_image', 'reply_msg', 'reply_raw_msg', # # 'reply_video', 'sender', 'text', 'type', 'url', 'voice_length'] # # # print(msg.member, type(msg.sender)) # # target_friend.send('我已经截图了,哈哈,你撤回也么有用咯!' + msg.text) # # target_friend.send_image('my_picture.png') # # target_friend.send_video('my_video.mov') # # target_friend.send_file('my_file.zip') # # target_friend.send('@img@my_picture.png') # # print('footer reply_friend:', msg) target_group = self.groups.search(MONITOR_GROUP_LIST)[0] print('监控群组:', target_group) # 监控群聊消息,打印群聊中的文本消息 @self.bot.register( chats=target_group, msg_types=wxpy.TEXT or wxpy.PICTURE or wxpy.VIDEO or wxpy.MAP or wxpy.CARD or wxpy.SHARING or wxpy.RECORDING or wxpy.ATTACHMENT or wxpy.NOTE ) def reply_group(msg): print('header reply_group:', msg) # target_group.send('我已经截图了,哈哈,你撤回也么有用咯!' + msg.text) print('footer reply_group', msg) # 处理撤回消息 @self.bot.register(except_self=False) def handle_receive_msg(msg): """ 监听消息 :param msg: 接收到的消息 :return: """ try: # 原信息数据 raw = msg.raw # raw.get('Status') == 3 个人消息 # 如果消息的状态码是4 即撤回消息 if raw.get('Status') == 4: # 如果是群消息 if isinstance(msg.chat, wxpy.api.chats.group.Group): # 获取群成员的puid puid = msg.member.puid # 获取发送者的昵称 name = msg.member.nick_name # 如果是好友消息 elif isinstance(msg.chat, wxpy.api.chats.friend.Friend): # 获取好友的puid puid = msg.chat.puid # 获取好友的昵称 name = msg.chat.nick_name # # 获取发送者的puid # puid = msg.sender.puid # # 获取发送者的名称 # name = msg.sender.raw['UserName'] else: puid = None name = None if puid: # 被撤回消息的msgid的匹配规则 msg_id_regex = re.compile('<msgid>(\d+)</msgid>') # 获取被撤回消息的msgid msg_content = msg_id_regex.findall(raw.get('Content')) if msg_content: old_msg_id = msg_content[0] else: old_msg_id = None # 获取该发送者的最后5次的消息记录 chat_msgs = self.msgs.get(puid) print(chat_msgs) # 遍历消息记录 for chat_msg in chat_msgs[::-1]: # 跳过不是被撤回的信息 if str(chat_msg.id) != old_msg_id: continue chat = chat_msg.chat # 如果被撤回的信息是文本信息 if chat_msg.type == "Text": # 如果消息长度过长 则不予处理 if len(chat_msg.text) >= 150: warning = "有人炸群咯!!!" self.bot.file_helper.send('%s %s' % (name, warning)) break # 将此消息转发出来 chat_msg.forward(chat, prefix='%s 已截图,哈哈哈,消息内容为:' % name) # 如果被撤回的是位置信息 elif chat_msg.type == "Map": # 位置信息的匹配规则 map_regex = re.compile(r'label="(.+?)"') # 获取位置信息中的位置 map = map_regex.findall(chat_msg.raw.get("OriContent"))[0] # 将位置信息发出来 msg.reply('%s 已经看到你的位置啦,啦啦啦,位置信息为:【%s】' % (name, map)) else: # 获取信息的类型 # msg_type = self.msg_types.get(chat_msg.type).encode('utf-8') msg_type = self.msg_types.get(chat_msg.type) # 将信息转发出来 chat_msg.forward(chat, prefix='%s 怀孕了也不用怕,我们一起想办法!撤回了一条%s消息,消息内容为:' % (name, msg_type)) break else: # 如果是群消息 if isinstance(msg.chat, wxpy.api.chats.group.Group): # 获取群成员的puid puid = msg.member.puid # 如果是好友消息 elif isinstance(msg.chat, wxpy.api.chats.friend.Friend): # 获取好友的puid puid = msg.chat.puid else: puid = None if puid: # 记录消息 self.msgs.setdefault(puid, []).append(msg) # 截取消息 保留最大5条记录 self.msgs[puid] = self.msgs[puid][-5:] except Exception as ex: print('error:{}'.format(ex)) # # 机器人回复 # @self.bot.register(msg_types=TEXT) # def tuling_reply_msg(msg): # print(msg) # sender_username = msg.sender.raw['UserName'] # # 输出发送信息的好友或者群聊中的人员信息 # print(sender_username) # # 判断是否和我设置的想要自动恢复到人一致如果一致调用tuling进行消息回复 # if sender_username == target_friend.raw['UserName']: # # 输出或得到的消息 # print(msg) # # # # 调用tuling机器人回复消息,并将消息赋值给message # # message = tuling.do_reply(msg) # # # 输出回复消息的内容 # # print(message) # @self.bot.register() # def tuling_reply_msg(msg): # """ # 自动回复消息 # :param msg: 接收到的信息数据 # :return: 回复文本 # """ # # do_reply会自动回复消息并返回消息文本 # tu_ling.do_reply(msg) # pass # ==================================================================================== print('正在运行...') # 阻塞进程 # self.bot.join() # 使机器人后台运行,并进入交互模式 wxpy.embed()
def handlerPush(msg): if isDebug: logging.info(msg) for plugin in plugins: try: plugin.process(msg, msg.type) except Exception as e: logging.error(e) # 自动接收好友申请 @bot.register(msg_types=FRIENDS) def auto_accept_friends(msg): new_friend = msg.card.accept() new_friend.set_remark_name("BotFrient-" + demojize(new_friend.nick_name)) new_friend.send("""[自动同意好友申请] 你好ヾ(≧▽≦*)o""") # 公众号监听 @bot.register(mps) def forward_mps(msg): msg.forward(bot.file_helper, prefix="来自" + msg.sender.name) embed(banner=""" \t\t\t\t############################ \t\t\t\t# WELCOME TO WeChatBot # \t\t\t\t############################ """)
def run(self): self.bot = Bot(cache_path=True) self.myself = self.bot.self self._signal_2.emit('成功登陆!账号:%s,可以关闭二维码了!' % self.myself.name) self.get_friendslist() self.get_chatroomslist() ########################################################## # 处理微信信息 ########################################################## # @self.bot.register(msg_types=TEXT,except_self=False) # def just_print(msg): # print(msg) # 私聊信息,文字 @self.bot.register(msg_types=TEXT,except_self=False) def get_msg(msg): fromChatroom = False print(msg) if msg.sender.name== self.bot.self.name: # 这是我发出的消息 from_Name = '我' if msg.receiver.name == '文件传输助手': to_Name = '助手' if '#' in msg.text and remote_pc == True: # 执行命令条件:1发给助手 2命令中带井号 3远控开启 do_what = msg.text.split('#')[1] # 以#分割,取第二个元素,即:具体指令。 wechat_do(do_what) # 调用微信远控的方法 else: to_Name = msg.chat.name elif msg.receiver.name == self.bot.self.name: # 这是别人发给我的 to_Name = '我' if msg.sender.name == '文件传输助手': from_Name = '助手' else: from_Name = msg.chat.name # 自动回复 if reply_busy == True: # 忙碌回复 msg_busy = myshow.lineEdit_busy.text() msg.reply('[自动回复] %s' % msg_busy) if reply_robot == True: # 机器人回复 myshow.tuling.do_reply(msg) message = from_Name + '→' + to_Name + ':' + msg.text send_time = msg.create_time self._signal_1.emit(fromChatroom, message, send_time) # 信号焕发,连接 write_log # 私聊信息,图片、视频等 @self.bot.register(msg_types=[PICTURE, RECORDING, ATTACHMENT, VIDEO]) def download_files(msg): print(msg) fromChatroom = False if msg.sender.name == self.bot.self.name: # 这是我发出的消息 from_Name = '我' if msg.receiver.name == '文件传输助手': to_Name = '助手' else: to_Name = msg.chat.name elif msg.receiver.name == self.bot.self.name: # 这是别人发给我的 to_Name = '我' if msg.sender.name == '文件传输助手': from_Name = '助手' else: from_Name = msg.chat.name # 自动回复 if reply_busy == True: msg_busy = myshow.lineEdit_busy.text() msg.reply('[自动回复] %s' % msg_busy) if reply_robot == True: # 机器人回复 myshow.tuling.do_reply(msg) # 新建接收文件夹 downloadDir = '接收文件' if not os.path.exists(downloadDir): # 目录如果不存在 os.makedirs(downloadDir) workPath = os.getcwd() # 当前程序工作的路径 downloadPath = os.path.join(workPath, downloadDir) # 接收文件的路径 os.chdir(downloadPath) # 改变当前工作目录 msg.get_file(msg.file_name) # 下载文件 os.chdir(workPath) message = from_Name + '→' + to_Name + ':' + '[文件: %s]' % msg.file_name send_time = msg.create_time self._signal_1.emit(fromChatroom, message, send_time) # 信号焕发,连接 write_log # 群聊信息,@我的文字信息 @self.bot.register(chats=Group,msg_types=TEXT) def get_msg_at(msg): print(msg) if msg.is_at: print('333333') print(msg.member.name) if reply_busy == True: msg_busy = myshow.lineEdit_busy.text() msg.reply(u'@%s\u2005[自动回复] %s' % (msg.member.nick_name, msg_busy)) if reply_robot == True: myshow.tuling.do_reply(msg) from_Name = msg.member.name chatroom_NickName = msg.chat.name fromChatroom = True message = '[' + chatroom_NickName + '] ' + from_Name + ' :' + msg.text send_time = msg.create_time self._signal_1.emit(fromChatroom, message, send_time) # 信号焕发,连接 write_log embed() # 堵塞线程
import stats_word import json import requests from pyquery import PyQuery from wxpy import Bot, Message, embed, SHARING bot = Bot() #扫码登录微信 my_friend = bot.friends() #定义好友变量 @bot.register() #接收share类信息 def auto_reply(msg): if Message.type == 'sharing': r = requests.get(msg.url) document = PyQuery(r.text) content = document('#js_content').text() reply = stats_word.stats_text(content, count=100) return reply #将词频自动发给好友 embed() #保持监听状态
import wxpy as pp # 实例化,并登录微信 bot = pp.Bot(cache_path=True) # 调用图灵机器人API tuling = pp.Tuling(api_key='4a0488cdce684468b95591a641f0971d') @bot.register() def auto_reply(msg): tuling.do_reply(msg) pp.embed()
#统计文章汉语词频 output = stats_word.stats_text_cn(content, 100) output_str = str(output) return output_str #导入wxpy 模块 from wxpy import Bot, Message, embed bot = Bot() #初始化机器人,扫码登录 my_friend = bot.friends().search('somebody')[0] #搜索名称含有‘somebody’的微信好友 my_friend.send('Hello, please send me a message.') #给微信好友发送信息 @bot.register(my_friend) #装饰器,匹配好友,空默认匹配所有 def auto_reply(msg): '''This function aims to gain the url from weichat message and to reply words frequency of Sharing Chinese articels.''' if msg.type == 'Sharing': #只处理类型为Sharing的信息 url = msg.url re_friend = data_cn(url) msg.reply(re_friend) #给好友返回结果 else: print("Your friend doesn't send a message") embed() #进入Python 命令,让程序保持运行
#!/usr/bin/env python3 """简单地在两个微信群中同步消息 """ import wxpy wechat = wxpy.Bot() groups = wechat.groups() G1 = wxpy.ensure_one(groups.search("生物信息学群")) G2 = wxpy.ensure_one(groups.search("生物信息学2群")) F_groups = [G1, G2] @wechat.register(F_groups, except_self=False) def sync_my_groups(msg): wxpy.sync_message_in_groups(msg, F_groups) wxpy.embed(banner="堵塞微信,直至手动结束")
import wxpy # 导入wxpy模块,from wxpy import *,会报错函数不可用,方法1:*改成以下代码的所用到的所有函数,方法2:在以下所用到的wxpy函数前加上wxpy. bot = wxpy.Bot() # 扫码登陆微信 my_friend = bot.friends().search('云如', city='抚州')[0] #搜索朋友 my_friend.send('请给我分享一篇文章可好') #请求朋友发送消息 SHARING = 'Sharing' #消息类型 @bot.register(my_friend, SHARING) #装饰器,预先注册:预先将特定聊天对象,特定类型消息,注册到对应的处理函数,实现自动回复 def print_msg(msg): import requests import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning ) #禁用安全证书,解决InsecureRequestWarning response = requests.get(msg.url) #msg.url获取朋友分享类消息的网址 from pyquery import PyQuery document = PyQuery(response.text) content = document('#js_content').text() #从网页中导出文本 from mymodule import stats_word as s results = s.stats_text_cn(content, 100) #调用函数,统计词频 r_string = ''.join(str(i) for i in results) #列表转化为字符串 print(r_string) return r_string #自动把结果回复的朋友 return=msg.reply() wxpy.embed() #堵塞线程,以保持监听状态
@bot.register(chats=[bot.self], msg_types=wxpy.TEXT, except_self=False) def regiter_text(msg): global Records if msg.text == 'end': with open(opts.outFile, 'w', encoding='utf-8') as jsonFile: json.dump(Records, jsonFile, ensure_ascii=False, indent=4, sort_keys=True) jsonFile.close() bot.logout() elif msg.text == 'save': with open(opts.outFile, 'w', encoding='utf-8') as jsonFile: json.dump(Records, jsonFile, ensure_ascii=False, indent=4, sort_keys=True) print('Saved records') elif msg.text == 'reload': if opts.inFile: with open(opts.inFile, 'r', encoding='utf-8') as jsonFile: Records = json.load(jsonFile) print('Reloaded records') else: print('No input file, cannot reload') wxpy.embed() #bot.join()
import requests import pyquery from mymodule.stats_word import stats_text # 从 模块中(mymodule是包,stats_word是模块) 导入 函数stats_text # 第一步:引入wxpy模块,监听好友消息,获取SHARING类型消息的网页链接 import wxpy # 导入wxpy模块 bot = wxpy.Bot() # 初始化机器人,会出现一个二维码,扫码登录即可 my_friend = bot.friends().search('熊小腰')[ 0] # 搜索名字含有“熊小腰”的朋友(如果针对所有好友,则是my_friend=bot.friends()) @bot.register(my_friend, wxpy.SHARING) # 接受好友类型为sharing的消息 def receive_mf(msg): # 参数msg为监听到的消息 r = requests.get(msg.url) # 请求sharing类型消息的网页链接 # 第二步:将获取的链接用Day11项目中的代码进行处理 document = pyquery.PyQuery(r.text) # 通过pyquery解析该网页 content = document( '#js_content').text() # '#js_content'是网页的一个标签名,这个标签中存放着文档的内容。 text = content # 将content赋值给text dict_result = stats_text(text, 100) # 把结果赋值给dict_result # 第三步:将处理结果返回给发送消息的好友 msg.reply(str(dict_result)) #str()函数将某一类型的变量或者常量转换为字符串,回复好友 # 法二是:my_friend.send(str(dict_result)) # 法三是:return str(dict_result) wxpy.embed() # 进入Python命令行,让程序保持运行
def main(): bot = Bot() my_friend = ensure_one(bot.friends().search('果果爸爸')) @bot.register(my_friend,SHARING) def auto_reply(msg): response = requests.get(msg.url) #msg.url为分享的网址 document = PyQuery(response.text) content = document('#js_content').text() contents = stats_word.stats_text_cn(content,count=10) result=np.array(contents) word_list=[] number_list=[] for i in range(len(result)): word_list+=[result[i][0]] number_list+=[int(result[i][1])] #绘图: #为了能在matplotlib中显示中文,需要中文字体的支持 font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=8) plt.rcdefaults() fig, ax = plt.subplots() y_pos = np.arange(len(word_list)) ax.barh(y_pos, number_list, align='center', color='green', ecolor='black') ax.set_yticks(y_pos) ax.set_yticklabels(word_list, fontproperties=font) ax.invert_yaxis() ax.set_xlabel('词频', fontproperties=font) ax.set_title('好友分享文章词频统计', fontproperties=font) plt.savefig("stats.png") #保存图片 msg.reply_image("stats.png") #回复图片 embed() #堵塞线程,保持监听状态
# step 2. 保存TEXT类型消息的txt文件 if msg.type == 'Text': _default_text_register(msg) elif msg.type == 'Sharing': _default_share_register(msg) # elif msg.type == "Picture": # _default_picture_register(msg) # 自动接受新的好友请求 @bot.register(msg_types=FRIENDS) def auto_accept_friends(msg): # 接受好友请求 new_friend = msg.card.accept() # 向新的好友发送消息 new_friend.send('本项目为自动领取美团、饿了么红包,自动手气最佳 \n' '项目已开源\n' 'https://github.com/chengzijian/ai-hongbao\n' '感谢以下项目的支持\n' 'https://github.com/game-helper/hongbao\n' 'https://github.com/youfou/wxpy\n' '查看使用说明请扣 H\n' '查询绑定的手机号码请扣 Q\n' '使用前请先绑定手机号'.decode("UTF-8")) # 堵塞线程,以保持监听状态 embed()
def forward_manager_message(msg): if msg.member == manager: msg.forward(bot.file_helper, prefix='部门领导发言') if __name__ == '__main__': os.chdir(r'.\PythonLearn\src\spider\weixin') # 指定工作路径 if not os.path.exists('info/' + bot.self.name): # 判断在‘weixin’文件下是否存在文件夹‘info’和机器人账号自身名称的文件夹 filepath = os.getcwd() # 显示当前python脚本工作路径 os.makedirs(filepath + '/info/' + bot.self.name + '/images') # 可生成多层递规目录,在工作路径下创建文件夹‘info’、机器人账号自身名称的文件夹和‘images’文件夹 myfriends = bot.core.get_friends(update=True)[0:] # 获取微信好友列表 myfriends_list = [] for myfriend in myfriends: item = {} item['NickName'] = myfriend['NickName'] item['HeadImgUrl'] = myfriend['HeadImgUrl'] item['Sex'] = sex_dict[str(myfriend['Sex'])] item['Province'] = myfriend['Province'] item['City'] = myfriend['City'] item['Signature'] = myfriend['Signature'] item['UserName'] = myfriend['UserName'] myfriends_list.append(item) print(item) bot.file_helper.send('Hello from wxpy!') # 向文件传输助手发送消息 save_data(myfriends_list) download_images(myfriends_list) embed() # 进入 Python 命令行、让程序保持运行 # bot.join() # 或者仅仅堵塞线程