你們天天都在用微信,有沒有想過用python來控制咱們的微信,很少說,直接上乾貨! 這個是在 itchat上作的封裝 http://itchat.readthedocs.io/zh/latest/python
安裝模塊api
pip3 install wxpy pip install wxpy -i "https://pypi.doubanio.com/simple/" #豆瓣源
bot = Bot() #初始化一個對象,就至關於拿到了這我的的微信,後續的一些操做都要用它來完成
friends = bot.friends() # 獲取朋友 chats = bot.chats() # 獲取聊天對象
groups = bot.groups() #獲取羣聊
maps = bot.maps() #獲取公衆號
# 拿到的都是列表 若是要取到對象加上角標[0]
可是這樣很麻煩
推薦方法,這樣寫
ensure_one(bot.groups().search('全棧開發脫產11期'))
friend = bot.friends().search('袁勇')[0]
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')
bot.friends().stats_text()
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 參數 – 設定歡迎內容,將在進入命令行後展現。
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()
bot = Bot() # 設置歷史消息的最大保存數量爲 10000 條 bot.messages.max_history = 10000 # 搜索全部本身發送的,文本中包含 'wxpy' 的消息 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.將異常消息發送到指定對象那裏ide
from wxpy import get_wechat_logger # 得到一個專用 Logger # 當不設置 `receiver` 時,會將日誌發送到隨後掃碼登錄的微信的"文件傳輸助手" logger = get_wechat_logger() #指定接受對象 group_reciver = ensure_one(bot.groups().search('全棧開發脫產11期')) # 發送警告 logger.warning('這是一條 WARNING 等級的日誌,你收到了嗎?') # 接收捕獲的異常 try: 1 / 0 except Exception as e logger.exception(e)