一、下載安裝itchat模塊
二、小實驗:獲取微信好友頭像信息
這需要用itchat模塊中的一個方法
itchat
.
get_friends
(
)
#獲取微信所有微信好友信息
現在我們導入itchat,打印一下,看看好友信息有哪些字段數據
import
itchat
#itchat.login()生成一個登陸二維碼,此方式每次程序運行都需要掃碼
itchat
.
auto_login
(
hotReload
=
True
)
#持續登錄,只用掃一次二維碼即可
friends
=
itchat
.
get_friends
(
)
#獲取微信所有好友信息
for
i
in
friends:
print
(i)
這里只拿出幾個常用字段說明:
UserName:微信號唯一標識符
NickName:微信名
HeadImgUrl:頭像url
RemarkName:備注
Signature:簽名
Province:省份
City:城市
從好友信息對象中獲取頭像圖片并存儲:
import
itchat
#itchat.login()生成一個登陸二維碼,此方式每次程序運行都需要掃碼
itchat
.
auto_login
(
hotReload
=
True
)
#持續登錄,只用掃一次二維碼即可
friends
=
itchat
.
get_friends
(
)
#獲取微信所有好友信息
print
(
friends
)
for
i
in
friends
:
img
=
itchat
.
get_head_img
(
userName
=
i
[
'UserName'
]
)
#獲取好友頭像
path
=
r
'C:\Users\Administrator\PycharmProjects\untitled\Test\微信好友:'
+
i
[
'RemarkName'
]
+
'.jpg'
with
open
(
path
,
'wb'
)
as
f
:
f
.
write
(
img
)
三、使用圖靈機器人實現微信自動回復
進入圖靈機器人官方網站創建機器人
記錄機器人的apikey
進入幫助中心,找到apiv2.0接入教程,里面會有詳細的對接教程及一些參數的說明
然后就可以開始通過python itchat和圖靈機器人進行對接,實現自動回復消息
import
itchat
import
requests
import
json
def
get_response
(
msg
)
:
url
=
'http://openapi.tuling123.com/openapi/api/v2'
data
=
{
"reqType"
:
0
,
"perception"
:
{
"inputText"
:
{
"text"
:
msg
}
,
"inputImage"
:
{
"url"
:
"imageUrl"
}
,
"selfInfo"
:
{
"location"
:
{
"city"
:
"北京"
,
"province"
:
"北京"
,
"street"
:
"信息路"
}
}
}
,
"userInfo"
:
{
"apiKey"
:
"圖靈機器人apikey號"
,
"userId"
:
"what"
#userID隨便填一個字符
}
}
data
=
json
.
dumps
(
data
)
#把data變成json格式
response
=
requests
.
post
(
url
,
data
=
data
)
.
json
(
)
#打印出來是個字典
#print(response['results'][0]['values']['text'])#從數據中取出機器人回復的消息文字
return
(
response
[
'results'
]
[
0
]
[
'values'
]
[
'text'
]
)
#get_response('你有什么事嗎')#模擬好友發送信息
#python3中可以使用json模塊來對json數據進行編解碼
#它包含了兩個函數:
#json.dumps()對數據進行編碼
#json.loads()對數據進行解碼
itchat
.
auto_login
(
hotReload
=
True
)
#保持登錄
@itchat
.
msg_register
(
itchat
.
content
.
TEXT
)
#裝飾器,對下面的函數添加新功能
def
auto_reply
(
message
)
:
#print(message)
only_reply_info
=
'哈哈哈,你又上當了!'
#設置指定回復消息
friend_info
=
message
[
'Text'
]
#獲取好友發送的文本信息
friend_id
=
message
[
'FromUserName'
]
#獲取好友id
reply_info
=
get_response
(
friend_info
)
#將好友信息發送給圖靈機器人
only_friend_info
=
itchat
.
search_friends
(
name
=
'微信備注名'
)
#獲取指定好友發送的消息
if
friend_id
==
only_friend_info
[
0
]
[
'UserName'
]
:
itchat
.
send
(
msg
=
only_reply_info
,
toUserName
=
friend_id
)
#規定指定聯系人回復消息
else
:
itchat
.
send
(
msg
=
reply_info
,
toUserName
=
friend_id
)
#正常機器人智能回復
if
__name__
==
"__main__"
:
itchat
.
run
(
)
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
