python實(shí)現(xiàn)微信接口(itchat)

python實(shí)現(xiàn)微信接口(itchat)

安裝

  • sudo pip install itchat

登錄

  • itchat.auto_login() 這種方法將會(huì)通過(guò)微信掃描二維碼登錄,但是這種登錄的方式確實(shí)短時(shí)間的登錄,并不會(huì)保留登錄的狀態(tài),也就是下次登錄時(shí)還是需要掃描二維碼,如果加上hotReload==True,那么就會(huì)保留登錄的狀態(tài),至少在后面的幾次登錄過(guò)程中不會(huì)再次掃描二維碼,該參數(shù)生成一個(gè)靜態(tài)文件itchat.pkl用于存儲(chǔ)登錄狀態(tài)

退出及登錄完成后調(diào)用的特定的方法

這里主要使用的是灰調(diào)函數(shù)的方法,登錄完成后的方法需要賦值在 loginCallback中退出后的方法,需要賦值在 exitCallback中.若不設(shè)置 loginCallback的值, 將會(huì)自動(dòng)刪除二維碼圖片并清空命令行顯示.


import itchat, time
def lc():
    print("Finash Login!")
def ec():
    print("exit")

itchat.auto_login(loginCallback=lc, exitCallback=ec)
time.sleep()
itchat.logout()    #強(qiáng)制退出登錄    

回復(fù)消息

send

  • send(msg="Text Message", toUserName=None)

參數(shù):

  • msg : 文本消息內(nèi)容
  • @fil@path_to_file : 發(fā)送文件
  • @img@path_to_img : 發(fā)送圖片
  • @vid@path_to_video : 發(fā)送視頻
  • toUserName : 發(fā)送對(duì)象, 如果留空, 將發(fā)送給自己.

返回值

  • True or False

實(shí)例代碼

# coding-utf-8
import itchat
itchat.auto_login()
itchat.send("Hello World!")
ithcat.send("@fil@%s" % '/tmp/test.text')
ithcat.send("@img@%s" % '/tmp/test.png')
ithcat.send("@vid@%s" % '/tmp/test.mkv')

send_msg

  • send_msg(msg='Text Message', toUserName=None),其中的的msg是要發(fā)送的文本,toUserName是發(fā)送對(duì)象, 如果留空, 將發(fā)送給自己,返回值為True或者False

實(shí)例代碼

import itchat
itchat.auto_login()
itchat.send_msg("hello world.")

send_file

  • send_file(fileDir, toUserName=None) fileDir是文件路徑, 當(dāng)文件不存在時(shí), 將打印無(wú)此文件的提醒,返回值為True或者False

實(shí)例代碼

mport itchat

itchat.auto_login()
itchat.send_file("/tmp/test.txt")

send_image

  • send_image(fileDir, toUserName=None) 參數(shù)同上

實(shí)例代碼


import itchat

itchat.auto_login()
itchat.send_img("/tmp/test.txt")

send_video

  • send_video(fileDir, toUserName=None) 參數(shù)同上

實(shí)例代碼

import itchat

itchat.auto_login()
itchat.send_video("/tmp/test.txt")

注冊(cè)消息方法

itchat 將根據(jù)接受到的消息類型尋找對(duì)應(yīng)的已注冊(cè)的方法.
如果一個(gè)消息類型沒(méi)有對(duì)應(yīng)的注冊(cè)方法, 該消息將會(huì)被舍棄.
在運(yùn)行過(guò)程中也可以動(dòng)態(tài)注冊(cè)方法, 注冊(cè)方式與結(jié)果不變.

注冊(cè)方法

  • 不帶具體對(duì)象注冊(cè), 將注冊(cè)為普通消息的回復(fù)方法.
import itchat
from itchat.content import *
@itchat.msg_register(TEXT)   #這里的TEXT表示如果有人發(fā)送文本消息,那么就會(huì)調(diào)用下面的方法
def simple_reply(msg):
    #這個(gè)是向發(fā)送者發(fā)送消息
    itchat.send_msg('已經(jīng)收到了文本消息,消息內(nèi)容為%s'%msg['Text'],toUserName=msg['FromUserName'])
    return "T reveived: %s" % msg["Text"]     #返回的給對(duì)方的消息,msg["Text"]表示消息的內(nèi)容
    
  • 帶對(duì)象參數(shù)注冊(cè), 對(duì)應(yīng)消息對(duì)象將調(diào)用該方法,其中isFriendChat表示好友之間,isGroupChat表示群聊,isMapChat表示公眾號(hào)
