wxpy 实现微信机器人
生活随笔
收集整理的這篇文章主要介紹了
wxpy 实现微信机器人
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
??wxpy 號稱可能是最優雅的微信個人號 API, 它 在 itchat 的基礎上,通過大量接口優化提升了模塊的易用性,并進行豐富的功能擴展,并且可輕松調用Tuling機器人,搭建屬于自己的聊天機器人。具體請參考 wxpy官方文檔
??基礎講解直接看官方文檔即可,非常簡單明了,這里我就直接講我簡單實現的功能吧!
1. 查看消息撤回
?
def dlDoc(fPath, ra, content, flag):"""download_document:param fPath: filePath:param ra: rawData:param content::param flag::return:"""ra.get('Text')(fPath)bot.file_helper.send(content)if 4 == flag:bot.file_helper.send_image(fPath)elif 7 == flag:bot.file_helper.send_video(fPath)else:bot.file_helper.send_file(fPath)os.remove(fPath)?監聽代碼:
@bot.register(except_self=False, run_async=True, enabled=True) def handleReceiveMsg(msg):"""監聽消息:param msg: 匹配的消息對象:return:"""raw = msg.raw # 原始數據 (dict 數據)mss = msg.bot.messages # 獲取該bot所有messagesle = len(mss)if raw['Status'] == 4:# 獲取消息IDoldmsgid = re.search(re.compile('<msgid>(.*?)</msgid>', re.S), raw['Content']).group(1)for i in range(le - 1, -1, -1):if oldmsgid == str(mss[i].id):name = msg.chat.nameif name is None or name == '':name = msg.chat.nick_nameif mss[i].type == 'Text':bot.file_helper.send(name + '撤回了一條消息:' + mss[i].text)breakelif mss[i].type == 'Map':bot.file_helper.send(name + '撤回了一個位置信息:' + mss[i].location['label'])breakelif mss[i].type == 'Card':card = mss[i].cardname = card.nameif name is None or name == '':name = card.nick_namesex = str(card.sex)if sex == '1':sex = '男'else:sex = '女'bot.file_helper.send(name + '撤回了一張名片:名稱:' + name + ',性別:' + sex)breakelif mss[i].type == 'Sharing':bot.file_helper.send(name + '撤回了一個分享:' + mss[i].url)breakelif mss[i].type == 'Picture':dlDoc(mss[i].file_name, mss[i].raw, name + '撤回了一張圖片,圖片正在加載。。。')breakelif mss[i].type == 'Recording':dlDoc(mss[i].file_name, mss[i].raw, name + '撤回了一條語音,語音正在加載。。。')breakelif mss[i].type == 'Attachment':dlDoc(mss[i].file_name, mss[i].raw, name + '撤回了一個文件,文件正在加載。。。')breakelif mss[i].type == 'Video':dlDoc(mss[i].file_name, mss[i].raw, name + '撤回了一個視頻,視頻正在加載。。。')break2. 查看課程表
?a) 數據結構:這個設計就有點糙了,簡單粗暴的直接寫在內存,大家可以來一個巧妙的數據庫設計,hhh
day_dict = {0: '星期一',1: '星期二',2: '星期三',3: '星期四',4: '星期五',5: '星期六',6: '星期日', }classes = {0: {1: "", 2: "9:55-11:35AM B203 JAVA程序設計", 3: '', 4: '', 5: '18:00-21:00 A214 計算機網絡/Java實驗'},1: {1: "", 2: "9:55-11:35AM B213 技術經濟學", 3: '', 4: '', 5: '18:00-21:00 A314 電子商務實驗'},2: {1: "8:00-9-40 B203 藥學英語", 2: "9:55-11:35AM B201 Matlab",3: '1:30-3.10 A214 matlab實驗', 4: '3:25-5.10 A214 R語言實驗', 5: '18:00-21:00 D207 藥學信息學'},3: {1: "", 2: "9:55-11:35AM B201 項目管理", 3: '1:30-3.10 B201 電子商務', 4: '', 5: ''},4: {1: "", 2: "9:55-11:35AM B213 計算機網絡", 3: '1:30-4:10 B201 GMP', 4: '', 5: ''} }? b) 事件監聽代碼:
@bot.register([file_helper], TEXT, except_self=False) def reply_file_helper(msg):"""課程表查詢:param msg::return:"""if '課程表' in msg.text:weekday_id = localtime(time())[6]if weekday_id < 5:day_classes = classes[weekday_id]text = '今日課程:\r\n'for key, value in day_classes.items():if value:text += (value + '\r\n')msg.reply(text)else:msg.reply('周末沒有課哦!')else:returnembed()3. 人臉檢測
?? a) 人臉檢測運用開源庫 dlib實現
#! /usr/bin/python # _*_ coding: utf-8 _*_ __author__ = 'Jeffery' __date__ = '2018/5/1 23:10' import cv2 import numpy as np import dlibdef rect_to_bb(rect):""":param rect: dlib 臉部區域檢測輸出:return: 返回一個矩形坐標"""x = rect.left()y = rect.top()w = rect.right() - xh = rect.bottom() - yreturn x, y, w, hdef shape_to_np(shape, dtype="int"):""":param shape: dlib臉部特征檢測的輸出:param dtype::return:"""coords = np.zeros((68, 2), dtype=dtype)for i in range(0, 68):coords[i] = (shape.part(i).x, shape.part(i).y)return coordsdef resize(image, width=1200):""":param image: 要檢測的圖片:param width::return:"""r = width * 1.0 / image.shape[1]dim = (width, int(image.shape[0] * r))resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)return resizeddef detect(image_file):""":param image_file: image_file_path:return:"""count = 0image = cv2.imread('./imgs/'+image_file)# image = resize(image, width=1200)gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)detector = dlib.get_frontal_face_detector()rects = detector(gray, 1)predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")for (i, rect) in enumerate(rects):count += 1shape = predictor(gray, rect)shape = shape_to_np(shape)(x, y, w, h) = rect_to_bb(rect)cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)# cv2.putText(image, "Face #{}".format(i + 1), (x - 10, y - 10),# cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)for (x, y) in shape:cv2.circle(image, (x, y), 1, (0, 0, 255), -1)cv2.imwrite('./res_imgs/detect_res_'+image_file, image)return './res_imgs/detect_res_'+image_file, countif __name__ == '__main__':detect('1.png')? b) 事件監聽
????這段代碼必須指出的是它存在一定的問題,請慎用,有時間我再考慮一下性能問題
4. 深夜提醒
?這個就簡單啦
@bot.register(Friend, TEXT, except_self=True) def reply_text(msg):"""回復好友消息:param msg:匹配上的 消息對象:return: msg.reply"""struct_time = localtime(time())if struct_time[3] >= 23 or struct_time[3] <= 7:now_time = strftime('%Y-%m-%d %H:%M:%S', struct_time)weekday = day_dict[struct_time[6]]msg.reply(u'[自動回復]現在是北京時間:' + now_time + " " + weekday +', 時間不早了早點休息,明早一看到消息主人會立刻給您回復')5. Tuling機器人
?Tuling機器人的使用你只需要申請一個api_key即可以使用,當然你也可以用自己的語料庫訓練一個別致的聊天機器人。
bot = Bot(cache_path=False, console_qr=False) tuling = Tuling(api_key='api_key') @bot.register(Friend, TEXT, except_self=True) def reply_text(msg):"""回復好友消息:param msg:匹配上的 消息對象:return: msg.reply"""tuling.do_reply(msg)總結
以上是生活随笔為你收集整理的wxpy 实现微信机器人的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux 环境下配置ftp服务器
- 下一篇: R语言入门2---R语言基础绘图