下載整個文檔
安裝對應微信版本
src/Wechat-V2.7.1.82.exe
修改src/test.py
from WechatPCAPI import WechatPCAPI
import time
msg = {
"num":0,
"receive_wechat_id":'', #接收消息微信ID
"remark_name":"", #接收消息微信ID 備注
"str":""
}
# 接收消息的回調函數,可自行定義
def on_message(message):
msg_data = message["data"]
if "wx_id" in msg_data.keys():
if msg_data['wx_id'] == msg["receive_wechat_id"]:
msg["remark_name"] = msg_data['remark_name']
print("您正在與{}對話".format(msg["remark_name"]))
elif "msg" in msg_data.keys():
if "from_wxid" in msg_data.keys():
if msg_data["from_wxid"] == msg["receive_wechat_id"] and msg["str"] != "":
if msg_data["msg"] != msg["str"]:
msg["num"] += 1
if msg["num"] == 0:
print("【So Sad T_T 】今天{}沒有找您!".format(msg["remark_name"], msg["num"]))
else:
print("今天{}一共給您發送了【{}】條信息!".format(msg["remark_name"], msg["num"]))
print("【新信息】{}給您發消息啦!!!".format(msg["remark_name"]))
print("時間:{}".format(msg_data['time']))
print("內容:{}".format(msg_data["msg"]))
print("請輸入回復內容:\n")
with open('zhlmsg.txt', 'a+') as f: # 設置文件對象
f.write(msg["remark_name"]+" "+msg_data['time']+"\n")
f.write(msg_data["msg"]+"\n")
else:
with open('zhlmsg.txt', 'a+') as f: # 設置文件對象
f.write("您自己 "+msg_data['time']+"\n")
f.write(msg_data["msg"]+"\n")
else:
print("=========================================================")
print("您收到的是其他人的信息:\n【{}】\n".format(msg_data["msg"][0:50]))
if len(msg_data['msg'])>50:
print("對方發送的消息很長,請到微信進行查看!\n")
print("=========================================================")
if msg["num"] == 0:
print("【So Sad T_T 】今天{}沒有找您!".format(msg["remark_name"], msg["num"]))
else:
print("今天{}一共給您發送了【{}】條信息!".format(msg["remark_name"], msg["num"]))
print("【輸入 T 退出聊天】您可以繼續與【{}】聊天:\n".format(msg["remark_name"]))
else:
pass
def main():
# 初始化wx實例
wx_inst = WechatPCAPI(on_message=on_message)
# 啟動微信 目前僅支持微信V2.7.1.82
wx_inst.start_wechat(block=True)
# 等待登陸成功,此時需要人為掃碼登錄微信
while not wx_inst.get_myself():
time.sleep(5)
# 登錄成功了
#print(wx_inst.get_myself())
# 以下嘗試發送各類消息給文件傳輸助手,可以換成任何人的wx_id
while True:
if msg["remark_name"] != "":
msg["str"] = input("【輸入 T 退出聊天】請輸入您要發送給【{}】的信息:\n".format(msg["remark_name"]))
if msg["str"] == "T" or msg["str"] == "t": break
wx_inst.send_text(to_user=msg["receive_wechat_id"], msg=msg["str"])
if msg["num"] == 0:
print("【So Sad T_T 】今天{}沒有找您!".format(msg["remark_name"], msg["num"]))
else:
print("今天{}一共給您發送了【{}】條信息!".format(msg["remark_name"], msg["num"]))
time.sleep(10)
# 更新所有好友信息,數據會通過上面的回調函數返回
#wx_inst.update_frinds()
if __name__ == '__main__':
main()
運行
python test.py
到此,您可以與指定對象愉快的聊天了~
與其他用戶在線聊天的思路:
- receive_wechat_id 改為 receive_wechat_ids ,存放您想對話的用戶wechat ID 和 用戶姓名
- 增加聊天對象選擇,去掉默認聊天對象,選擇后可開始聊天或切換與其他用戶聊天
- 增加判斷接收到的信息來源是否 在receive_wechat_ids里
3.1 如果是,則增加選擇是否立即回復該用戶,若輸入的關鍵字不是立即回復則與當前用戶繼續聊天
3.2 如果不是,則讓用戶選擇是否添加當前發送信息的用戶到 receive_wechat_ids 列表,若輸入的關鍵詞不是添加則與當前用戶繼續聊天
若用戶選擇添加則讓用戶選擇是否立即回復當前發送信息的用戶,同3.1處理 - 可以選擇發送圖片,鏈接等,具體參考源碼,不過個人感覺比較麻煩,可以通過判斷 輸入文字開頭是否是系統盤或HTTP讓系統自動識別發送文字還是圖片/鏈接,而不需要用戶選擇發送圖片,鏈接。
PS: 為什么搞這個東西?
上班時聊天不用打開微信啊。還可以捕獲重要人的信息。而且他撤回的信息也可以看到(除非不是文字了)。