天天看点

Python:微信销量上报自动提醒与统计

前言:最近在看统计学,所以很久没写代码了。手痒痒,把之前说的“微信销量上报自动提醒与统计”做出来了,使用效果如下图:

Python:微信销量上报自动提醒与统计
Python:微信销量上报自动提醒与统计

在同目录下准备了2个txt文档,分别放入标准上报模板和需要上报销量的单位,格式如下:

Python:微信销量上报自动提醒与统计
Python:微信销量上报自动提醒与统计

2月15日更新:

1、把自动关机的代码注释掉了,如果需要可以自己打开;

2、增加了重复上报的判断,如果是的话,就发送“**,收到,数据已更新!”

3、新增了模板的前四个字符判断,代替了“销量上报”,可以自定义了;

4、新增了“销量上报群和总结时间.txt”,可以把想要交互的群放在里面,也便于修改;

5、感谢同事胡大师的帮忙,支持多线程了

还有几个问题:

1、我本来想用多线程来自动到时间就统计今日数据+关机的,但是实际测试下来一直不行,等多线程再学一段时间看看能不能优化;

2、对于模板和上报人员的要求比较高,不能有一点错误,否则就会统计不到,我在想如果用正则表达式模糊匹配是否会好一点;

具体代码如下:

#coding=utf8
import itchat
from itchat.content import *
import re
import datetime
import os
import threading
import time


class Test_Thread(threading.Thread):
    # 初始化,时间为time_to_run,字符串类型
    def __init__(self, time_to_run):
        self.end_time = time_to_run
        threading.Thread.__init__(self)
    #每10秒判断一次是否已经总结时间
    def run(self):
        a = True
        while(a):
            #每次等待一秒后判断当前时间是否到达,比如22:00
            time.sleep(10)
            current_time = datetime.datetime.now()
            current_time_format = current_time.hour * 3600 + current_time.minute * 60 + current_time.second
            end_time_format = int(self.end_time.split(':')[0]) * 3600 + int(self.end_time.split(':')[1]) * 60
            if current_time_format >= end_time_format:
                itchat.get_chatrooms()
                room_report = itchat.search_chatrooms(name=qun_name)[0]['UserName']
                alt_store_str = '、'.join(alt_store)
                not_alt_store_str = '、'.join(not_alt_store)
                itchat.send('今日共收到{}家门店的销量上报,已收到:{},未收到:{}!'.format(len(alt_store), alt_store_str, not_alt_store_str), toUserName=room_report)
                total_muban = today_count()
                itchat.send(total_muban, toUserName=room_report)
                a = False
                # os.system("shutdown -s -t 0") #自动关机

def time_to_run(end_time):
    '''判断是否到某一个时间
    end_time, 类似22:00'''
    current_time = datetime.datetime.now()
    current_time_format = current_time.hour * 3600 + current_time.minute * 60 + current_time.second
    end_time_format = int(end_time.split(':')[0]) * 3600 + int(end_time.split(':')[1]) * 60
    if current_time_format >= end_time_format : return 1
    else: return 0

