[09]微信之itchat库

itchat文档:https://itchat.readthedocs.io/zh/latest/

itchat是一个开源的微信个人号接口,可以使用该库进行微信网页版中的所有操作,比如:所有好友、添加好友、拉好友群聊、微信机器人等等。详细用户请看文档介绍,在这里

微信好友全头像的拼接

安装依赖包

pip install itchat
pip install pillow
  • 代码
import itchat
import math
import PIL.Image as Image
import os

itchat.auto_login()
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(r'文件夹' + "/" + str(num) + ".jpg",'wb')
    fileImage.write(img)
    fileImage.close()
    num += 1

ls = os.listdir(r'文件夹')
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(r'文件夹' + "/" + 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.save(r'文件夹' + "/" + "all.jpg")
itchat.send_image(r'文件夹' + "/" + "all.jpg", 'filehelper')

代码中的文件夹是需要创建一个文件夹,并用该文件夹的路径替换调文件夹

代码运行过程中会出现登录二维码,用微信扫一下,你就可以看到处理的进度。稍后你的微信文件传输助手就会收到拼接好的头像图片。

all.jpg

基本信息统计

  • 代码1
# -*- coding:utf-8 -*-
import itchat
from pandas import DataFrame


itchat.login()
friends = itchat.get_friends(update=True)[0:]
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:])
malecol = round(float(male) / total * 100, 2)
femalecol = round(float(female) / total * 100, 2)
othercol = round(float(other) / total * 100, 2)
print('男性朋友:%.2f%%' % (malecol) +
      '\n' + '女性朋友:%.2f%%' % (femalecol) +
      '\n' + '性别不明的好友:%.2f%%' % (othercol))

# 使用echarts,加上这段
from echarts import Echart, Legend, Pie #pip install echarts-python

chart = Echart(u'%s的微信好友性别比例' % (friends[0]['NickName']), 'from WeChat')
chart.use(Pie('WeChat',
              [{'value': male, 'name': u'男性 %.2f%%' % malecol},
               {'value': female, 'name': u'女性 %.2f%%' % femalecol},
               {'value': other, 'name': u'其他 %.2f%%' % othercol}],
              radius=["50%", "70%"]))
chart.use(Legend(["male", "female", "other"]))
del chart.json["xAxis"]
del chart.json["yAxis"]
chart.plot()

def get_var(var):
    variable = []
    for i in friends:
        value = i[var]
        variable.append(value)
    return variable

NickName = get_var('NickName')#昵称
Sex = get_var('Sex')#性别
Province = get_var('Province')#省份
City = get_var('City')#城市
Signature = get_var('Signature')#签名

data = {'NickName': NickName,
        'Sex': Sex,
        'Province': Province,
        'City': City,
        'Signature': Signature
        }

frame = DataFrame(data)
frame.to_csv('data.csv', index=True, encoding="utf_8_sig")

好像不够直观,有兴趣的朋友可以加上可视化的展示,我这里用基于python的Echarts
先安装了

pip install echarts-python

展示比例一般使用百分比圆饼表吧

# 使用echarts,加上这段
from echarts import Echart, Legend, Pie

chart = Echart(u'%s的微信好友性别比例' % (friends[0]['NickName']), 'from WeChat')
chart.use(Pie('WeChat',
              [{'value': male, 'name': u'男性 %.2f%%' % (float(male) / total * 100)},
               {'value': female, 'name': u'女性 %.2f%%' % (float(female) / total * 100)},
               {'value': other, 'name': u'其他 %.2f%%' % (float(other) / total * 100)}],
              radius=["50%", "70%"]))
chart.use(Legend(["male", "female", "other"]))
del chart.json["xAxis"]
del chart.json["yAxis"]
chart.plot()

image.png

  • 代码2
# -*- coding:utf-8 -*-
import itchat
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt


