問題
想要將本地監(jiān)控日志發(fā)送到微信或者其他通訊工具上,GitHub上搜了搜,看到了這個(gè):ItChat
簡單使用
ItChat功能包括:微信消息獲取、重復(fù)回答、向指定用戶或群組發(fā)送消息、圖靈機(jī)器人等。調(diào)用的web版微信的接口,并能夠在掃碼登錄后保持一定時(shí)間的登錄狀態(tài)。
消息獲取并全部轉(zhuǎn)發(fā)給特定用戶:
itchat.auto_login(hotReload=True)
users = itchat.search_friends(name=u'此地一為別')
userName = users[0]['UserName']
@itchat.msg_register(itchat.content.TEXT)
def print_content(msg):
print msg.text
itchat.send(msg.text, toUserName = userName)
-
itchat.auto_login(hotReload=True):保持在線狀態(tài) -
itchat.search_friends(name=u'此地一為別'):根據(jù)好友名獲取好友相關(guān)Info,該方法定義為:def search_friends(self, name=None, userName=None, remarkName=None, nickName=None, wechatAccount=None):,各參數(shù)含義可見參考 -
itchat.msg_register,修飾器定義為:def msg_register(self, msgType, isFriendChat=False, isGroupChat=False, isMpChat=False):,可以指定是好友還是群聊、公眾號信息等 -
itchat.send(msg.text, toUserName = userName):發(fā)送消息,當(dāng)userName為'filehelper'時(shí),發(fā)送給微信文件傳輸助手 -
@itchat.msg_register(itchat.content.TEXT)獲取的不僅為text類型的文本,也可以為:- 文本對應(yīng)itchat.content.TEXT
- 圖片對應(yīng)itchat.content.PICTURE
- 語音對應(yīng)itchat.content.RECORDING
- 名片對應(yīng)itchat.content.CARD
向特定群組發(fā)送消息
def sendToGroup(msgContentList, groupNickName):
if len(msgContentList) == 0:
print 'No msg need send'
return True
groups = itchat.search_chatrooms(name = groupNickName)
print groups
groupName = groups[0]['UserName']
for msgContentItem in msgContentList:
itchat.send(msgContentItem, toUserName = groupName)
itchat.auto_login(hotReload=True)
sendToGroup(warnMessageDict['ok'], u'機(jī)器人')
sendToGroup(warnMessageDict['pending'], u'機(jī)器人')
- 發(fā)送前判斷是否存在待發(fā)送消息
-
itchat.search_chatrooms:獲取群聊相關(guān)Info,定義為def search_chatrooms(self, name=None, userName=None):,各參數(shù)含義可見參考 -
warnMessageDict是讀取的監(jiān)控日志信息形成的字典
將文本消息原封不動(dòng)的返回
@itchat.msg_register(itchat.content.TEXT)
def print_content(msg):
return msg['Text']
itchat.auto_login()
itchat.run()
注意開啟自動(dòng)重復(fù)回復(fù)時(shí)使用run方法。
參考文章
itchat API
ItChat GitHub
微信獲取好友、公眾號、群聊的信息
獲取自己的用戶信息,返回自己的屬性字典
itchat.search_friends()
獲取特定UserName的用戶信息
itchat.search_friends(userName='@abcdefg1234567')
獲取任何一項(xiàng)等于name鍵值的用戶
itchat.search_friends(name='wxceshi')
獲取分別對應(yīng)相應(yīng)鍵值的用戶
itchat.search_friends(wechatAccount='wceshi')
三、四項(xiàng)功能可以一同使用:itchat.search_friends(name='wxceshi', wechatAccount='wcceshi')
獲取特定UserName的群聊,返回值為一個(gè)字典
itchat.search_chatrooms(userName='@abcdefg1234567')
獲取名字中含有特定字符的群聊,返回值為一個(gè)字典的列表
itchat.search_chatrooms(name='LittleCoder')
以下方法相當(dāng)于僅特定了UserName
itchat.search_chatrooms(userName='@abcdefg1234567', name='LittleCoder')
獲取特定UserName的公眾號,返回值為一個(gè)字典
itchat.search_mps(userName='@abcdefg1234567')
獲取名字中含有特定字符的公眾號,返回值為一個(gè)字典的列表
itchat.search_mps(name='gzh')
以下方法相當(dāng)于僅特定了UserName
itchat.search_mps(userName='@abcdefg1234567', name='gzh')
群聊用戶列表的獲取方法為update_chatroom。
群聊在首次獲取中不會(huì)獲取群聊的用戶列表,所以需要調(diào)用該命令才能獲取群聊的成員
該方法需要傳入群聊的UserName,返回特定群聊的用戶列表
memberList = itchat.update_chatroom('bcdefg67')