微信聊天机器人-存储好友分享消息

一、背景

一般大公司都比较重视企业文化,和学习氛围,这不我们的团队也是如此,每个人每月微信分享必须超过5篇内容,一个是提高自己的阅读量,另外还可以把有用的资源分享给其他人。开始记录的一段时间还算比较顺利,可是当大家的分享内容一多的时候,总是发生记漏的情况,后来我就萌生了一个想法,可不可以让程序来记录分享数据,这样就不会发生错误了。正好这一段时间刚好在学习python,那就拿这个案例来练练手,网上搜索了一些资料,发现我的需求果然可以用程序来实现,那么还等什么直接开干吧

二、效果展示

1、自动回复

2、生成的excel效果展示

三、wxpy

wxpy

1、wxpy安装比较简单,直接使用pip命令行安装即可

pip install wxpy

2、wxpy的帮助文档还是比较详细的,网上大多数的文章都是简单的使用了下这个库,没有详细的解释,如果有时间,建议最好自己过一遍帮助文档

3、使用起来也是相当简单

3.1 先导入wxpy模块

from wxpy import *

3.2 构造一个机器人对象(机器人对象可构造多个)

bot = Bot()

3.3 发送消息给文件助手

bot.file_helper.send('你好')

3.4 发送消息给好友

friend = bot.friends().search('朝十晚八')[0]
friend.send('你好')

3.5 自动回复指定好友消息

@bot.register([Friend])
def auto_monitor_friend_all(msg):
 with cond :
     if msg.text.startswith(orderHeader) and msg.sender.name in destusers :
         print(u'收到一条好友指令消息:', msg.text)
         __dealwith_order(msg)
     else :
         print(u'收到一条好友消息', msg)
         if msg.type == PICTURE :
             image_cache = image_cache_path + '/' + msg.file_name
             msg.get_file(image_cache)
         tuling.do_reply(msg)

上述自动回复消息使用了图灵机器人,使用时需要自己去这儿申请一个图灵账号,然后创建一个图灵机器人,得到机器人的apikey,然后构造一个Tuling对象,使用该对象进程回复消息

tuling = Tuling(api_key='3d131c218dd44aa88def35ac37b5c9ab')

3.6 自动添加好友

# 注册好友请求类消息
@bot.register(msg_types = FRIENDS)
def auto_accept_friends(msg):
 with cond :
     # 接受好友 (msg.card 为该请求的用户对象)
     new_friend = bot.accept_friend(msg.card)
     new_friend.send(u'图灵接受了你的好友请求,我们可以开始聊天了')

3.7 添加后台定时消息

wxpy构造的机器人对象属于web方式连接,如果长时间没有消息,可能会掉线,因此我们开启一个后台线程,隔一段时间发送消息给自己。

def restartTimer() :
    global t
    if t.is_alive() :
        t.stop() 

    t = Timer.Timer(deamonMsg, timerInterval)
    t.setDaemon(True)
    t.start()

def deamonMsg() :
    with cond :
        msgCount = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        print(u'发送消息给文件夹助手,保持连接活跃。消息内容:', msgCount)
        bot.file_helper.send(msgCount)

上述代码中cond为线程同步条件变量,当使用bot对象发送消息时,需要对bot对象进行保护。

3.8 处理消息指令,主要用于控制定时器

def __dealwith_order(msg) :
    orderstr = msg.text.lower()#不区分大小写
    orderstr = orderstr[len(orderHeader):]
    if orderstr == "1" :
        bot.registered.enable(auto_accept_friends)
        msg.reply('自动接收好友请求已开启')
    elif orderstr == "2" :
        bot.registered.disable(auto_accept_friends)
        msg.reply('自动接收好友请求已关闭')
    elif orderstr == "3" :
        if t.is_alive() :
            if t.is_pause() :
                msg.reply('后台线程已挂起')
            else :
                msg.reply('后台线程运行正常')
        else :
            msg.reply('后台线程已退出')
    elif orderstr == "4" :
        t.resume()
        msg.reply('后台线程已恢复')
    elif orderstr == "5" :
        t.pause()
        msg.reply('后台线程已挂起')
    elif orderstr == "6" :
        restartTimer() 
        msg.reply('后台线程已重启')
    elif orderstr.startswith("7 ") :
        global timerInterval
        timerInterval = int(orderstr[2:].strip())
        restartTimer() 
        msg.reply('后台线程刷新间隔已修改:{0}'.format(timerInterval))
    else :
        msg.reply('指令:order+序号\n1、开启自动接收好友请求\n2、关闭自动接收好友请求\n3、查看后台线程是否活跃\n4、恢复后台线程\n5、挂起后台线程\n6、重新启动后台线程\n')

四、读写excel

1、使用pip命令安装openpyxl

pip install openpyxl

