功能
- 微信好友分析
- 好友省份城市分析
- 把所有好友头像合并成一张
- 打印好友信息
- 群发信息(群发助手)
- 给指定群的所有成员私发信息
- 统计好友信息生成excel并转发
用到的资源
import itchat
import requests
import re
import sys
import os
import urllib
import xlwt
import time
import matplotlib as mpl
from matplotlib import pyplot as plt
import numpy as np
import PIL.Image as Image
from os import listdir
import math
import pandas as pd
微信 python 接口 – itchat 文档https://www.bbsmax.com/A/1O5EBbO8d7/
源代码
import itchat
import requests
import re
import sys
import os
import urllib
import xlwt
import time
import matplotlib as mpl
from matplotlib import pyplot as plt
import numpy as np
import PIL.Image as Image
from os import listdir
import math
import pandas as pd
#字体设置,防止乱码
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
zhfont = mpl.font_manager.FontProperties(fname='C:\Windows\Fonts\微软雅黑\msyh.ttf', size=14)
#微信好友分析
def friend_analysis(friends):
labels = ['男', '女', '其他']
data = [0, 0, 0]
# friends[0] 是自己的信息
for friend in friends[1:]:
sex = friend["Sex"]
if sex == 1:
data[0] += 1
elif sex == 2:
data[1] += 1
else:
data[2] += 1
fig = plt.figure()
plt.pie(data, labels=labels,autopct="%.2f%%")
plt.title("微信好友分析",fontsize=18)
plt.show()
# extract the variables: NickName, Sex, City, Province, Signature
def get_features(friends):
features = []
for friend in friends:
feature = {'NickName': friend['NickName'], 'Sex': friend['Sex'], 'City': friend['City'],
'Province': friend['Province'], 'Signature': friend['Signature']}
features.append(feature)
return pd.DataFrame(features)
#好友省份城市分析
def province_analysis():
features = get_features(friends[1:])
print(features.columns)
features.head()
locations = features.loc[:, ['Province', 'City']] # get location columns
locations = locations[locations['Province'] != ''] # clean empty city or province records
data = locations.groupby(['Province', 'City']).size().unstack() # group by and count
count_subset = data.take(data.sum(1).argsort())[-20:] # obtain the 20 highest data
# plot
subset_plot = count_subset.plot(kind='bar', stacked=True, figsize=(24, 24))
# set fonts
xtick_labels = subset_plot.get_xticklabels()
for label in xtick_labels:
label.set_fontproperties(zhfont)
legend_labels = subset_plot.legend().texts
for label in legend_labels:
label.set_fontproperties(zhfont)
label.set_fontsize(10)
plt.xlabel('Province', fontsize=20)
plt.ylabel('Number', fontsize=20)
plt.show()
#把所有好友头像合并成一张
def getImage(friends):
#下载所有好友的头像图片
num = 0
for i in friends:
img = itchat.get_head_img(i["UserName"])
with open('./headImg/' + str(num) + ".png",'wb') as f:
f.write(img)
f.close()
num += 1
#获取文件夹内的文件个数
length = len(os.listdir('./headImg'))
#根据总面积求每一个的大小
each_size = int(math.sqrt(float(810*810)/length))
#每一行可以放多少个
lines = int(810/each_size)
#生成白色背景新图片
image = Image.new('RGBA', (810, 810),'white')
x = 0
y = 0
for i in range(0,length):
try:
img = Image.open('./headImg/' + str(i) + ".png")
except IOError:
print(i)
print("Error")
else:
img = img.resize((each_size, each_size), Image.ANTIALIAS) #resize image with high-quality
image.paste(img, (x * each_size, y * each_size))
x += 1
if x == lines:
x = 0
y += 1
image.save('./headImg/' + "all.png")
#通过文件传输助手发送到自己微信中
itchat.send_image('./headImg/' + "all.png",'filehelper')
image.show()
#打印好友信息单
def printFriend():
for i in range(len(friends)):
# print("姓名:"+friends[i]["RemarkName"]+" 昵称: "+friends[i]["NickName"]+" 省会: "+friends[i]["Province"]+" 城市: "+friends[i]["City"]+" 个性签名: "+friends[i]["Signature"])
print("""
----------------好友{1}的信息--------------
姓名:{0}
昵称:{1}
省会:{2}
城市:{3}
个性签名:{4}
------------------end----------------------
""".format(friends[i]["RemarkName"], friends[i]["NickName"], friends[i]["Province"], friends[i]["City"],
friends[i]["Signature"]))
print("一共", len(friends), "个好友")
#群发信息(群发助手)
def qunfamsg(messge):
#信息内容
SINCERE_WISH = u'%s'+messge
#获取好友列表
friendList = itchat.get_friends(update=True)[1:]
for friend in friendList:
# 如果是演示目的,把下面的方法改为print即可
# 如果是运行的话,把下面的方法改为itchat.send即可
print(SINCERE_WISH % (friend['RemarkName'] or friend['NickName']), friend['UserName'])
#每发一条信息休息时间
time.sleep(.5)
#指定某个群内所有成员私发信息
def privateRoom(Name):
REAL_SINCERE_WISH = u'祝%s新年快乐!!'
#指定群的群名
chatroomName = Name
itchat.get_chatrooms(update=True)
chatrooms = itchat.search_chatrooms(name=chatroomName)
if chatrooms is None:
print(u'没有找到群聊:' + chatroomName)
else:
chatroom = itchat.update_chatroom(chatrooms[0]['UserName'])
for friend in chatroom['MemberList']:
friend = itchat.search_friends(userName=friend['UserName'])
# 如果是演示目的,把下面的方法改为print即可
# 如果是运行的话,把下面的方法改为itchat.send即可
print(REAL_SINCERE_WISH % (friend['DisplayName'] or friend['NickName']), friend['UserName'])
time.sleep(.5)
#统计好友信息生成excel并转发
def create_and_rtans():
file = xlwt.Workbook()
table = file.add_sheet('info',cell_overwrite_ok=True)
male=female=other=0
for i in friends[1:]:
sex=i["Sex"]
if sex==1:
male+=1
elif sex==2:
female+=1
else:
other+=1
total = len(friends[1:])
#表格表头
table.write(0,5,u'[made by litianci]')
table.write(0,7,u'[共'+set(len(friends)-1)+u'位好友,其中'+str(male)+u'位男性朋友'+str(female)+u'位女性朋友,另外'+str(other)+u'位不明性别]')
table.write(0,0,u'[昵称]')
table.write(0,1,u'[备注名]')
table.write(0,2,u'[省份]')
table.write(0,3,u'[城市]')
table.write(0,4,u'[个性签名]')
#控制行数
a = 0
#信息写进表格
for i in friends:
table.write(a+1,0,i['NickName'])
table.write(a+1,1,i['RemarkName'])
table.write(a+1,2,i['Province'])
table.write(a+1,3,i['Signature'])
a=a+1
#保存文件
fileName=friends[0]['NickName']+time.strftime("%Y%m%d",time.localtime())+'.xls'
file.save(fileName)
#发送文件
itchat.send('@%s@%s' % ('fil',fileName),'filehelper')
itchat.send('made by litianci','filehelper')
if __name__ == '__main__':
itchat.auto_login()
# 获取好友信息
friends = itchat.get_friends(update=True)[0:]
Name = {}
Nic = []
User = []
for i in range(len(friends)):
Nic.append(friends[i]["NickName"])
User.append(friends[i]["UserName"])
for i in range(len(friends)):
Name[Nic[i]] = User[i]
# 微信好友分析
#friend_analysis(friends)
# 好友省份城市分析
#province_analysis()
# 把所有好友头像合并成一张
#getImage(friends)
#打印好友信息
#printFriend()
#群发信息(群发助手)
#qunfamsg("群发信息的内容")
#给指定群的所有成员私发信息
#privateRoom("指定群的名字")
# 统计好友信息生成excel并转发
#create_and_rtans():
#保持运行
itchat.run()