這個微信接口還挺有意思的,隨便玩了下,可以備份消息,群發(fā)消息好多,不過貌似有些功能還有些bug,寫了一段群發(fā)消息的代碼,可以做個群聊機(jī)器人:
import itchat
itchat.auto_login(hotReload=True)
chatrooms = itchat.get_chatrooms(update=True, contactOnly=True)
chatroom_ids = [c['UserName']for c in chatrooms]
print('正在監(jiān)測的群聊:', len(chatrooms), '個')
print(' '.join([item['NickName'] for item in chatrooms]))
print(chatroom_ids)
@itchat.msg_register(itchat.content.TEXT, isGroupChat=True)
def msg_reply(msg):
default = '倪幸福啊!'
if msg['FromUserName'] in chatroom_ids:
return default
else:
return None
itchat.run()
實(shí)現(xiàn)了一個自動回復(fù)特定群消息的功能,不過如果連上圖靈機(jī)器人就可以更智能一點(diǎn)了,懶得搞了,還有msg那一長串誰看下去啊- -還有很多功能以后再玩吧。
參考:http://www.lxweimin.com/p/7aeadca0c9bd
實(shí)現(xiàn)爬好友圖片功能:
import PIL.Image as Image
itchat.auto_login(hotReload=True)
friends = itchat.get_friends(update=True)[0:]
user = friends[0]['UserName']
num = 0
for i in friends:
img = itchat.get_head_img(userName=i['UserName'])
fileImage = open('F:/test/myenviron' + "/" + str(num) + ".jpg", 'wb')
fileImage.write(img)
fileImage.close()
num += 1
ls = os.listdir('F:/test/myenviron')
each_size = int(math.sqrt(float(640*640)/len(ls)))
lines = int(640/each_size)
image = Image.new('RGBA',(640,640))
x = 0
y = 0
for i in range(0,len(ls)+1):
try:
img = Image.open('F:/test/myenviron' + "/" + str(i) + ".jpg")
except IOError:
print("Error")
else:
img = img.resize((each_size, each_size), Image.ANTIALIAS)
image.paste(img, (x*each_size, y*each_size))
x += 1
if x == lines:
x = 0
y += 1
image = image.convert('RGB')
image.save('F:/test/myenviron' + "/" + 'all.jpg')
itchat.send_image('F:/test/myenviron' + "/" + 'all.jpg', 'filehelper')
參考:http://www.lxweimin.com/p/cd4e4c0080ec
注意JPGA變?yōu)镽GB
——————————————————————————————————————————-
圖靈機(jī)器人
import itchat
import requests
然后定義一個向圖靈機(jī)器人發(fā)送消息并接受機(jī)器人回復(fù)的消息,并將從圖靈機(jī)器人接受到的消息return返回。
def get_response(_info):
print(_info) # 從好友發(fā)過來的消息
api_url = 'http://www.tuling123.com/openapi/api' # 圖靈機(jī)器人網(wǎng)址
data = {
'key': '485712b8079e44e1bc4af10872b08319', # 如果這個 apiKey 如不能用,那就注冊一次
'info': _info, # 這是我們從好友接收到的消息 然后轉(zhuǎn)發(fā)給圖靈機(jī)器人
'userid': 'wechat-robot', # 這里你想改什么都可以
}
r = requests.post(api_url, data=data).json() # 把data數(shù)據(jù)發(fā)
print(r.get('text')) # 機(jī)器人回復(fù)給好友的消息
return r
三、定義消息回復(fù)
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
return "【我是天才^_^】" + get_response(msg["Text"])["text"]
/這里是關(guān)閉群消息的,針對群消息可以再加一欄/
四、掃碼登錄,大功告成。
if __name__ == '__main__':
itchat.auto_login(hotReload=True) # hotReload = True, 保持在線,下次運(yùn)行代碼可自動登錄
itchat.run()
爬好友信息
import codecs
import json
from pyecharts import Bar,Pie,Map,WordCloud
# 容器類, pip有安裝的版本問題,通過wheels安裝,詳情可以搜索
from collections import Counter
import jieba.analyse
# 數(shù)據(jù)存儲方法,為了防止編碼不統(tǒng)一的情況,使用codecs來進(jìn)行打開
def saveFriends(friendsList):
outputFile = 'F:/test/myenviron/friends.json'
with codecs.open(outputFile, 'w', encoding='utf-8') as jsonFile:
# 默認(rèn)使用ascii,為了輸出中文將參數(shù)ensure_ascii設(shè)置成False
jsonFile.write(json.dumps(friendsList,ensure_ascii=False))
def getFriends(inputFile):
with codecs.open(inputFile, encoding='utf-8') as f:
friendsList = json.load(f)
return friendsList
# 繪制柱狀圖
def drawBar(name,rank):
outputFile = 'F:/test/myenviron/省份柱狀圖.image'
bar = Bar(title='省份分布柱狀圖', width=1200, height=600, title_pos='center')
bar.add(
'', # 注解label屬性
name, # 橫
rank # 縱
)
bar.show_config()
bar.render(outputFile)
# 繪制餅圖
def drawPie(name,rank):
outputFile = 'F:/test/myenviron/性別比例圖.image'
pie = Pie('性別比例圖', width=1200, height=600, title_pos='center')
pie.add(
'',
name, rank,
is_label_show = True, # 是否顯示標(biāo)簽
label_text_color = None, # 標(biāo)簽顏色
legend_orient = 'vertical', # 圖例是否垂直
legend_pos = 'left'
)
pie.render(outputFile)
# 繪制地圖
def drawMap(name,rank):
outputFile = 'F:/test/myenviron/區(qū)域分布圖.image'
map = Map(title='微信好友區(qū)域分布圖', width=1200, height=600, title_pos='center')
map.add(
'',name,rank,
maptype = 'china', # 地圖范圍
is_visualmap = True, # 是否開啟鼠標(biāo)縮放漫游等
is_label_show = True # 是否顯示地圖標(biāo)記
)
map.render(outputFile)
# 繪制個性簽名詞云
def drawWorldCloud(name,rank):
outputFile = 'F:/test/myenviron/簽名詞云.image'
cloud = WordCloud('微信好友簽名詞云圖', width=1200, height=600, title_pos='center', background_color='white')
cloud.add(
' ',name,rank,
shape='circle'
)
cloud.render(outputFile)
# 實(shí)現(xiàn)將counter數(shù)據(jù)結(jié)構(gòu)拆分成兩個list,再傳給pyecharts
def counter2list(_counter):
nameList,countList = [],[]
for counter in _counter:
nameList.append(counter[0])
countList.append(counter[1])
return nameList,countList
def dict2list(_dict):
nameList, countList = [], []
for key, value in _dict.items():
nameList.append(key)
countList.append(value)
return nameList, countList
# 利用jieba模塊提取出關(guān)鍵詞并計(jì)算其權(quán)重,利用了TF-IDF算法
def extractTag(text,tagsList):
if text:
tags = jieba.analyse.extract_tags(text)
for tag in tags:
tagsList[tag] += 1
if __name__ == '__main__':
# 性別在itchat接口獲取的數(shù)據(jù)中顯示的是0,1,2三種我們使用一個字典將其映射為男、女、其他
sexList = {'0': '其他', '1': '男', '2': '女'}
# 自動登陸
itchat.auto_login(hotReload=True)
# 利用API獲取朋友列表
friends = itchat.get_friends(update=True)
friendsList = []
for friend in friends:
# 將friends提取出有用數(shù)據(jù)并存放在字典中
item = {}
item['NickName'] = friend['NickName']
item['Sex'] = sexList[str(friend['Sex'])]
item['Province'] = friend['Province']
item['Signature'] = friend['Signature']
# 為了獲取頭像用
item['UserName'] = friend['UserName']
friendsList.append(item)
# 保存好友列表的json信息
saveFriends(friendsList)
# 讀取friends.json中的數(shù)據(jù)
inputFile = 'F:/test/myenviron/friends.json'
friendList = getFriends(inputFile)
# 需要統(tǒng)計(jì)的字段使用counter數(shù)據(jù)類型存儲
provinceCounter = Counter()
sexDict = {'男':0,'女':0,'其他':0}
signatureCounter = Counter()
for friend in friendList:
if friend['Province'] != '':
provinceCounter[friend['Province']] += 1
sexDict[friend['Sex']] += 1
extractTag(friend['Signature'],signatureCounter)
# 統(tǒng)計(jì)出排名前16的省份
provinceList, rankList = counter2list(provinceCounter.most_common(15))
# 繪制柱狀圖
drawBar(provinceList, rankList)
# 繪制地圖
drawMap(provinceList, rankList)
# 繪制男女比例餅圖
sexList, percentList = dict2list(sexDict)
drawPie(sexList, percentList)
# 繪制詞云
tagsList,rankList = counter2list(signatureCounter.most_common(200))
drawWorldCloud(tagsList, rankList)