最新消息:

python 玩转微信,超有趣

Python 少儿编程 1943浏览 0评论

itchat

无意间发现的一个有意思的开源项目itchat,相当于微信api,扫码登录后去抓包爬取信息,还可以post去发送信息。 GitHub star数量4,非常火,作者是@LittleCoder,已经把微信的接口完成了,大大的方便了我们对微信的挖掘,以下的功能也通过itchat来实现。

安装itchat这个库

pip install itchat

先来段简单的试用,实现微信的登录,运行下面代码会生成一个二维码,扫码之后手机端确认登录,就会发送一条信息给‘filehelper’,这个filehelper就是微信上的文件传输助手。

import itchat# 登录itchat.login()#  发送消息itchat.send(u'你好', 'fileheper')

1.有了itchat,如果你想要给文件传输助手发一条信息,只需要这样:

import itchat

itchat.auto_login()

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

如果你想要回复发给自己的文本消息,只需要这样:

import itchat@itchat.msg_register(itchat.content.TEXT)def text_reply(msg):    return msg.text

itchat.auto_login()
itchat.run()

用户搜索

使用search_friends方法可以搜索用户,有四种搜索方式:

  1. 仅获取自己的用户信息

  2. 获取特定UserName的用户信息

  3. 获取备注、微信号、昵称中的任何一项等于name键值的用户

  4. 获取备注、微信号、昵称分别等于相应键值的用户

其中三、四项可以一同使用,下面是示例程序:

# 获取自己的用户信息,返回自己的属性字典itchat.search_friends()# 获取特定UserName的用户信息itchat.search_friends(userName='@abcdefg1234567')# 获取任何一项等于name键值的用户itchat.search_friends(name='littlecodersh')# 获取分别对应相应键值的用户itchat.search_friends(wechatAccount='littlecodersh')# 三、四项功能可以一同使用itchat.search_friends(name='LittleCoder机器人', wechatAccount='littlecodersh')

微信好友男女比例

想统计下自己微信里好友的性别比例,当然也是很简单,先获取好友列表,统计列表里性别计数

import itchat# 先登录itchat.login()# 获取好友列表friends = itchat.get_friends(update=True)[0:]# 初始化计数器,有男有女,当然,有些人是不填的male = female = other = 0# 遍历这个列表,列表里第一位是自己,所以从"自己"之后开始计算# 1表示男性,2女性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:])# 好了,打印结果print(u"男性好友:%.2f%%" % (float(male) / total * 100))print(u"女性好友:%.2f%%" % (float(female) / total * 100))print(u"其他:%.2f%%" % (float(other) / total * 100))

结果:

python 玩转微信,超有趣

结果是个意外。。。。

好友昵称,备注,以及个性签名 

其实还可以爬出很多每个好友的其他属性,比如家乡等等信息! 直接上代码

# coding:utf-8import itchat# 先登录itchat.login()# 获取好友列表friends = itchat.get_friends(update=True)[0:]for i in friends:    # 获取个性签名
    # print(i)
    name = i['RemarkName']
    nickname = i['NickName']    # 正则匹配过滤掉emoji表情,例如emoji1f3c3等
    signature = i["Signature"].strip().replace("span", "").replace("class", "").replace("emoji",                                                                                        "")    print(name + "," + nickname + "," + signature)

运行效果如图:

python 玩转微信,超有趣

好友个性签名词云

获取好友列表的时候,返回的json信息中还看到了有个性签名的信息,脑洞一开,把大家的个性签名都抓下来,看看高频词语,还做了个词云。 先全部抓取下来 打印之后你会发现,有大量的span,class,emoji,emoji1f3c3等的字段,因为个性签名中使用了表情符号,这些字段都是要过滤掉的,写个正则和replace方法过滤掉 贴代码:

# wordcloud词云import matplotlib.pyplot as pltfrom wordcloud import WordCloud, ImageColorGeneratorimport osimport numpy as npimport PIL.Image as Imagedimport itchat

os.path.dirname(__file__)
alice_coloring = np.array(Imaged.open(os.path.join('/Users/t-mac/desktop', "640.jpeg")))
my_wordcloud = WordCloud(background_color="white", max_words=2000, mask=alice_coloring,                         max_font_size=40, random_state=42,                         font_path='/Users/sebastian/Library/Fonts/Arial Unicode.ttf').generate(wl_space_split)
image_colors = ImageColorGenerator(alice_coloring)
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()# 保存图片 并发送到手机my_wordcloud.to_file(os.path.join('/Users/t-mac/desktop', "wechat_cloud.png"))
itchat.send_image("wechat_cloud.png", 'filehelper')

效果如图:

python 玩转微信,超有趣

附件的下载与发送

itchat的附件下载方法存储在msg的Text键中。

发送的文件的文件名(图片给出的默认文件名)都存储在msg的FileName键中。

下载方法接受一个可用的位置参数(包括文件名),并将文件相应的存储。

@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])def download_files(msg):
    msg.download(msg.fileName)
    itchat.send('@%s@%s' % (        'img' if msg['Type'] == 'Picture' else 'fil', msg['FileName']),
        msg['FromUserName'])    return '%s received' % msg['Type']

如果你不需要下载到本地,仅想要读取二进制串进行进一步处理可以不传入参数,方法将会返回图片的二进制串。

@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])def download_files(msg):    with open(msg.fileName, 'wb') as f:
        f.write(msg.download())

用户多开

使用如下命令可以完成多开的操作:

import itchat

newInstance = itchat.new_instance()
newInstance.auto_login(hotReload=True, statusStorageDir='newInstance.pkl')@newInstance.msg_register(itchat.content.TEXT)def reply(msg):    return msg.text

newInstance.run()

退出及登陆完成后调用特定方法

登陆完成后的方法需要赋值在loginCallback中。

而退出后的方法需要赋值在exitCallback中。

import timeimport itchatdef lc():    print('finish login')def ec():    print('exit')

itchat.auto_login(loginCallback=lc, exitCallback=ec)
time.sleep(3)
itchat.logout()

若不设置loginCallback的值,则将会自动删除二维码图片并清空命令行显示。

 

自动添加好友

首先为了自动添加,所以先注册一个好友添加功能的消息,并当好友添加后,自动回复

python 玩转微信,超有趣

自动回复好友

好友通过非关键字发送可以获取机器人的功能菜单,再通过相应的命令进入其他功能,如果好友没有发送正确的命令,则return 开始菜单。

python 玩转微信,超有趣

  • 拉好友入群
    当好友输入的命令等同于menu_1定义的命令时,机器人自动发送群的邀请给好友,好友点击后可以进入

python 玩转微信,超有趣

  • 表单填写
    发送填写要求和模板给好友

python 玩转微信,超有趣

  • 联系管理员(分享名片)
    通过分享名片,让需要联系管理员的好友自己添加管理员

python 玩转微信,超有趣

转自公众号:
YaK芽课

您必须 登录 才能发表评论!