# 在注册时增加isGroupChat=True将判定为群聊回复
@itchat.msg_register(TEXT, isGroupChat = True)
def groupchat_reply(msg):
    '''
    msg['Content'],信息内容
    msg['FromUserName'],信息的发送方ID,如果是群信息的话就是群ID,是一长串数字,没有msg['NickName'],所以要用chatroom_dict()进行转化
    msg['ActualNickName'],信息发送者的昵称,注意如果是群里的话就是群里信息的实际发送者
    '''
    d = chatroom_dict()
    chatroom_id = msg['FromUserName']
    chatroom_name = d[chatroom_id]
    if chatroom_name == qun_name: #这里指定了群,且该群必须保存在通讯录里!
        text = msg['Content']
        if text == '今日销量统计':
            alt_store_str = '、'.join(alt_store)
            not_alt_store_str = '、'.join(not_alt_store)
            itchat.send('今日共收到{}家门店的销量上报,已收到:{},未收到:{}!'.format(len(alt_store), alt_store_str,
                                                                        not_alt_store_str), toUserName=chatroom_id)
            total_muban = today_count()
            itchat.send(total_muban, toUserName=chatroom_id)
            # os.system("shutdown -s -t 0") #自动关机
        elif str(text).startswith(muban_start):
        #把获得文字中根据模板提取关键字
            store_num_list = []
            for i in range(0, muban_count):
                store_num_list.append(re.search(new_muban, text).group(i + 1))
            store = store_num_list[0]
            if store in store_dict:
                store_dict[store] = store_num_list[1:]
                if store in alt_store:
                    itchat.send('{},收到,数据已更新!'.format(store), toUserName=chatroom_id)
                else:
                    alt_store.append(store)
                    alt_store_str = '、'.join(alt_store)
                    not_alt_store.remove(store)
                    not_alt_store_str = '、'.join(not_alt_store)
                    itchat.send('{},收到!\n目前已收到{}的销量,尚未收到{},请在{}前上报,谢谢!'.format(store, alt_store_str, not_alt_store_str, summary_time), toUserName=chatroom_id)

def chatroom_dict():
    '''获得群的ID和群名称,并组合成字典'''
    d = {}
    chatrooms = itchat.get_chatrooms(update=True)
    for chatroom in chatrooms:
        d[chatroom['UserName']] = chatroom['NickName']
    return d

def run_itchat():
    '''运行微信'''
    itchat.auto_login(True)
    itchat.run()

def get_muban():
    '''读取模板内容'''
    with open("销量上报模板.txt", "r") as file:
        muban = file.read()
    return muban

def get_store():
    '''获取需要上报销量的单位名称并组成列表和字典'''
    with open("销量上报单位.txt", "r") as file:
        not_alt_store = []
        store_dict = {}
        for line in file.readlines():
            line = line.strip()
            not_alt_store.append(line)
            store_dict[line] = []
    return not_alt_store, store_dict

def get_qun():
    '''获得要交互的群名称和总结时间'''
    with open("销量上报群和总结时间.txt", "r") as file:
        qun_list = []
        for line in file.readlines():
            line = line.strip()
            qun_list.append(line)
    return qun_list

def today_count():
    '''合并统计今天已上报的销量'''
    today_value_list = []
    for key in store_dict:
        if store_dict[key] == []:
            continue
        else:
            today_value_list.append(store_dict[key])
    new_list = list_value_combine(today_value_list, muban_count)
    total_muban = string_replace(muban, muban_count, new_list)
    return total_muban

def list_value_combine(old_list, muban_count):
    '''按顺序合并列表中多个子列表的值,并获得一个新的列表'''
    new_list = []
    old_len = len(old_list)
    for j in range(muban_count-1):
        temp_num = 0
        for i in range(old_len):
            temp_num += int(old_list[i][j])
        new_list.append(temp_num)
    return new_list

def string_replace(muban, muban_count, new_list):
    '''根据列表中的元素依次替换字符串中的*'''
    for i in range(muban_count):
        temp = str(muban).find('*')
        if i ==0:
            muban ='今日已上报销量合计:' + muban[temp+1:]
        else:
            muban = muban[:temp] + str(new_list[i-1]) + muban[temp+1:]
    return muban

if __name__ == '__main__':
    muban = get_muban()
    muban_start = muban[:4]
    new_muban = muban.replace('*', '(.*?)') #变成正则表达式的样式
    muban_count = muban.count('*')
    qun_name = get_qun()[0] #交互群的名称
    summary_time = get_qun()[1] #总结的时间
    store_dict = get_store()[1] #门店字典,key是名称,value是以列表形式展现的销量数据
    not_alt_store = get_store()[0] #尚未上报销量的门店列表
    alt_store = [] #已经上报了销量的门店列表
    cal1 = Test_Thread(summary_time)  # 定义cal1对象,为test_thread类派生,定义22点运行
    cal1.start()
    run_itchat()