微信聊天機器人-存儲好友分享消息


一、背景

    一般大公司都比較重視企業文化,和學習氛圍,這不我們的團隊也是如此,每個人每月微信分享必須超過5篇內容,一個是提高自己的閱讀量,另外還可以把有用的資源分享給其他人。開始記錄的一段時間還算比較順利,可是當大家的分享內容一多的時候,總是發生記漏的情況,后來我就萌生了一個想法,可不可以讓程序來記錄分享數據,這樣就不會發生錯誤了。正好這一段時間剛好在學習python,那就拿這個案例來練練手,網上搜索了一些資料,發現我的需求果然可以用程序來實現,那么還等什么直接開干吧

二、效果展示

1、自動回復

 


2、生成的excel效果展示

三、wxpy

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):
 3     with cond :
 4         if msg.text.startswith(orderHeader) and msg.sender.name in destusers :
 5             print(u'收到一條好友指令消息:', msg.text)
 6             __dealwith_order(msg)
 7         else :
 8             print(u'收到一條好友消息', msg)
 9             if msg.type == PICTURE :
10                 image_cache = image_cache_path + '/' + msg.file_name
11                 msg.get_file(image_cache)
12             tuling.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):
4     with cond :
5         # 接受好友 (msg.card 為該請求的用戶對象)
6         new_friend = bot.accept_friend(msg.card)
7         new_friend.send(u'圖靈接受了你的好友請求,我們可以開始聊天了')

3.7添加后台定時消息

wxpy構造的機器人對象屬於web方式連接,如果長時間沒有消息,可能會掉線,因此我們開啟一個后台線程,隔一段時間發送消息給自己。

 1 def restartTimer() :
 2     global t
 3     if t.is_alive() :
 4         t.stop() 
 5 
 6     t = Timer.Timer(deamonMsg, timerInterval)
 7     t.setDaemon(True)
 8     t.start()
 9 
10 def deamonMsg() :
11     with cond :
12         msgCount = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
13         print(u'發送消息給文件夾助手,保持連接活躍。消息內容:', msgCount)
14         bot.file_helper.send(msgCount)

上述代碼中cond為線程同步條件變量,當使用bot對象發送消息時,需要對bot對象進行保護。

3.8處理消息指令,主要用於控制定時器

 1 def __dealwith_order(msg) :
 2     orderstr = msg.text.lower()#不區分大小寫
 3     orderstr = orderstr[len(orderHeader):]
 4     if orderstr == "1" :
 5         bot.registered.enable(auto_accept_friends)
 6         msg.reply('自動接收好友請求已開啟')
 7     elif orderstr == "2" :
 8         bot.registered.disable(auto_accept_friends)
 9         msg.reply('自動接收好友請求已關閉')
10     elif orderstr == "3" :
11         if t.is_alive() :
12             if t.is_pause() :
13                 msg.reply('后台線程已掛起')
14             else :
15                 msg.reply('后台線程運行正常')
16         else :
17             msg.reply('后台線程已退出')
18     elif orderstr == "4" :
19         t.resume()
20         msg.reply('后台線程已恢復')
21     elif orderstr == "5" :
22         t.pause()
23         msg.reply('后台線程已掛起')
24     elif orderstr == "6" :
25         restartTimer() 
26         msg.reply('后台線程已重啟')
27     elif orderstr.startswith("7 ") :
28         global timerInterval
29         timerInterval = int(orderstr[2:].strip())
30         restartTimer() 
31         msg.reply('后台線程刷新間隔已修改:{0}'.format(timerInterval))
32     else :
33         msg.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) :
2     wbk = openpyxl.load_workbook(fileName)
3     names = wbk.sheetnames
4 else :
5     wbk = openpyxl.Workbook()
6     sheet = wbk.active
7     sheet.title = 'all'
8     names.append('all')
9     FixedSheetWidth(sheet)

3、修改列寬度和內容

 1 headList = ['發送者', '群聊', '接受者', '發送時間', '接受時間','分享內容', '網址']
 2 
 3 def GetCellKey(r, c) : 
 4     cell =  chr(ord('A') + c - 1) + str(r)
 5     return cell
 6     
 7 def FixedSheetWidth(sheet) :
 8     for i in range(0, len(cwidth)):
 9         sheet.column_dimensions[chr(ord('A') + i)].width = cwidth[i]
10 
11 def WriteSheetTitle(sheet) :
12     i = 1
13     for svalue in headList:
14         sheet[GetCellKey(1, i)] = svalue
15         sheet[GetCellKey(1, i)].font = openpyxl.styles.Font(bold = True)
16         i = i + 1

4、添加行數據

 1 def WriteSheetRow(wbk, sheet, rowValueList, rowIndex, isBold):
 2     i = 1
 3     for svalue in rowValueList :
 4         if isBold :
 5             sheet[GetCellKey(rowIndex, i)] = svalue
 6             sheet[GetCellKey(rowIndex, i)].font = openpyxl.styles.Font(bold = True)
 7         else:
 8             sheet[GetCellKey(rowIndex, i)] = svalue
 9         i = i + 1
10 
11     #寫入單獨已用戶名為標簽的sheet
12     name = rowValueList[0]
13     subsheet = None
14     if name not in names :
15         subsheet = wbk.create_sheet(name)
16         WriteSheetTitle(subsheet)
17         FixedSheetWidth(subsheet)
18         names.append(name)
19     else :
20         subsheet = wbk[name]
21 
22     j = 1
23     rowIndex = subsheet.max_row + 1
24     for svalue in rowValueList:
25         if isBold :
26             subsheet[GetCellKey(rowIndex, j)] = svalue
27         else:
28             subsheet[GetCellKey(rowIndex, j)] = svalue
29         j = j + 1
View Code

5、備份用於查看的文件

1 #備份文件
2 file2see = os.path.join(os.getcwd(), generateFileName(''))
3 if not os.path.exists(file2see) :
4     shutil.copyfile(fileName, file2see)
5 else :
6     if os.access(file2see, os.W_OK) :
7         shutil.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):
 7     def __init__(self, fun, seconds):
 8         self.__runTime = seconds
 9         self.__runfun = fun
10         self.__elapsed = 0.0 #流失的時間
11         self.__flag = threading.Event()     # 用於暫停線程的標識
12         self.__flag.set()       # 設置為True
13         self.__running = threading.Event()      # 用於停止線程的標識
14         self.__running.set()      # 將running設置為True
15         threading.Thread.__init__(self)
16         print("initialize Timer completed!")
17 
18     def run(self):
19         while self.__running.isSet():
20             self.__flag.wait()      # 為True時立即返回, 為False時阻塞直到內部的標識位為True后返回
21             time.sleep(0.1) #100ms檢測一次退出狀態
22             self.__elapsed = self.__elapsed + 0.1
23             if self.__elapsed > self.__runTime :
24                 self.__elapsed = 0.0
25                 self.__runfun()
26 
27     def pause(self):
28         self.__flag.clear()     # 設置為False, 讓線程阻塞
29 
30     def is_pause(self) :
31         return  self.__flag.isSet() == False
32 
33     def resume(self):
34         self.__flag.set()    # 設置為True, 讓線程停止阻塞
35 
36     def stop(self):
37         self.__flag.set()       # 將線程從暫停狀態恢復, 如何已經暫停的話
38         self.__running.clear()        # 設置為False
39         self.__elapsed = 0.0
View Code

六、demo下載

  需要全部代碼的到csdn直接下載:自動聊天機器人-存儲好友分享消息

七、參考文章

 

如果您覺得文章不錯,不妨給個打賞,寫作不易,感謝各位的支持。您的支持是我最大的動力,謝謝!!! 

 

  


很重要--轉載聲明

  1. 本站文章無特別說明,皆為原創,版權所有,轉載時請用鏈接的方式,給出原文出處。同時寫上原作者:朝十晚八 or Twowords
  2. 如要轉載,請原文轉載,如在轉載時修改本文,請事先告知,謝絕在轉載時通過修改本文達到有利於轉載者的目的。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM