Python玩轉微信
你們天天都在用微信,有沒有想過用python來控制咱們的微信,很少說,直接上乾貨! 這個是在 itchat上作的封裝 http://itchat.readthedocs.io/zh/latest/html
安裝模塊python
pip3 install wxpy pip install wxpy -i "https://pypi.doubanio.com/simple/" #豆瓣源
1.生成微信對象
bot = Bot() #初始化一個對象,就至關於拿到了這我的的微信,後續的一些操做都要用它來完成
2.分別找到微信對象的好友,聊天對象,朋友,羣組,公衆號
friends = bot.friends() # 獲取朋友 chats = bot.chats() # 獲取聊天對象
groups = bot.groups() #獲取羣聊
maps = bot.maps() #獲取公衆號
# 拿到的都是列表 若是要取到對象加上角標[0]
可是這樣很麻煩
推薦方法,這樣寫
ensure_one(bot.groups().search('羣名'))
3. 查找某個好友
friend = bot.friends().search('好友名字')[0]
4.向好友發送消息
1 # 發送文本 2 my_friend.send('Hello, WeChat!') 3 # 發送圖片 4 my_friend.send_image('my_picture.png') 5 # 發送視頻 6 my_friend.send_video('my_video.mov') 7 # 發送文件 8 my_friend.send_file('my_file.zip') 9 # 以動態的方式發送圖片 10 my_friend.send('@img@my_picture.png')
5.統計微信好友的信息,好比男女比例,地域分配,等等
bot.friends().stats_text()
6.監聽羣裏面某我的的消息
1 from wxpy import * 2 3 bot = Bot() 4 5 # 定位公司羣 6 company_group = ensure_one(bot.groups().search('公司微信羣')) 7 8 # 定位老闆 9 boss = ensure_one(company_group.search('老闆大名')) 10 11 # 將老闆的消息轉發到文件傳輸助手 12 @bot.register(company_group) 13 def forward_boss_message(msg): 14 if msg.member == boss: 15 msg.forward(bot.file_helper, prefix='老闆發言') 16 17 # 堵塞線程 18 embed() # banner 參數 – 設定歡迎內容,將在進入命令行後展現。
7.接入圖靈機器人 讓機器人來回復好友信息
from wxpy import * import wxpy from wxpy import * bot = Bot() #初始化一個對象,就至關於拿到了這我的的微信,後續的一些操做都要用它來完成 # me = ensure_one(bot.search('本身名字')) # me.send('哈哈') all_friends = bot.friends() # 找到我全部的好友 tuling = Tuling(api_key='0f329eba0af742cfb34daa64f9edef8b') # 接入圖靈機器人 for friend in all_friends : @bot.register(friend) def reply_me_friend(msg): tuling.do_reply(msg) embed()
8.設置最大保存信息條數,而且能夠搜索
bot = Bot() # 設置歷史消息的最大保存數量爲 10000 條 bot.messages.max_history = 10000 # 搜索全部本身發送的,文本中包含 'wxpy' 的消息 bot.messages.search('wxpy', sender=bot.self)
9.用微信監控你的程序
1.得到專用loggerapi
wxpy.get_wechat_logger(receiver=None, name=None, level=30) 得到一個可向指定微信聊天對象發送日誌的 Logger 參數: receiver – 當爲 None, True 或字符串時,將以該值做爲 cache_path 參數啓動一個新的機器人,併發送到該機器人的」文件傳輸助手」 當爲 機器人 時,將發送到該機器人的」文件傳輸助手」 當爲 聊天對象 時,將發送到該聊天對象 name – Logger 名稱 level – Logger 等級,默認爲 logging.WARNING 返回: Logger
2.指定一個羣爲消息接受者微信
1 from wxpy import * 2 3 # 初始化機器人 4 bot = Bot() 5 # 找到須要接收日誌的羣 -- `ensure_one()` 用於確保找到的結果是惟一的,避免發錯地方 6 group_receiver = ensure_one(bot.groups().search('XX業務-告警通知')) 7 8 # 指定這個羣爲接收者 9 logger = get_wechat_logger(group_receiver) 10 11 logger.error('打擾你們了,但這是一條重要的錯誤日誌...') #默認的日誌級別設置爲WARNING(日誌級別等級CRITICAL > ERROR > WARNING > INFO > DEBUG)
3.將異常消息發送到指定對象那裏併發
from wxpy import get_wechat_logger # 得到一個專用 Logger # 當不設置 `receiver` 時,會將日誌發送到隨後掃碼登錄的微信的"文件傳輸助手" logger = get_wechat_logger() #指定接受對象 group_reciver = ensure_one(bot.groups().search('羣名稱')) # 發送警告 logger.warning('這是一條 WARNING 等級的日誌,你收到了嗎?') # 接收捕獲的異常 try: 1 / 0 except Exception as e logger.exception(e)