#此时稍微等一会,会跳出一个二维码,用手机微信扫描登录即可
itchat.login()
#friends里面就是你的好友信息啦,一共有36个字段,包括昵称、你的备注、性别、地区、签名、头像地址等等
friends = itchat.get_friends(update=True)
df_friends = pd.DataFrame(friends)
#性别统计,0是未知,1是男生,2是女生
Sex_count = df_friends['Sex'].value_counts()
plt.figure(figsize=(16,8)) #设置图片大小
labels = ['male','female','unknown']
colors = ['red','yellowgreen','lightskyblue']
#画性别分布饼图
plt.pie(Sex_count,colors=colors,labels=labels,autopct = '%3.1f%%',startangle = 90,pctdistance = 0.8)
# 设置x,y轴刻度一致,这样饼图才能是圆的
plt.axis('equal')
plt.legend(loc='left')
# plt.show() #这个注释打开,下面无法保存图片
plt.savefig('好友性别比例.jpg')

'''获取好友的省份和地区分布'''
Province = df_friends.Province
Province_count = Province.value_counts()
#有一些好友地理信息为空,过滤掉这一部分人
Province_count = Province_count[Province_count.index!='']
df_province =DataFrame(Province_count)
df_province.to_csv('省份分布.csv',encoding='utf-8')

City = df_friends.City
City_count = City.value_counts()
City_count = City_count[City_count.index!='']

#统计好友基本信息
number_of_friends = len(friends)
NickName = friends[0]['NickName'] #获取自己的昵称
file_name_all = NickName+'_basic_inf.txt'

with open(file_name_all,'w') as f:
    f.write('你共有%d个好友,其中有%d个男生,%d个女生,%d未显示性别。\n\n' %(number_of_friends, Sex_count[1], Sex_count[2], Sex_count[0]))

    f.write('你的朋友主要来自省份:%s(%d)、%s(%d)和%s(%d)。\n\n' %(Province_count.index[0],Province_count[0],Province_count.index[1],
     Province_count[1],Province_count.index[2],Province_count[2]))

    f.write('主要来自这些城市:%s(%d)、%s(%d)、%s(%d)、%s(%d)、%s(%d)和%s(%d)。'%(City_count.index[0],City_count[0],City_count.index[1],
     City_count[1],City_count.index[2],City_count[2],City_count.index[3],City_count[3],City_count.index[4],City_count[4],City_count.index[5],City_count[5]))

image.png

个性签名和昵称分布

  • code
# -*- coding:utf-8 -*-
import jieba,re,itchat
import numpy as np
from collections import defaultdict
from wordcloud import WordCloud, ImageColorGenerator
import PIL.Image as Image
import matplotlib.pyplot as plt
from pandas import DataFrame
import pandas as pd


#此时稍微等一会,会跳出一个二维码,用手机微信扫描登录即可
itchat.login()
#friends里面就是你的好友信息啦,一共有36个字段,包括昵称、你的备注、性别、地区、签名、头像地址等等
friends = itchat.get_friends(update=True)
df_friends = pd.DataFrame(friends)
Signatures = df_friends.Signature
regex1 = re.compile('<span.*?</span>') #匹配表情
regex2 = re.compile('\s{2,}')#匹配两个以上占位符。
#用一个空格替换表情和多个空格。
Signatures = [regex2.sub(' ',regex1.sub('',signature,re.S)) for signature in Signatures]
Signatures = [signature for signature in Signatures if len(signature)>0] #去除空字符串
text = ' '.join(Signatures)
wordlist = jieba.cut(text, cut_all=False)

def statistics(lst) :
    dic = {}
    for k in lst:
        if not k.decode('utf-8') in dic :
            dic[k.decode('utf-8')] = 0
        dic[k.decode('utf-8')] +=1
    return dic

worddic = statistics(wordlist)

coloring = np.array(Image.open("./xiaodong.jpg"))#词云的背景和颜色,需要提前自己找好
my_wordcloud = WordCloud(background_color="white", max_words=2000,
              mask=coloring, max_font_size=200, random_state=8, scale=2,
              font_path="./songti.otf").generate_from_frequencies(worddic)

