不少人都在用微信,有沒有想要用Python來控制咱們的微信呀,哎呀,直接來點乾貨吧,咱們能夠直接在itchat上封裝
http://itchat.readthedocs.io/zh/latest/html
安裝模塊api
1 pip install wxpy 2 3 4 pip install wxpy -i "https://pypi.doubanio.com/simple " #豆瓣源
1. 生成微信對象微信
1 bot = Bot() #初始化一個對象,至關於拿到這我的的微信,後續一些操做都由它完成
2.分別找到微信對象的好友,聊天對象,朋友等併發
1 friends = bot.friends() #獲取朋友 2 chats = bot.chats() #獲取聊天對象 3 groups = bot.groups() #獲取羣號 4 maps = bot.maps() #獲取公衆號 5 6 #拿到的是列表,若是獲取對象加上角標[0] 7 #這樣很麻煩,推薦這個寫法 8 ensure_one(bot.groups().search('家人'))
3.查找某一個好友ide
1 friends = bot.friends().search('方浩')[0]
4.向好友發送消息spa
1 #發送文本 2 my_friend.send('Hello,') 3 4 #發送圖片 5 my_friend.send_image('01.jpg') 6 7 #發送視頻 8 my_friend.send_video('video.mov') 9 10 #發送文件 11 my_friend.send_file('my_file.zip') 12 13 #以動態的方式發送圖片 14 my_friend.send('@img@my_prictue.png')
5.統計微信好友的信息,好比男女比例等等線程
bot.friends().stats_text()
6.監聽羣裏某人的信息日誌
1 from wxpy import * 2 3 bot = Bot() 4 5 #定位家人羣 6 company_group = ensure_one(bot.group().search('家人微信羣')) 7 8 #定位小弟 9 di = 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 ember() #banner參數-設定歡迎內容,進入命令後展現。
7.接入圖靈機器人,讓機器人來回復好友消息code
1 from wxpy import * 2 import wxpy 3 from wxpy import * 4 bot = Bot() #初始化一個對象,就至關於拿到了這我的的微信,後續的一些操做都要用它來完成 5 # me = ensure_one(bot.search('袁勇')) 6 # me.send('哈哈') 7 all_friends = bot.friends() # 找到我全部的好友 8 tuling = Tuling(api_key='0f329eba0af742cfb34daa64f9edef8b') # 接入圖靈機器人 9 for friend in all_friends : 10 @bot.register(friend) 11 def reply_me_friend(msg): 12 tuling.do_reply(msg) 13 embed()
8.設置最大保存信息條數,而且能夠搜索視頻
1 bot = Bot() 2 # 設置歷史消息的最大保存數量爲 10000 條 3 bot.messages.max_history = 10000 4 5 # 搜索全部本身發送的,文本中包含 'wxpy' 的消息 6 bot.messages.search('wxpy', sender=bot.self)
1.得到專用logger
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.將異常消息發送到指定對象那裏
1 from wxpy import get_wechat_logger 2 3 # 得到一個專用 Logger 4 # 當不設置 `receiver` 時,會將日誌發送到隨後掃碼登錄的微信的"文件傳輸助手" 5 logger = get_wechat_logger() 6 7 #指定接受對象 8 group_reciver = ensure_one(bot.groups().search('全棧開發脫產11期')) 9 10 # 發送警告 11 logger.warning('這是一條 WARNING 等級的日誌,你收到了嗎?') 12 13 # 接收捕獲的異常 14 try: 15 1 / 0 16 except Exception as e 17 logger.exception(e)