前言
itchat是一個開源的微信個人號接口,使用python調用微信從未如此簡單。使用不到三十行的代碼,你就可以完成一個能夠處理所有信息的微信機器人。當然,該api的使用遠不止一個機器人,更多的功能等著你來發現,比如這些。該接口與公眾號接口itchatmp共享類似的操作方式,學習一次掌握兩個工具。如今微信已經成為了個人社交的很大一部分,希望這個項目能夠幫助你擴展你的個人的微信號、方便自己的生活。
安裝
sudo pip install itchat
登錄
itchat.auto_login() 這種方法將會通過微信掃描二維碼登錄,但是這種登錄的方式確實短時間的登錄,并不會保留登錄的狀態,也就是下次登錄時還是需要掃描二維碼,如果加上hotReload==True,那么就會保留登錄的狀態,至少在后面的幾次登錄過程中不會再次掃描二維碼,該參數生成一個靜態文件itchat.pkl用于存儲登錄狀態
退出及登錄完成后調用的特定的方法
這里主要使用的是灰調函數的方法,登錄完成后的方法需要賦值在 loginCallback 中退出后的方法,需要賦值在 exitCallback 中.若不設置 loginCallback 的值, 將會自動刪除二維碼圖片并清空命令行顯示.
import itchat, timedef lc(): print("Finash Login!")def ec(): print("exit")itchat.auto_login(loginCallback=lc, exitCallback=ec)time.sleep()itchat.logout() #強制退出登錄 回復消息
send
send(msg="Text Message", toUserName=None)
參數:
msg : 文本消息內容
@fil@path_to_file : 發送文件
@img@path_to_img : 發送圖片
@vid@path_to_video : 發送視頻
toUserName : 發送對象, 如果留空, 將發送給自己.
返回值
True or False
實例代碼
# coding-utf-8import itchatitchat.auto_login()itchat.send("Hello World!")ithcat.send("@fil@%s" % '/tmp/test.text')ithcat.send("@img@%s" % '/tmp/test.png')ithcat.send("@vid@%s" % '/tmp/test.mkv')send_msg
send_msg(msg='Text Message', toUserName=None),其中的的msg是要發送的文本,toUserName是發送對象, 如果留空, 將發送給自己,返回值為True或者False
實例代碼
import itchatitchat.auto_login()itchat.send_msg("hello world.")send_file
send_file(fileDir, toUserName=None) fileDir是文件路徑, 當文件不存在時, 將打印無此文件的提醒,返回值為True或者False
實例代碼
import itchatitchat.auto_login()itchat.send_file("/tmp/test.txt")send_image
send_image(fileDir, toUserName=None) 參數同上
新聞熱點
疑難解答