itchat 微信的使用


#coding=utf8
import itchat

# 自動回復
# 封裝好的裝飾器,當接收到的消息是Text,即文字消息
@itchat.msg_register('Text')
def text_reply(msg):
    # 當消息不是由自己發出的時候
    if not msg['FromUserName'] == myUserName:
        # 發送一條提示給文件助手
        itchat.send_msg(u"[%s]收到好友@%s 的信息:%s\n" %
                        (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(msg['CreateTime'])),
                         msg['User']['NickName'],
                         msg['Text']), 'filehelper')
        # 回復給好友
        return u'[自動回復]您好,我現在有事不在,一會再和您聯系。\n已經收到您的的信息:%s\n' % (msg['Text'])

if __name__ == '__main__':
    itchat.auto_login()

    # 獲取自己的UserName
    myUserName = itchat.get_friends(update=True)[0]["UserName"]
    itchat.run()

好友簽名標簽雲

# coding:utf-8
import itchat
import re

itchat.login()
friends = itchat.get_friends(update=True)[0:]
tList = []
for i in friends:
    signature = i["Signature"].replace(" ", "").replace("span", "").replace("class", "").replace("emoji", "")
    rep = re.compile("1f\d.+")
    signature = rep.sub("", signature)
    tList.append(signature)

# 拼接字符串
text = "".join(tList)

# jieba分詞
import jieba
wordlist_jieba = jieba.cut(text, cut_all=True)
wl_space_split = " ".join(wordlist_jieba)

# wordcloud詞雲
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import os
import numpy as np
import PIL.Image as Image


d = os.path.dirname(__file__)
# 更改目錄下Wordcloud生成圖片,如:xiaohuangren.jpg
alice_coloring = np.array(Image.open(os.path.join(d, "xiaohuangren.jpg")))
# win系統需要更改font路徑,如:C:\Windows\Fonts\msyhbd.ttc
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(d, "wechat_cloud.png"))
itchat.send_image("wechat_cloud.png", 'filehelper')
# coding:utf-8
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)

# 使用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()

 

自動回復機器人

import requests
import itchat

KEY = 'd364bd41d25c4c1a9dfcecccf8ed8494'

def get_response(msg):
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
    'key' : KEY,
    'info' : msg,
    'userid' : 'wechat-robot',
    }
    try:
        r = requests.post(apiUrl, data=data).json()
        return r.get('text')
    except Exception as e:
        print(e)

@itchat.msg_register(['Map', 'Card', 'Note', 'Sharing', 'Picture','Text'])
def tuling_reply(msg):
    defaultReply = 'I received: ' + msg['Text']
    reply = get_response(msg['Text'])
    return reply or defaultReply

itchat.auto_login(hotReload=True)
itchat.run()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM