微信聊天機器人-儲存好友分享訊息
一、背景
一般大公司都比較重視企業文化,和學習氛圍,這不我們的團隊也是如此,每個人每月微信分享必須超過5篇內容,一個是提高自己的閱讀量,另外還可以把有用的資源分享給其他人。開始記錄的一段時間還算比較順利,可是當大家的分享內容一多的時候,總是發生記漏的情況,後來我就萌生了一個想法,可不可以讓程式來記錄分享資料,這樣就不會發生錯誤了。正好這一段時間剛好在學習python,那就拿這個案例來練練手,網上搜索了一些資料,發現我的需求果然可以用程式來實現,那麼還等什麼直接開幹吧
二、效果展示
1、自動回覆
2、生成的excel效果展示
三、wxpy
ofollow,noindex">wxpy
1、wxpy安裝比較簡單,直接使用pip命令列安裝即可:pip install wxpy
2、wxpy的幫助文件還是比較詳細的,網上大多數的文章都是簡單的使用了下這個庫,沒有詳細的解釋,如果有時間,建議最好自己過一遍幫助文件
3、使用起來也是相當簡單
3.1先匯入wxpy模組
1 from wxpy import *
3.2構造一個機器人物件 (機器人物件可構造多個)
1 bot = Bot()
3.3傳送訊息給檔案助手
1 bot.file_helper.send( ' 你好 ' )
3.4傳送訊息給好友
1 friend = bot.friends().search('朝十晚八')[0] 2 friend.send('你好')
3.5自動回覆指定好友訊息
1 @bot.register([Friend]) 2 def auto_monitor_friend_all(msg): 3with cond : 4if msg.text.startswith(orderHeader) and msg.sender.name in destusers : 5print(u'收到一條好友指令訊息:', msg.text) 6__dealwith_order(msg) 7else : 8print(u'收到一條好友訊息', msg) 9if msg.type == PICTURE : 10image_cache = image_cache_path + '/' + msg.file_name 11msg.get_file(image_cache) 12tuling.do_reply(msg)
上述自動回覆訊息使用了圖靈機器人,使用時需要自己去 這兒 申請一個圖靈賬號,然後建立一個圖靈機器人,得到機器人的apikey,然後構造一個Tuling物件,使用該物件程序回覆訊息
1 tuling = Tuling(api_key='3d131c218dd44aa88def35ac37b5c9ab')
3.6自動新增好友
1 # 註冊好友請求類訊息 2 @bot.register(msg_types = FRIENDS) 3 def auto_accept_friends(msg): 4with cond : 5# 接受好友 (msg.card 為該請求的使用者物件) 6new_friend = bot.accept_friend(msg.card) 7new_friend.send(u'圖靈接受了你的好友請求,我們可以開始聊天了')
3.7新增後臺定時訊息
wxpy構造的機器人物件屬於web方式連線,如果長時間沒有訊息,可能會掉線,因此我們開啟一個後臺執行緒,隔一段時間傳送訊息給自己。
1 def restartTimer() : 2global t 3if t.is_alive() : 4t.stop() 5 6t = Timer.Timer(deamonMsg, timerInterval) 7t.setDaemon(True) 8t.start() 9 10 def deamonMsg() : 11with cond : 12msgCount = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') 13print(u'傳送訊息給資料夾助手,保持連線活躍。訊息內容:', msgCount) 14bot.file_helper.send(msgCount)
上述程式碼中cond為執行緒同步條件變數,當使用bot物件傳送訊息時,需要對bot物件進行保護。
3.8處理訊息指令,主要用於控制定時器
1 def __dealwith_order(msg) : 2orderstr = msg.text.lower()#不區分大小寫 3orderstr = orderstr[len(orderHeader):] 4if orderstr == "1" : 5bot.registered.enable(auto_accept_friends) 6msg.reply('自動接收好友請求已開啟') 7elif orderstr == "2" : 8bot.registered.disable(auto_accept_friends) 9msg.reply('自動接收好友請求已關閉') 10elif orderstr == "3" : 11if t.is_alive() : 12if t.is_pause() : 13msg.reply('後臺執行緒已掛起') 14else : 15msg.reply('後臺執行緒執行正常') 16else : 17msg.reply('後臺執行緒已退出') 18elif orderstr == "4" : 19t.resume() 20msg.reply('後臺執行緒已恢復') 21elif orderstr == "5" : 22t.pause() 23msg.reply('後臺執行緒已掛起') 24elif orderstr == "6" : 25restartTimer() 26msg.reply('後臺執行緒已重啟') 27elif orderstr.startswith("7 ") : 28global timerInterval 29timerInterval = int(orderstr[2:].strip()) 30restartTimer() 31msg.reply('後臺執行緒重新整理間隔已修改:{0}'.format(timerInterval)) 32else : 33msg.reply('指令:order+序號\n1、開啟自動接收好友請求\n2、關閉自動接收好友請求\n3、檢視後臺執行緒是否活躍\n4、恢復後臺執行緒\n5、掛起後臺執行緒\n6、重新啟動後臺執行緒\n') View Code
四、讀寫excel
1、使用pip命令安裝openpyxl:pip install openpyxl
2、使用openpyxl.load_workbook載入excel檔案,如果檔案不存在則使用openpyxl.Workbook()構造工作簿,操作完成後使用工作簿save介面儲存檔案
1 if os.path.exists(fileName) : 2wbk = openpyxl.load_workbook(fileName) 3names = wbk.sheetnames 4 else : 5wbk = openpyxl.Workbook() 6sheet = wbk.active 7sheet.title = 'all' 8names.append('all') 9FixedSheetWidth(sheet)
3、修改列寬度和內容
1 headList = ['傳送者', '群聊', '接受者', '傳送時間', '接受時間','分享內容', '網址'] 2 3 def GetCellKey(r, c) : 4cell =chr(ord('A') + c - 1) + str(r) 5return cell 6 7 def FixedSheetWidth(sheet) : 8for i in range(0, len(cwidth)): 9sheet.column_dimensions[chr(ord('A') + i)].width = cwidth[i] 10 11 def WriteSheetTitle(sheet) : 12i = 1 13for svalue in headList: 14sheet[GetCellKey(1, i)] = svalue 15sheet[GetCellKey(1, i)].font = openpyxl.styles.Font(bold = True) 16i = i + 1
4、新增行資料
1 def WriteSheetRow(wbk, sheet, rowValueList, rowIndex, isBold): 2i = 1 3for svalue in rowValueList : 4if isBold : 5sheet[GetCellKey(rowIndex, i)] = svalue 6sheet[GetCellKey(rowIndex, i)].font = openpyxl.styles.Font(bold = True) 7else: 8sheet[GetCellKey(rowIndex, i)] = svalue 9i = i + 1 10 11#寫入單獨已使用者名稱為標籤的sheet 12name = rowValueList[0] 13subsheet = None 14if name not in names : 15subsheet = wbk.create_sheet(name) 16WriteSheetTitle(subsheet) 17FixedSheetWidth(subsheet) 18names.append(name) 19else : 20subsheet = wbk[name] 21 22j = 1 23rowIndex = subsheet.max_row + 1 24for svalue in rowValueList: 25if isBold : 26subsheet[GetCellKey(rowIndex, j)] = svalue 27else: 28subsheet[GetCellKey(rowIndex, j)] = svalue 29j = j + 1 View Code
5、備份用於檢視的檔案
1 #備份檔案 2 file2see = os.path.join(os.getcwd(), generateFileName('')) 3 if not os.path.exists(file2see) : 4shutil.copyfile(fileName, file2see) 5 else : 6if os.access(file2see, os.W_OK) : 7shutil.copyfile(fileName, file2see)
五、定時器
定時器主要用於後臺定時傳送訊息給機器人自己,保持自己線上狀態
定時器物件使用python的執行緒物件thread.Thread作為父類,並添加了pause、is_pause、resume和stop介面,使定時器控制起來更方便
1 # -*- coding: UTF-8 -*- 2 3 import time 4 import threading 5 6 class Timer(threading.Thread): 7def __init__(self, fun, seconds): 8self.__runTime = seconds 9self.__runfun = fun 10self.__elapsed = 0.0 #流失的時間 11self.__flag = threading.Event()# 用於暫停執行緒的標識 12self.__flag.set()# 設定為True 13self.__running = threading.Event()# 用於停止執行緒的標識 14self.__running.set()# 將running設定為True 15threading.Thread.__init__(self) 16print("initialize Timer completed!") 17 18def run(self): 19while self.__running.isSet(): 20self.__flag.wait()# 為True時立即返回, 為False時阻塞直到內部的標識位為True後返回 21time.sleep(0.1) #100ms檢測一次退出狀態 22self.__elapsed = self.__elapsed + 0.1 23if self.__elapsed > self.__runTime : 24self.__elapsed = 0.0 25self.__runfun() 26 27def pause(self): 28self.__flag.clear()# 設定為False, 讓執行緒阻塞 29 30def is_pause(self) : 31returnself.__flag.isSet() == False 32 33def resume(self): 34self.__flag.set()# 設定為True, 讓執行緒停止阻塞 35 36def stop(self): 37self.__flag.set()# 將執行緒從暫停狀態恢復, 如何已經暫停的話 38self.__running.clear()# 設定為False 39self.__elapsed = 0.0 View Code
六、demo下載
需要全部程式碼的到csdn直接下載: 自動聊天機器人-儲存好友分享訊息