天天看點

利用itchat實作模拟微信網頁登入及好友性别分析+自動回複消息和檔案

前兩天在微信公衆号(Python中文社群)上了解到一個很有趣的Python的“玩法”

就是通過itchat庫來實作微信的一些基本操作

首先,我們要安裝itchat庫

pip install itchat
           

然後我們就可以利用三行簡單的代碼來實作網頁的微信登入

import itchat #首先得導入包。。。
itchat.auto_login()   #這裡可以将屬性設定hotReload=True即‘熱啟動’
#itchat.auto_login(hotReload=True)是可以将你掃描二維碼登入後的狀态儲存為一個itchat.pkl檔案,這樣可以讓你下次運作時不再掃描二維碼即可登入(網上看到有人說是十分鐘左右,我也沒做驗證,是以不太清楚)。
itchat.run()   # 運作并保持線上狀态
           

登入成功後就是這樣了

利用itchat實作模拟微信網頁登入及好友性别分析+自動回複消息和檔案

然後我們就可以進行一些有趣的操作啦

你想知道你的微信好友是男的多還是女的多嗎?

首先我們要将你的好友的性别讀取并暫時儲存下來,

  1. 這裡要說一下微信好友性别傳回的值
  2. 男性:1
  3. 女性:2
  4. 不明:0“不明”
import itchat
if __name__ == '__main__':
    itchat.auto_login(hotReload=True)
    #讀取朋友的資訊,update為更新
    friends=itchat.get_friends(update=True)[0:]
    male=female=other=0
    #這裡從friend[1]開始,因為friend[0]是你自己的資訊
    for i in friends[1:]:
    #隻需要讀取好友的sex即可,當然你還可以讀取其他的内容進行分析
        sex=i["Sex"]
        if sex==1:
            male+=1
        elif sex==2:
            female+=1
        else:
            other+=1
    total=len(friends)
    print("男性好友:%.2f%%"%(float(male)/total*100)+"\n"
          +"女性朋友: %.2f%%"%(float(female)/total*100)+"\n"+
          "不明性别好友:%.2f%%"%(float(other)/total*100))
           

這樣就能夠看到你的好友性别的分布啦,也可以看到城市、年齡等的分布。還可以通過pyecharts庫将資料可視化,以便讓這些資料更加清晰的顯示出來。

然後我們要

  1. 抓取每日一句
  2. 将每日一句的内容轉換為音頻(.mp3)檔案
  3. 當接收到好友的消息時
  4. 給好友發送每日一句和音頻檔案

    抓取每日一句

#需要利用到一點爬蟲的知識
#emmm```我在網上找了一小段代碼
def get_news():
    """擷取金山詞霸的每日一句,中文和英文"""
    url = "http://open.iciba.com/dsapi/"  #這是位址
    r = requests.get(url)  #發送請求
    content = r.json()['content']
    note = r.json()['note']
    return content, note
           

将抓取下來的文字轉換為語音

需要用到百度的語音API接口,教程很多,隻需要注冊一個賬号即可。

利用itchat實作模拟微信網頁登入及好友性别分析+自動回複消息和檔案
def Voice(message):
    message = message
   APP_ID = '你的 App ID'
   API_KEY = '你的 Api Key'
    SECRET_KEY = '你的 Secret Key'
    client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
    print('語音提醒:', message)  #輸出字元串主要是為了看抓取到的内容。
    #百度語音合成
    #可檢視百度的技術文檔[python技術文檔](https://ai.baidu.com/docs#/TTS-Online-Python-SDK/top)
    result = client.synthesis(message, 'zh', 1, {'vol': 5})  #
    if not isinstance(result, dict):
        with open('sound.mp3', 'wb') as f:
            f.write(result)
            f.close()
           

文檔中的說明

利用itchat實作模拟微信網頁登入及好友性别分析+自動回複消息和檔案
利用itchat實作模拟微信網頁登入及好友性别分析+自動回複消息和檔案

接下來就是發送消息和檔案

#完整代碼
from __future__ import unicode_literals
import itchat
from aip import AipSpeech
from wxpy import *
import requests

def get_news()
    url = "http://open.iciba.com/dsapi/"
    r = requests.get(url)
    content = r.json()['content']
    note = r.json()['note']
    return content, note

def Voice_broadcast(message):
    message = message
    APP_ID = '14865118'
    API_KEY = 'lWvOaGZY7lW8Kd6s6I3IVGvP'
    SECRET_KEY = 'v566mLWh6bq69vVK9DEfsXDVqE9o06QO'
    client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
    print('語音提醒:', message)
    #百度語音合成
    result = client.synthesis(message, 'zh', 1, {'vol': 5})
    if not isinstance(result, dict):
        with open('sound.mp3', 'wb') as f:
            f.write(result)
            f.close()
    #playsound子產品播放語音

@itchat.msg_register([PICTURE,TEXT])
def simple_reply(msg):
    content, note = get_news()
    voice = note + content
    Voice_broadcast(voice)

    itchat.send(voice,msg['FromUserName'])
    try:
        itchat.send_file("sound.mp3",msg['FromUserName'])
        print("success")
    except:
        print("fail")


if __name__ == "__main__":
    itchat.auto_login(hotReload=True)
    friends_list = itchat.get_friends(update=True)
    itchat.run()