itchat微信接口

这个微信接口还挺有意思的,随便玩了下,可以备份消息,群发消息好多,不过貌似有些功能还有些bug,写了一段群发消息的代码,可以做个群聊机器人:

import itchat

itchat.auto_login(hotReload=True)
chatrooms = itchat.get_chatrooms(update=True, contactOnly=True)
chatroom_ids = [c['UserName']for c in chatrooms]
print('正在监测的群聊:', 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()

实现了一个自动回复特定群消息的功能,不过如果连上图灵机器人就可以更智能一点了,懒得搞了,还有msg那一长串谁看下去啊- -还有很多功能以后再玩吧。
参考:http://www.jianshu.com/p/7aeadca0c9bd

实现爬好友图片功能:

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')

参考:https://www.jianshu.com/p/cd4e4c0080ec
注意JPGA变为RGB

——————————————————————————————————————————-
图灵机器人

import itchat
import requests
然后定义一个向图灵机器人发送消息并接受机器人回复的消息,并将从图灵机器人接受到的消息return返回。


def get_response(_info):
    print(_info)                                       # 从好友发过来的消息
    api_url = 'http://www.tuling123.com/openapi/api'   # 图灵机器人网址
    data = {
        'key': '485712b8079e44e1bc4af10872b08319',     # 如果这个 apiKey 如不能用,那就注册一次
        'info': _info,                                 # 这是我们从好友接收到的消息 然后转发给图灵机器人
        'userid': 'wechat-robot',                      # 这里你想改什么都可以
    }
    r = requests.post(api_url, data=data).json()       # 把data数据发
    print(r.get('text'))                               # 机器人回复给好友的消息
    return r
 

三、定义消息回复

@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
    return "【我是天才^_^】" + get_response(msg["Text"])["text"]
 
/这里是关闭群消息的,针对群消息可以再加一栏/

四、扫码登录,大功告成。

if __name__ == '__main__':
    itchat.auto_login(hotReload=True)                  # hotReload = True, 保持在线,下次运行代码可自动登录
    itchat.run()

爬好友信息

import codecs
import json
from pyecharts import Bar,Pie,Map,WordCloud
# 容器类, pip有安装的版本问题,通过wheels安装,详情可以搜索
from collections import Counter
import jieba.analyse

# 数据存储方法,为了防止编码不统一的情况,使用codecs来进行打开
def saveFriends(friendsList):
    outputFile = 'F:/test/myenviron/friends.json'
    with codecs.open(outputFile, 'w', encoding='utf-8') as jsonFile:
        # 默认使用ascii,为了输出中文将参数ensure_ascii设置成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, # 是否显示标签
        label_text_color = None, # 标签颜色
        legend_orient = 'vertical', # 图例是否垂直
        legend_pos = 'left'
    )
    pie.render(outputFile)

# 绘制地图
def drawMap(name,rank):
    outputFile = 'F:/test/myenviron/区域分布图.image'
    map = Map(title='微信好友区域分布图', width=1200, height=600, title_pos='center')
    map.add(
        '',name,rank,
        maptype = 'china', # 地图范围
        is_visualmap = True, # 是否开启鼠标缩放漫游等
        is_label_show = True # 是否显示地图标记
    )
    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)

# 实现将counter数据结构拆分成两个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模块提取出关键词并计算其权重,利用了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接口获取的数据中显示的是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提取出有用数据并存放在字典中
        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中的数据
    inputFile = 'F:/test/myenviron/friends.json'
    friendList = getFriends(inputFile)

    # 需要统计的字段使用counter数据类型存储
    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)

    # 统计出排名前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)

你可能感兴趣的:(itchat微信接口)