import itchat
from itchat.content import *

@itchat.msg_register(TEXT, isFriendChat=True, isGroupChat=True,isMpChat=True)
def text_reply(msg):
    msg.user.send("%s : %s" % (mst.type, msg.text))
  • 消息類型
    向注冊(cè)方法傳入的 msg 包含微信返回的字典的所有內(nèi)容.itchat 增加 Text, Type(也就是參數(shù)) 鍵值, 方便操作.
    itcaht.content中包含所有的消息類型參數(shù), 如下表
參數(shù) l類型 Text 鍵值
TEXT 文本 文本內(nèi)容(文字消息)
MAP 地圖 位置文本(位置分享)
CARD 名片 推薦人字典(推薦人的名片)
SHARING 分享 分享名稱(分享的音樂(lè)或者文章等)
PICTURE 下載方法 圖片/表情
RECORDING 語(yǔ)音 下載方法
ATTACHMENT 附件 下載方法
VIDEO 小視頻 下載方法
FRIENDS 好友邀請(qǐng) 添加好友所需參數(shù)
SYSTEM 系統(tǒng)消息 更新內(nèi)容的用戶或群聊的UserName組成的列表
NOTE 通知 通知文本(消息撤回等)

附件的下載與發(fā)送

itchat 的附件下載方法存儲(chǔ)在 msgText 鍵中.
發(fā)送的文件名(圖片給出的默認(rèn)文件名), 都存儲(chǔ)在 msgFileName 鍵中.
下載方法, 接受一個(gè)可用的位置參數(shù)(包括文件名), 并將文件響應(yīng)的存儲(chǔ).
注意:下載的文件存儲(chǔ)在指定的文件中,直接將路徑與FileName連接即可,如msg["Text"]('/tmp/weichat'+msg['FileName'])

@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
    #msg.download(msg['FileName'])   #這個(gè)同樣是下載文件的方式
    msg['Text'](msg['FileName'])      #下載文件
    #將下載的文件發(fā)送給發(fā)送者
    itchat.send('@%s@%s' % ('img' if msg['Type'] == 'Picture' else 'fil', msg["FileName"]), msg["FromUserName"])

群消息

增加了三個(gè)鍵值,如下:

  • isAt 判斷是否 @ 本號(hào)
  • ActualNickName : 實(shí)際 NickName(昵稱)
  • Content : 實(shí)際 Content

測(cè)試程序

import itcaht
from itchat.content import TEXT

@itchat.msg_register(TEXT, isGroupChat=True)
def text_reply(msg):
    if(msg.isAt):    #判斷是否有人@自己
    #如果有人@自己,就發(fā)一個(gè)消息告訴對(duì)方我已經(jīng)收到了信息
    itchat.send_msg("我已經(jīng)收到了來(lái)自{0}的消息,實(shí)際內(nèi)容為{1}".format(msg['ActualNickName'],msg['Text']),toUserName=msg['FromUserName'])

itchat.auto_login()
itchat.run()

注冊(cè)消息的優(yōu)先級(jí)

總的來(lái)說(shuō)就是后面注冊(cè)同種類型的消息會(huì)覆蓋之前注冊(cè)的消息,詳情見(jiàn)文檔https://itchat.readthedocs.io/zh/latest/

消息內(nèi)容