image_colors = ImageColorGenerator(coloring)

plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()
my_wordcloud.to_file('签名分词.png')
#---------------------------------------------------
'''换一种词云产生方式,将关键词放大比例显示'''
word_space_split = ' '.join(wordlist)
coloring = np.array(Image.open("./xiaodong.jpg")) #词云的背景和颜色。这张图片在本地。
my_wordcloud = WordCloud(background_color="white", max_words=2000,
             mask=coloring, max_font_size=60, random_state=42, scale=2,
             font_path="./songti.otf").generate(word_space_split)

my_wordcloud.to_file('关键词签名分词.jpg') #保存图片

#--------------------------------------昵称云图-------------------------------------------------------
Nicknames = df_friends.NickName
regex1 = re.compile('<span.*?</span>') #匹配表情
regex2 = re.compile('\s{2,}')#匹配两个以上占位符。
#用一个空格替换表情和多个空格。
Nicknames = [regex2.sub(' ',regex1.sub('',nickname,re.S)) for nickname in Nicknames]
Nicknames = [nickname for nickname in Nicknames if len(nickname)>0] #去除空字符串
text_nicknames = ''.join(Nicknames)
a = re.compile(' ')
text_nicknames = a.sub('',text_nicknames)

def save_chinese(text):
    text = text.decode('utf-8')
    a = re.compile(u"[\u4E00-\u9FA5]+")
    text = a.findall(text)
    text=''.join(text)
    return text

text_nicknames = save_chinese(text_nicknames)

def get_count(Sequence):
    counts = defaultdict(int) #初始化一个字典
    for x in Sequence:
        counts[x] += 1

    return counts

nickname_count = get_count(text_nicknames)
#nickname_count_s = sorted(nickname_count.iteritems(), key=lambda d:d[1], reverse = True)
coloring = np.array(Image.open("./xiaodong.jpg"))#词云的背景和颜色,需要提前自己找。
nm_wordcloud = WordCloud(background_color="white", max_words=2000,
               mask=coloring, max_font_size=200, random_state=8, scale=2,
               font_path="./songti.otf").generate_from_frequencies(nickname_count)

# image_colors = ImageColorGenerator(coloring)
#plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(nm_wordcloud)
plt.axis("off")
plt.show()
nm_wordcloud.to_file('昵称云图.png')

image.png

image.png

爬取所有T信好友的信息

  • code
import itchat
from pandas import DataFrame

itchat.login()

friends=itchat.get_friends(update=True)[0:]

def get_var(var):
 variable=[]
 for i in friends:
  value=i[var]
  variable.append(value)
 return variable
 

NickName=get_var('NickName')
Sex=get_var('Sex')
Province=get_var('Province')
City=get_var('City')
Signature=get_var('Signature')

data={'NickName':NickName,'Sex':Sex,'Province':Province,'City':City,'Signature':Signature}
frame=DataFrame(data)
frame.to_csv('data.csv',index=True,encoding="utf_8_sig")

计算微信好友男女比例:

import itchat
 
itchat.login()
friends=itchat.get_friends(update=True)[0:]
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:])
malecol=round(float(male)/total*100,2)
femalecol=round(float(female)/total*100,2)
othercol=round(float(other)/total*100,2)
print('男性朋友:%.2f%%' %(malecol)+'\n'+'女性朋友:%.2f%%' % (femalecol)+'\n'+'性别不明的好友:%.2f%%' %(othercol))
print("显示图如下:")

微信聊天机器人

本文主要使用该库完成一个能够处理微信消息的的图灵器人,包括好友聊天、群聊天。

1、登陆
import itchat
# 登陆
itchat.auto_login()   # 可设置hotReload = True
# 运行并保持在线状态
itchat.run()

此外,itchat 也提供短时间内断线重连的功能,只需要添加hotReload = True参数,下次登陆时不需要通过扫描二维码,只需要在手机端确认登陆即可。