2、使用openpyxl.load_workbook加载excel文件,如果文件不存在则使用openpyxl.Workbook()构造工作簿,操作完成后使用工作簿save接口保存文件

if os.path.exists(fileName) :
    wbk = openpyxl.load_workbook(fileName)
    names = wbk.sheetnames
else :
    wbk = openpyxl.Workbook()
    sheet = wbk.active
    sheet.title = 'all'
    names.append('all')
    FixedSheetWidth(sheet)

3、修改列宽度和内容

headList = ['发送者', '群聊', '接受者', '发送时间', '接受时间','分享内容', 网址']

def GetCellKey(r, c) : 
    cell =  chr(ord('A') + c - 1) + str(r)
    return cell
    
def FixedSheetWidth(sheet) :
    for i in range(0, len(cwidth)):
        sheet.column_dimensions[chr(ord('A') + i)].width = cwidth[i]

def WriteSheetTitle(sheet) :
    i = 1
    for svalue in headList:
        sheet[GetCellKey(1, i)] = svalue
        sheet[GetCellKey(1, i)].font = openpyxl.styles.Font(bold = True)
        i = i + 1

4、添加行数据

def WriteSheetRow(wbk, sheet, rowValueList, rowIndex, isBold):
    i = 1
    for svalue in rowValueList :
        if isBold :
            sheet[GetCellKey(rowIndex, i)] = svalue
            sheet[GetCellKey(rowIndex, i)].font = openpyxl.styles.Font(bold = True)
        else:
            sheet[GetCellKey(rowIndex, i)] = svalue
        i = i + 1

    #写入单独已用户名为标签的sheet
    name = rowValueList[0]
    subsheet = None
    if name not in names :
        subsheet = wbk.create_sheet(name)
        WriteSheetTitle(subsheet)
        FixedSheetWidth(subsheet)
        names.append(name)
    else :
        subsheet = wbk[name]

    j = 1
    rowIndex = subsheet.max_row + 1
    for svalue in rowValueList:
        if isBold :
            subsheet[GetCellKey(rowIndex, j)] = svalue
        else:
            subsheet[GetCellKey(rowIndex, j)] = svalue
        j = j + 1

5、备份用于查看的文件

#备份文件
file2see = os.path.join(os.getcwd(), generateFileName(''))
if not os.path.exists(file2see) :
    shutil.copyfile(fileName, file2see)
else :
    if os.access(file2see, os.W_OK) :
        shutil.copyfile(fileName, file2see)

五、定时器

定时器主要用于后台定时发送消息给机器人自己,保持自己在线状态

定时器对象使用python的线程对象thread.Thread作为父类,并添加了pause、is_pause、resume和stop接口,使定时器控制起来更方便

# -*- coding: UTF-8 -*-

import time
import threading

class Timer(threading.Thread):
    def __init__(self, fun, seconds):
        self.__runTime = seconds
        self.__runfun = fun
        self.__elapsed = 0.0 #流失的时间
        self.__flag = threading.Event()     # 用于暂停线程的标识
        self.__flag.set()       # 设置为True
        self.__running = threading.Event()      # 用于停止线程的标识
        self.__running.set()      # 将running设置为True
        threading.Thread.__init__(self)
        print("initialize Timer completed!")

    def run(self):
        while self.__running.isSet():
            self.__flag.wait()      # 为True时立即返回, 为False时阻塞直到内部的标识位为True后返回
            time.sleep(0.1) #100ms检测一次退出状态
            self.__elapsed = self.__elapsed + 0.1
            if self.__elapsed > self.__runTime :
                self.__elapsed = 0.0
                self.__runfun()

    def pause(self):
        self.__flag.clear()     # 设置为False, 让线程阻塞

    def is_pause(self) :
        return  self.__flag.isSet() == False

    def resume(self):
        self.__flag.set()    # 设置为True, 让线程停止阻塞

    def stop(self):
        self.__flag.set()       # 将线程从暂停状态恢复, 如何已经暂停的话
        self.__running.clear()        # 设置为False
        self.__elapsed = 0.0

六、demo下载

需要全部代码的到csdn直接下载:自动聊天机器人-存储好友分享消息

七、参考文章

关于wxpy的小实验(一):实现登录微信、消息接收、处理、回复和人脸检测处理反馈

用python读写excel(xlrd、xlwt)

python3 读写Excel


如果您觉得文章不错,不妨给个 打赏,写作不易,感谢各位的支持。您的支持是我最大的动力,谢谢!!!




很重要–转载声明

  1. 本站文章无特别说明,皆为原创,版权所有,转载时请用链接的方式,给出原文出处。同时写上原作者:朝十晚八 or Twowords

  2. 如要转载,请原文转载,如在转载时修改本文,请事先告知,谢绝在转载时通过修改本文达到有利于转载者的目的。


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值