注意:所有的消息內(nèi)容都是可以用鍵值對(duì)來(lái)訪問(wèn)的,如msg["FromUserName]就是查看發(fā)送者,itchat.search_friends(userName=msg['FromUserName'])['NickName']查看的是當(dāng)發(fā)送者昵稱

一般消息

一般的消息都遵循以下的內(nèi)容:

{
    "FromUserName": "",
    "ToUserName": "",
    "Content": "",
    "StatusNotifyUserName": "",
    "ImgWidth": 0,
    "PlayLength": 0,
    "RecommendInfo": {},
    "StatusNotifyCode": 0,
    "NewMsgId": "",
    "Status": 0,
    "VoiceLength": 0,
    "ForwardFlag": 0,
    "AppMsgType": 0,
    "Ticket": "",
    "AppInfo": {},
    "Url": "",
    "ImgStatus": 0,
    "MsgType": 0,
    "ImgHeight": 0,
    "MediaId": "",
    "MsgId": "",
    "FileName": "",
    "HasProductId": 0,
    "FileSize": "",
    "CreateTime": 0,
    "SubMsgType": 0
}

初始化消息

 MsgType: 51
    FromUserName: 自己ID
    ToUserName: 自己ID
    StatusNotifyUserName: 最近聯(lián)系的聯(lián)系人ID
    Content:
        <msg>
            <op id='4'>
                <username>
                    # 最近聯(lián)系的聯(lián)系人
                    filehelper,xxx@chatroom,wxid_xxx,xxx,...
                </username>
                <unreadchatlist>
                    <chat>
                        <username>
                        # 朋友圈
                            MomentsUnreadMsgStatus
                        </username>
                        <lastreadtime>
                            1454502365
                        </lastreadtime>
                    </chat>
                </unreadchatlist>
                <unreadfunctionlist>
                # 未讀的功能賬號(hào)消息,群發(fā)助手,漂流瓶等
                </unreadfunctionlist>
            </op>
        </msg>

文本消息

MsgType: 1
    FromUserName: 發(fā)送方ID
    ToUserName: 接收方ID
    Content: 消息內(nèi)容

圖片消息

itchat 增加了 Text 鍵, 鍵值為 下載該圖片的方法.

MsgType: 3
    FromUserName: 發(fā)送方ID
    ToUserName: 接收方ID
    MsgId: 用于獲取圖片,用于表示每一條消息
    Content:
        <msg>
            <img length="6503" hdlength="0" />
            <commenturl></commenturl>
        </msg>

拓展:如果想要得到Content中的具體內(nèi)容可以使用正則表達(dá)式匹配出來(lái)

視頻消息

**itchat 增加了 Text 鍵, 鍵值為 下載該視頻的方法.

    MsgType: 62
    FromUserName: 發(fā)送方ID
    ToUserName: 接收方ID
    MsgId: 用于獲取小視頻
    Content:
        <msg>
            <img length="6503" hdlength="0" />
            <commenturl></commenturl>
        </msg>

地理位置消息

itchat 增加了 Text 鍵, 鍵值為 該地點(diǎn)的文本形式.

MsgType: 1
    FromUserName: 發(fā)送方ID
    ToUserName: 接收方ID
    Content: http://weixin.qq.com/cgi-bin/redirectforward?args=xxx
    
    OriContent:<?xml version="1.0"?>
<msg>
    <location x="34.195278" y="117.177803" scale="16" label="江蘇省徐州市銅山區(qū)新區(qū)海河路" maptype="0" poiname="江蘇師范大學(xué)大學(xué)生公寓園區(qū)" />
</msg>

名片消息

itchat 增加了Text 鍵, 鍵值為 該調(diào)用 add_friend 需要的屬性.

 MsgType: 42
    FromUserName: 發(fā)送方ID
    ToUserName: 接收方ID
    Content:
        <?xml version="1.0"?>
        <msg bigheadimgurl="" smallheadimgurl="" username="" nickname=""  shortpy="" alias="" imagestatus="3" scene="17" province="" city="" sign="" sex="1" certflag="0" certinfo="" brandIconUrl="" brandHomeUrl="" brandSubscriptConfigUrl="" brandFlags="0" regionCode="" />

    RecommendInfo:
        {
            "UserName": "xxx", # ID,這里的是昵稱
            "Province": "xxx",   
            "City": "xxx",    
            "Scene": 17, 
            "QQNum": 0, 
            "Content": "", 
            "Alias": "xxx", # 微信號(hào)
            "OpCode": 0, 
            "Signature": "", 
            "Ticket": "", 
            "Sex": 0, # 1:男, 2:女
            "NickName": "xxx", # 昵稱
            "AttrStatus": 4293221, 
            "VerifyFlag": 0
        }

下面是添加好友的測(cè)試代碼

@itchat.msg_register(itchat.content.CARD,isFriendChat=True)
def simply(msg):
    print msg['Text']
    print msg['Content']
    itchat.add_friend(userName=msg['Text']['UserName'])  #添加推薦的好友
    print msg['RecommendInfo']
    print msg['RecommendInfo']['UserName']

語(yǔ)音消息

*itchat增加了Text鍵,鍵值為下載該語(yǔ)音文件的方法,下載下來(lái)的是MP3的格式


MsgType: 34
    FromUserName: 發(fā)送方ID
    ToUserName: 接收方ID
    MsgId: 用于獲取語(yǔ)音
    Content:
        <msg>
            <voicemsg endflag="1" cancelflag="0" forwardflag="0" voiceformat="4" voicelength="1580" length="2026" bufid="216825389722501519" clientmsgid="49efec63a9774a65a932a4e5fcd4e923filehelper174_1454602489" fromusername="" />
        </msg>

下載方法:msg['Text'](msg['FileName'])

動(dòng)畫表情

itchat添加了Text鍵,鍵值為下載該圖片表情的方法。
注意:本人親測(cè)對(duì)于一些微信商店提供的表情是不能下載成功的,這里的自帶的表情emoji是屬于TEXT類別的,因此如果將其注冊(cè)為PICTURE消息類型的話是不可以監(jiān)測(cè)到的

  MsgType: 47
    FromUserName: 發(fā)送方ID
    ToUserName: 接收方ID
    Content:
        <msg>
            <emoji fromusername = "" tousername = "" type="2" idbuffer="media:0_0" md5="e68363487d8f0519c4e1047de403b2e7" len = "86235" productid="com.tencent.xin.emoticon.bilibili" androidmd5="e68363487d8f0519c4e1047de403b2e7" androidlen="86235" s60v3md5 = "e68363487d8f0519c4e1047de403b2e7" s60v3len="86235" s60v5md5 = "e68363487d8f0519c4e1047de403b2e7" s60v5len="86235" cdnurl = "http://emoji.qpic.cn/wx_emoji/eFygWtxcoMF8M0oCCsksMA0gplXAFQNpiaqsmOicbXl1OC4Tyx18SGsQ/" designerid = "" thumburl = "http://mmbiz.qpic.cn/mmemoticon/dx4Y70y9XctRJf6tKsy7FwWosxd4DAtItSfhKS0Czr56A70p8U5O8g/0" encrypturl = "http://emoji.qpic.cn/wx_emoji/UyYVK8GMlq5VnJ56a4GkKHAiaC266Y0me0KtW6JN2FAZcXiaFKccRevA/" aeskey= "a911cc2ec96ddb781b5ca85d24143642" ></emoji> 
            <gameext type="0" content="0" ></gameext>
        </msg>

普通鏈接或應(yīng)用分享消息

主要針對(duì)的是分享的文章等等

    MsgType: 49
    AppMsgType: 5
    FromUserName: 發(fā)送方ID
    ToUserName: 接收方ID
    Url: 鏈接地址
    FileName: 鏈接標(biāo)題
    Content:
        <msg>
            <appmsg appid=""  sdkver="0">
                <title></title>
                <des></des>
                <type>5</type>
                <content></content>
                <url></url>
                <thumburl></thumburl>
                ...
            </appmsg>
            <appinfo>
                <version></version>
                <appname></appname>
            </appinfo>
        </msg>

音樂(lè)鏈接消息

主要針對(duì)的是音樂(lè)


MsgType: 49
    AppMsgType: 3
    FromUserName: 發(fā)送方ID
    ToUserName: 接收方ID
    Url: 鏈接地址
    FileName: 音樂(lè)名

    AppInfo: # 分享鏈接的應(yīng)用
        {
            Type: 0, 
            AppID: wx485a97c844086dc9
        }

    Content:
        <msg>
            <appmsg appid="wx485a97c844086dc9"  sdkver="0">
                <title></title>
                <des></des>
                <action></action>
                <type>3</type>
                <showtype>0</showtype>
                <mediatagname></mediatagname>
                <messageext></messageext>
                <messageaction></messageaction>
                <content></content>
                <contentattr>0</contentattr>
                <url></url>
                <lowurl></lowurl>
                <dataurl>
                    http://ws.stream.qqmusic.qq.com/C100003i9hMt1bgui0.m4a?vkey=6867EF99F3684&amp;guid=ffffffffc104ea2964a111cf3ff3edaf&amp;fromtag=46
                </dataurl>
                <lowdataurl>
                    http://ws.stream.qqmusic.qq.com/C100003i9hMt1bgui0.m4a?vkey=6867EF99F3684&amp;guid=ffffffffc104ea2964a111cf3ff3edaf&amp;fromtag=46
                </lowdataurl>
                <appattach>
                    <totallen>0</totallen>
                    <attachid></attachid>
                    <emoticonmd5></emoticonmd5>
                    <fileext></fileext>
                </appattach>
                <extinfo></extinfo>
                <sourceusername></sourceusername>
                <sourcedisplayname></sourcedisplayname>
                <commenturl></commenturl>
                <thumburl>
                    http://imgcache.qq.com/music/photo/album/63/180_albumpic_143163_0.jpg
                </thumburl>
                <md5></md5>
            </appmsg>
            <fromusername></fromusername>
            <scene>0</scene>
            <appinfo>
                <version>29</version>
                <appname>搖一搖搜歌</appname>
            </appinfo>
            <commenturl></commenturl>
        </msg>

群消息

itchat 增加了三個(gè)群聊相關(guān)的鍵值:

  • isAt : 判斷是否 @ 本號(hào)
  • ActualNickName : 實(shí)際 NickName
  • Content : 實(shí)際 Content
MsgType: 1
FromUserName: @@xxx
ToUserName: @xxx
Content:
    @xxx:<br/>xxx

紅包消息

 MsgType: 49
    AppMsgType: 2001
    FromUserName: 發(fā)送方ID
    ToUserName: 接收方ID
    Content: 未知

系統(tǒng)消息

 MsgType: 10000
    FromUserName: 發(fā)送方ID
    ToUserName: 自己ID
    Content:
        "你已添加了 xxx ,現(xiàn)在可以開(kāi)始聊天了。"
        "如果陌生人主動(dòng)添加你為朋友,請(qǐng)謹(jǐn)慎核實(shí)對(duì)方身份。"
        "收到紅包,請(qǐng)?jiān)谑謾C(jī)上查看"

賬號(hào)類型

tchat 為三種賬號(hào)都提供了 整體獲取方法與搜索方法.

好友

get_friends

  • itchat.get_friends() 返回完整的好友列表
  • 每個(gè)好友為一個(gè)字典, 其中第一項(xiàng)為本人的賬號(hào)信息;
  • 傳入update=True, 將更新好友列表并返回, get_friends(update=True)

search_friends

  • itchat.get_friends() 好友搜索,有以下四種方式
  • 僅獲取自己的用戶信息
# 獲取自己的用戶信息,返回自己的屬性字典
itchat.search_friends()
  • 獲取特定 UserName 的用戶信息

# 獲取特定UserName的用戶信息
itchat.search_friends(userName='@abcdefg1234567') 

## 獲取發(fā)送信息的好友的詳細(xì)信息
@itchat.msg_register(itchat.content.TEXT,isFriendChat=True)
def reply(msg):
    print msg['FromUserName']
    print itchat.search_friends(userName=msg['FromUserName'])   #詳細(xì)信息
    print itchat.search_friends(userName=msg['FromUserName'])['NickName']   #獲取昵稱
  • 獲取備注,微信號(hào), 昵稱中的任何一項(xiàng)等于name鍵值的用戶. (可以與下一項(xiàng)配置使用.)

比如在我的微信中有一個(gè)備注為autolife的人,我可以使用這個(gè)方法搜索出詳細(xì)的信息

# 獲取任何一項(xiàng)等于name鍵值的用戶
itchat.search_friends(name='autolife')
  • 獲取備注,微信號(hào), 昵稱分別等于相應(yīng)鍵值的用戶. (可以與上一項(xiàng)配置使用.)
# 獲取分別對(duì)應(yīng)相應(yīng)鍵值的用戶
itchat.search_friends(wechatAccount='littlecodersh')
# 三、四項(xiàng)功能可以一同使用
itchat.search_friends(name='LittleCoder機(jī)器人', wechatAccount='littlecodersh')

update_friend

主要用于好友更新

  • 特定用戶: 傳入用戶UserName, 返回指定用戶的最新信息.
  • 用戶列表: 傳入 UserName 組成的列表, 返回用戶最新信息組成的列表
memberList = itchat.update_friend('@abcdefg1234567')

公眾號(hào)

get_mps

** 將返回完整的工作號(hào)列表**

  • 每個(gè)公眾號(hào)為一個(gè)字典,
  • 傳入 update=True 將更新公眾號(hào)列表, 并返回.

search_mps

  • 獲取特定UserName的公眾號(hào)
# 獲取特定UserName的公眾號(hào),返回值為一個(gè)字典
itchat.search_mps(userName='@abcdefg1234567')
  • 獲取名字中還有特定字符的公眾號(hào).
# 獲取名字中含有特定字符的公眾號(hào),返回值為一個(gè)字典的列表
itchat.search_mps(name='LittleCoder')
  • 當(dāng)兩項(xiàng)都是勇士, 將僅返回特定UserName的公眾號(hào).

群聊

  • get_chatrooms : 返回完整的群聊列表.
  • search_chatrooms : 群聊搜索.
  • update_chatroom : 獲取群聊用戶列表或更新該群聊.
  • 群聊在首次獲取中不會(huì)獲取群聊的用戶列表, 所以需要調(diào)用該命令才能獲取群聊成員.
  • 傳入群聊的 UserName , 返回特定群聊的詳細(xì)信息.
  • 傳入UserName組成的列表, 返回指定用戶的最新信息組成的列表.
memberList = itchat.update_chatroom('@@abcdefg1234567', detailedMember=True)
  • 創(chuàng)建群聊,增加/刪除群聊用戶:
  • 由于之前通過(guò)群聊檢測(cè)是否被好友拉黑的程序, 目前這三個(gè)方法都被嚴(yán)格限制了使用頻率.
  • 刪除群聊需要本賬號(hào)為管理員, 否則無(wú)效.
  • 將用戶加入群聊有直接加入與發(fā)送邀請(qǐng), 通過(guò) useInvitation 設(shè)置.
  • 超過(guò) 40 人的群聊無(wú)法使用直接加入的加入方式.
memberList = itchat.get_frients()[1:]
# 創(chuàng)建群聊, topic 鍵值為群聊名稱.
chatroomUserName = itchat.create_chatroom(memberList, "test chatroom")
# 刪除群聊內(nèi)的用戶
itchat.delete_member_from_chatroom(chatroomUserName, memberList[0])
# 增加用戶進(jìn)入群聊.
itchat.add_member_into_chatroom(chatroomUserName, memberList[0], useInvitation=False)

方法匯總

itchat.add_friend                  
itchat.new_instance                
itchat.add_member_into_chatroom    
itchat.originInstance              
itchat.auto_login                  
itchat.returnvalues                
itchat.check_login                 
itchat.run                         
itchat.components                  
itchat.search_chatrooms            
itchat.config                      
itchat.search_friends              
itchat.configured_reply            
itchat.search_mps                  
itchat.content                     
itchat.send                        
itchat.core                        
itchat.send_file                   
itchat.Core                        
itchat.send_image                  
itchat.create_chatroom             
itchat.send_msg                    
itchat.delete_member_from_chatroom 
itchat.send_raw_msg                
itchat.dump_login_status           
itchat.send_video                  
itchat.get_chatrooms               
itchat.set_alias                   
itchat.get_contact                 
itchat.set_chatroom_name           
itchat.get_friends                 
itchat.set_logging                 
itchat.get_head_img                
itchat.set_pinned                  
itchat.get_mps                     
itchat.show_mobile_login           
itchat.get_msg                     
itchat.start_receiving             
itchat.get_QR                      
itchat.storage                     
itchat.get_QRuuid                  
itchat.update_chatroom             
itchat.instanceList                
itchat.update_friend               
itchat.load_login_status           
itchat.upload_file                 
itchat.log                         
itchat.utils                       
itchat.login                       
itchat.VERSION                     
itchat.logout                      
itchat.web_init                    
itchat.msg_register

實(shí)例

下面是博主寫的一個(gè)程序,該程序的主要功能是監(jiān)控撤回消息,并且如果有消息撤回就會(huì)撤回的消息發(fā)送給你,以后再也不用擔(dān)心看不到好友的撤回的消息了,由于注釋寫的很詳細(xì),因此這里就不在詳細(xì)的講解了,直接貼代碼

代碼

# coding:utf-8
import itchat
from itchat.content import TEXT
from itchat.content import *
import sys
import time
import re

reload(sys)
sys.setdefaultencoding('utf8')
import os

msg_information = {}
face_bug=None  #針對(duì)表情包的內(nèi)容


@itchat.msg_register([TEXT, PICTURE, FRIENDS, CARD, MAP, SHARING, RECORDING, ATTACHMENT, VIDEO],isFriendChat=True, isGroupChat=True, isMpChat=True)
def handle_receive_msg(msg):
    global face_bug
    msg_time_rec = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())   #接受消息的時(shí)間
    msg_from = itchat.search_friends(userName=msg['FromUserName'])['NickName']   #在好友列表中查詢發(fā)送信息的好友昵稱
    msg_time = msg['CreateTime']    #信息發(fā)送的時(shí)間
    msg_id = msg['MsgId']    #每條信息的id
    msg_content = None      #儲(chǔ)存信息的內(nèi)容
    msg_share_url = None    #儲(chǔ)存分享的鏈接,比如分享的文章和音樂(lè)
    print msg['Type']
    print msg['MsgId']
    if msg['Type'] == 'Text' or msg['Type'] == 'Friends':     #如果發(fā)送的消息是文本或者好友推薦
        msg_content = msg['Text']
        print msg_content

    #如果發(fā)送的消息是附件、視屏、圖片、語(yǔ)音
    elif msg['Type'] == "Attachment" or msg['Type'] == "Video" \
            or msg['Type'] == 'Picture' \
            or msg['Type'] == 'Recording':
        msg_content = msg['FileName']    #內(nèi)容就是他們的文件名
        msg['Text'](str(msg_content))    #下載文件
        # print msg_content
    elif msg['Type'] == 'Card':    #如果消息是推薦的名片
        msg_content = msg['RecommendInfo']['NickName'] + '的名片'    #內(nèi)容就是推薦人的昵稱和性別
        if msg['RecommendInfo']['Sex'] == 1:
            msg_content += '性別為男'
        else:
            msg_content += '性別為女'

        print msg_content
    elif msg['Type'] == 'Map':    #如果消息為分享的位置信息
        x, y, location = re.search(
            "<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*", msg['OriContent']).group(1, 2, 3)
        if location is None:
            msg_content = r"緯度->" + x.__str__() + " 經(jīng)度->" + y.__str__()     #內(nèi)容為詳細(xì)的地址
        else:
            msg_content = r"" + location
    elif msg['Type'] == 'Sharing':     #如果消息為分享的音樂(lè)或者文章,詳細(xì)的內(nèi)容為文章的標(biāo)題或者是分享的名字
        msg_content = msg['Text']
        msg_share_url = msg['Url']       #記錄分享的url
        print msg_share_url
    face_bug=msg_content

##將信息存儲(chǔ)在字典中,每一個(gè)msg_id對(duì)應(yīng)一條信息
    msg_information.update(
        {
            msg_id: {
                "msg_from": msg_from, "msg_time": msg_time, "msg_time_rec": msg_time_rec,
                "msg_type": msg["Type"],
                "msg_content": msg_content, "msg_share_url": msg_share_url
            }
        }
    )


##這個(gè)是用于監(jiān)聽(tīng)是否有消息撤回
@itchat.msg_register(NOTE, isFriendChat=True, isGroupChat=True, isMpChat=True)
def information(msg):
    #這里如果這里的msg['Content']中包含消息撤回和id,就執(zhí)行下面的語(yǔ)句
    if '撤回了一條消息' in msg['Content']:
        old_msg_id = re.search("\<msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1)   #在返回的content查找撤回的消息的id
        old_msg = msg_information.get(old_msg_id)    #得到消息
        print old_msg
        if len(old_msg_id)<11:  #如果發(fā)送的是表情包
            itchat.send_file(face_bug,toUserName='filehelper')
        else:  #發(fā)送撤回的提示給文件助手
            msg_body = "告訴你一個(gè)秘密~" + "\n" \
                       + old_msg.get('msg_from') + " 撤回了 " + old_msg.get("msg_type") + " 消息" + "\n" \
                       + old_msg.get('msg_time_rec') + "\n" \
                       + "撤回了什么 ?" + "\n" \
                       + r"" + old_msg.get('msg_content')
            #如果是分享的文件被撤回了,那么就將分享的url加在msg_body中發(fā)送給文件助手
            if old_msg['msg_type'] == "Sharing":
                msg_body += "\n就是這個(gè)鏈接? " + old_msg.get('msg_share_url')

            # 將撤回消息發(fā)送到文件助手
            itchat.send_msg(msg_body, toUserName='filehelper')
            # 有文件的話也要將文件發(fā)送回去
            if old_msg["msg_type"] == "Picture" \
                    or old_msg["msg_type"] == "Recording" \
                    or old_msg["msg_type"] == "Video" \
                    or old_msg["msg_type"] == "Attachment":
                file = '@fil@%s' % (old_msg['msg_content'])
                itchat.send(msg=file, toUserName='filehelper')
                os.remove(old_msg['msg_content'])
            # 刪除字典舊消息
            msg_information.pop(old_msg_id)

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

參考文章

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容