2、消息的发送

itchat 库可以发送 文本、图片、视频、附件等内容,如向微信文件传输助手发送消息,可这样:

itchat.send('Hello', toUserName='filehelper')

toUserName 为要向发送消息的人的微信号,可以在微信手机端点击查询,也可以使用itchat库中的search_friends函数来进行查找,返回其微信号,详细用法,自行查找官方文档。

3、消息的接收
###################### 完整代码##############################
# 加载库
from itchat.content import *
import requests
import json
import itchat


itchat.auto_login(hotReload = True)
# 调用图灵机器人的api,采用爬虫的原理,根据聊天消息返回回复内容
def tuling(info):
    appkey = "e5ccc9c7c8834ec3b08940e290ff1559"
    url = "http://www.tuling123.com/openapi/api?key=%s&info=%s"%(appkey,info)
    req = requests.get(url)
    content = req.text
    data = json.loads(content)
    answer = data['text']
    return answer

# 对于群聊信息,定义获取想要针对某个群进行机器人回复的群ID函数
def group_id(name):
    df = itchat.search_chatrooms(name=name)
    return df[0]['UserName']

# 注册文本消息,绑定到text_reply处理函数
# text_reply msg_files可以处理好友之间的聊天回复
@itchat.msg_register([TEXT,MAP,CARD,NOTE,SHARING])
def text_reply(msg):
    itchat.send('%s' % tuling(msg['Text']),msg['FromUserName'])

@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
    msg['Text'](msg['FileName'])
    return '@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName'])

# 现在微信加了好多群,并不想对所有的群都进行设置微信机器人,只针对想要设置的群进行微信机器人,可进行如下设置
@itchat.msg_register(TEXT, isGroupChat=True)
def group_text_reply(msg):
    # 当然如果只想针对@你的人才回复,可以设置if msg['isAt']: 
    item = group_id(u'想要设置的群的名称')  # 根据自己的需求设置
    if msg['ToUserName'] == item:
        itchat.send(u'%s' % tuling(msg['Text']), item)

itchat.run()

那么,下面你的好友、微信群可以愉快的跟图灵机器人聊天啦~~~

image.png

用微信每天给女朋友说晚安

准备:

微信号
pip install wxpy
pip install requests

代码如下:

# 不要抄下源码就运行,你需要改动几个地方
from __future__ import unicode_literals
from threading import Timer
from wxpy import *
import requests


# bot = Bot()
# 这里的二维码是用像素的形式打印出来!,如果你在win环境上运行,替换为  bot=Bot()
bot = Bot(console_qr=2, cache_path="botoo.pkl")


def get_news1():
    # 获取金山词霸每日一句,英文和翻译
    url = "http://open.iciba.com/dsapi/"
    r = requests.get(url)
    contents = r.json()['content']
    translation = r.json()['translation']
    return contents, translation

def send_news():
    try:
        my_friend = bot.friends().search(u'周小董')[0]  # 你朋友的微信名称,不是备注,也不是微信帐号。
        my_friend.send(get_news1()[0])
        my_friend.send(get_news1()[1][5:])
        my_friend.send(u"来自周小董的心灵鸡汤!")
        # 每86400秒(1天),发送1次,不用linux的定时任务是因为每次登陆都需要扫描二维码登陆,很麻烦的一件事,就让他一直挂着吧
        t = Timer(86400,send_news)
        t.start()
    except:
        my_friend = bot.friends().search('天马行空@2')[0]# 你的微信名称,不是微信帐号。
        my_friend.send(u"今天消息发送失败了")

if __name__ == "__main__":
    send_news()

最终效果是这样的:

image

参考:https://zhuanlan.zhihu.com/p/26514576
https://zhuanlan.zhihu.com/p/33230381
http://www.cnblogs.com/botoo/p/8276064.html
https://www.jianshu.com/p/5d4de51f5375
http://www.cnblogs.com/botoo/p/8622379.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周小董

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值