最近一段時間想看看能不能用萬能的python來對微信進行一些操作(比如自動搶紅包之類的...hahahaha),所以就在此記錄一下啦~~
1、安裝
sudo pip install itchat
2、登錄
itchat.auto_login()
注:itchat.auto_login()這種方法將會通過微信掃描二維碼登錄,但是這種登錄的方式確實短時間的登錄,並不會保留登錄的狀態,也就是下次登錄時還是需要掃描二維碼,如果加上hotReload==True,那么就會保留登錄的狀態,至少在后面的幾次登錄過程中不會再次掃描二維碼,該參數生成一個靜態文件itchat.pkl用於存儲登錄狀態
itchat.auto_login(hotReload=True)
3、退出登錄
主要使用的是回調函數的方法,登錄完成后的方法需要賦值在 loginCallback中退出后的方法,需要賦值在 exitCallback中.若不設置 loginCallback的值, 將會自動刪除二維碼圖片並清空命令行顯示.
import itchat,time
def lcb():
print("登錄完成!")
def ecb():
print("退出成功!")
itchat.auto_login(loginCallback=lcb,exitCallback=ecb) #源碼中規定需要用回調函數。
time.sleep(10)
itchat.logout() #強制退出登錄
4、發送消息
send()
itchat.send(msg="WANGPC的微信消息!",toUserName="filehelper") #返回值為True或Flase
實例:
或者:
send_msg
send_msg(msg='Text Message', toUserName=None),其中的的msg是要發送的文本,toUserName是發送對象, 如果留空, 將發送給自己,返回值為True或者False
實例代碼
send_file
send_file(fileDir, toUserName=None) fileDir是文件路徑, 當文件不存在時, 將打印無此文件的提醒,返回值為True或者False
實例代碼
send_image
send_image(fileDir, toUserName=None) 參數同上
實例代碼
send_video
send_video(fileDir, toUserName=None) 參數同上
實例代碼