[toc]
python wxpy 模块实现微信通知与告警
1、python wxpy的安装
# pip install wxpy -i "https://pypi.doubanio.com/simple/" # pip install wechat_sender -i "https://pypi.doubanio.com/simple/"
2、 wxpy登录后向文件助手发送一条信息
➜ test cat wechat.py #!/usr/bin/env python2.7 # -*- coding: utf-8 -*- from wxpy import * bot = Bot() bot.file_helper.send('hello world') print("ending")
3、wxpy登录后实现与好友/群聊
➜ test cat wechat_friends.py #!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import sys import time reload (sys) sys.setdefaultencoding("utf-8") # 这里要注意中文编码的问题 from wxpy import * bot = Bot() # 获取所有好友 friends = bot.friends() # 遍历输出好友名称 for friend in friends: print(friend) # 找到好友 friend = bot.friends() .search(unicode('有你'))[0] print(friend) friend.send('你在干嘛了?') # 获取所有聊天群 groups = bot.groups() # 遍历输出所有聊天群 for group in groups: print(group) # 找到目标群 # 搜索聊天群时,要确保将要搜索的群组保存在通讯录中 group = bot.groups() .search(unicode("an"))[0] i = 0 while i<= 999: group.send("This is bug !!!") i +=1 time.sleep(0.5)
4、 实现自动对消息处理
➜ test cat wechat_message.py #!/usr/bin/env python2.7 # -*- coding: utf-8 -*- from wxpy import * import sys reload (sys) sys.setdefaultencoding("utf-8") bot = Bot() # 获取好友 my_friend = bot.friends() .search(unicode('有你真好'))[0] # 搜索信息 messages = bot.messages.search(keywords='测试', sender=bot.self) for message in messages: print(message) # 发送文本 my_friend.send('hello,yangyang!') # 发送图片 my_friend.send_image('yangyang.png') # 发送视频 #my_friend.send_video('yangyang.mov') # 发磅文件 my_friend.send_file('yangyang.zip') # 以动态的方式发送图片 my_friend.send('yangyang.png') # 发送公众号 my_friend.send_raw_msg( #名片原始消息类型 raw_type=42, # 注意`ussername` 这里应为微信ID,且被发送的名片必须为自己的好友 raw_content = '<msg username="wxpy_bot" nickname="wxpy 机器人"/>' ) # 消息接收监听器 @bot.register() def print_others(msg): # 输出监听到的消息 print(msg) #回复消息 msg.reply("hello world") embed()
5、 wxpy图灵机器人
➜ test cat wechat_tulin.py #!/usr/bin/env python2.7 # -*- coding: utf-8 -*- from wxpy import * import sys import time reload (sys) sys.setdefaultencoding("utf-8") bot = Bot() # 获取好友 dear = bot.friends() .search(unicode('有你真好'))[0] # 注册获得个人的图录机器人key填入 tuling = Tuling(api_key='45a3c4xxxxxxxxx043a126a7119363d9fe') # 使用图灵机器人自动与指定好友聊天 @bot.register(dear) def reply_my_friend(msg): print(msg) tuling.do_reply(msg) embed()