首先你需要安裝 itchat 庫。
進入 cmd,先直接
pip install itchat
就好了。
我調的是圖靈機器人的接口,可以了解一下:
圖靈機器人的注冊,圖靈機器人api擷取方式微信機器人實作過程
開啟的時候會彈出一個二維碼,微信掃描後就會登陸了。
原理是網頁版微信,那個二維碼就是你網頁版微信登陸的二維碼。
詳細的過程見代碼裡的注釋。
# -*- coding: UTF8 -*-
import itchat
import requests
# 調用圖靈的api獲得一個回複,這個參數的msg就是接收到的消息内容
def get_response(msg):
apiUrl = 'http://www.tuling123.com/openapi/api'
data={
'key' : 'bd0a1aafaafd418bbdb6aa0a40f73859',
'info' : msg,
'userid': '小愛',
}
try:
r = requests.post(apiUrl, data=data).json()
return r.get("text")
except:
return
# 開啟群消息和好友消息監控,要緊挨着你定義的方法,我定義的是tuling_reply。
@itchat.msg_register(itchat.content.TEXT,isFriendChat=True,isGroupChat=True)
def tuling_reply(msg): # 這個msg包括很多内容,我們接受到的消息是存在'Text'這個字段中
if 'ActualNickName' in msg:
# 當檢測到有人@自己時,才會在群裡回複
if msg['isAt']:
reply=get_response(msg['Text'])
else:
reply=""
else:
reply=get_response(msg['Text'])
return reply
# hotReload=Rrue就是記錄你的登陸狀态,省的每次都登陸,不想保留狀态可以去掉這個參數
itchat.auto_login(hotReload=True)
itchat.run()
喜歡的點個贊❤吧!