itchat微信接口

這個微信接口還挺有意思的,隨便玩了下,可以備份消息,群發(fā)消息好多,不過貌似有些功能還有些bug,寫了一段群發(fā)消息的代碼,可以做個群聊機(jī)器人:

import itchat

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

實(shí)現(xiàn)了一個自動回復(fù)特定群消息的功能,不過如果連上圖靈機(jī)器人就可以更智能一點(diǎn)了,懶得搞了,還有msg那一長串誰看下去啊- -還有很多功能以后再玩吧。
參考:http://www.lxweimin.com/p/7aeadca0c9bd

實(shí)現(xiàn)爬好友圖片功能:

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

參考:http://www.lxweimin.com/p/cd4e4c0080ec
注意JPGA變?yōu)镽GB

——————————————————————————————————————————-
圖靈機(jī)器人

import itchat
import requests
然后定義一個向圖靈機(jī)器人發(fā)送消息并接受機(jī)器人回復(fù)的消息,并將從圖靈機(jī)器人接受到的消息return返回。


def get_response(_info):
    print(_info)                                       # 從好友發(fā)過來的消息
    api_url = 'http://www.tuling123.com/openapi/api'   # 圖靈機(jī)器人網(wǎng)址
    data = {
        'key': '485712b8079e44e1bc4af10872b08319',     # 如果這個 apiKey 如不能用,那就注冊一次
        'info': _info,                                 # 這是我們從好友接收到的消息 然后轉(zhuǎn)發(fā)給圖靈機(jī)器人
        'userid': 'wechat-robot',                      # 這里你想改什么都可以
    }
    r = requests.post(api_url, data=data).json()       # 把data數(shù)據(jù)發(fā)
    print(r.get('text'))                               # 機(jī)器人回復(fù)給好友的消息
    return r
 

三、定義消息回復(fù)

@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
    return "【我是天才^_^】" + get_response(msg["Text"])["text"]
 
/這里是關(guān)閉群消息的,針對群消息可以再加一欄/

四、掃碼登錄,大功告成。

if __name__ == '__main__':
    itchat.auto_login(hotReload=True)                  # hotReload = True, 保持在線,下次運(yùn)行代碼可自動登錄
    itchat.run()

爬好友信息

import codecs
import json
from pyecharts import Bar,Pie,Map,WordCloud
# 容器類, pip有安裝的版本問題,通過wheels安裝,詳情可以搜索
from collections import Counter
import jieba.analyse

# 數(shù)據(jù)存儲方法,為了防止編碼不統(tǒng)一的情況,使用codecs來進(jìn)行打開
def saveFriends(friendsList):
    outputFile = 'F:/test/myenviron/friends.json'
    with codecs.open(outputFile, 'w', encoding='utf-8') as jsonFile:
        # 默認(rèn)使用ascii,為了輸出中文將參數(shù)ensure_ascii設(shè)置成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, # 是否顯示標(biāo)簽
        label_text_color = None, # 標(biāo)簽顏色
        legend_orient = 'vertical', # 圖例是否垂直
        legend_pos = 'left'
    )
    pie.render(outputFile)

# 繪制地圖
def drawMap(name,rank):
    outputFile = 'F:/test/myenviron/區(qū)域分布圖.image'
    map = Map(title='微信好友區(qū)域分布圖', width=1200, height=600, title_pos='center')
    map.add(
        '',name,rank,
        maptype = 'china', # 地圖范圍
        is_visualmap = True, # 是否開啟鼠標(biāo)縮放漫游等
        is_label_show = True # 是否顯示地圖標(biāo)記
    )
    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)

# 實(shí)現(xiàn)將counter數(shù)據(jù)結(jié)構(gòu)拆分成兩個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模塊提取出關(guān)鍵詞并計(jì)算其權(quán)重,利用了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接口獲取的數(shù)據(jù)中顯示的是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提取出有用數(shù)據(jù)并存放在字典中
        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中的數(shù)據(jù)
    inputFile = 'F:/test/myenviron/friends.json'
    friendList = getFriends(inputFile)

    # 需要統(tǒng)計(jì)的字段使用counter數(shù)據(jù)類型存儲
    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)

    # 統(tǒng)計(jì)出排名前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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,578評論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,701評論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,691評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,974評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,694評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,026評論 1 329
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,015評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,193評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,719評論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,442評論 3 360
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,668評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,151評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,846評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,255評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,592評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,394評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,635評論 2 380

推薦閱讀更多精彩內(nèi)容