用Python编写的Telegram机器人分析

目前,电报机器人的创建热潮已开始逐渐消失,但其创建主题并未失去相关性。已经编写了许多库来促进与Telegram Bot API的交互,但是在创建机器人后,我没有找到脚本(库)来获取机器人统计信息。因此,我决定为Python中的所有机器人编写脚本。我们将通过记录用户操作并以方便的方式处理日志来接收统计信息。

环境要求


要使用该脚本,您需要安装以下库:

pip install datetime
pip install pandas

如何在您的机器人中嵌入分析?


存储库中为您的OS和data.csv文件下载py脚本。将它们放在您的漫游器所在的文件夹中。

将文件中使用的库与机器人主体连接后,添加以下行:

import tg_analytic

在bot命令添加后:

tg_analytic.statistics(<id >, <>)

如果您使用的是Telebot库,则它应如下所示:


另外,要直接从漫游器获取统计信息,您需要添加到message_handler(content_types = ['text']):

if message.text[:(  )] == '< >':
        st = message.text.split(' ')
        if 'txt' in st or '' in st:
            tg_analytic.analysis(st,message.chat.id)
            with open('%s.txt' %message.chat.id ,'r',encoding='UTF-8') as file:
                bot.send_document(message.chat.id,file)
                tg_analytic.remove(message.chat.id)
        else:
            messages = tg_analytic.analysis(st,message.chat.id)
            bot.send_message(message.chat.id, messages)

需要发明并输入关键字,以便只有您才能查看漫游器的统计信息。具有已实现的分析功能的电报机器人也存储在资源库中,因此您可以使用示例熟悉如何进行连接。

使用什么命令来获取统计信息?


例如,关键字将为“统计信息”:

    if message.text[:10] == '' or message.text[:10] == 'C':
        st = message.text.split(' ')
        if 'txt' in st or '' in st:
            tg_analytic.analysis(st,message.chat.id)
            with open('%s.txt' %message.chat.id ,'r',encoding='UTF-8') as file:
                bot.send_document(message.chat.id,file)
                tg_analytic.remove(message.chat.id)
        else:
            messages = tg_analytic.analysis(st,message.chat.id)
            bot.send_message(message.chat.id, messages)

bot命令的主体如下:
统计信息<天数> <请求参数* >>

*-有团队:“用户”,“团队”和“ tkht”。可以同时使用。“用户”提供所需天数的人员统计信息。“团队”提供了所需天数的团队统计信息。指定txt时,您将收到一个文件,否则答案以电报形式出现。

命令用法示例


统计2个团队用户


统计2队


统计团队的2位用户


脚本由什么组成?


通常,如果您对脚本不感兴趣,那么在此阶段,您可以完成阅读文章并开始在bot中实现它。

该脚本的第一部分是记录用户操作。我决定只保存日期,用户标识和他使用的命令:

def statistics(user_id, command):
    data = datetime.datetime.today().strftime("%Y-%m-%d")
    with open('data.csv', 'a', newline="", encoding='UTF-8') as fil:
        wr = csv.writer(fil, delimiter=';')
        wr.writerow([data, user_id, command])

第二部分是按需数据处理和必要统计数据的输出。我们从Pandas中的csv中读取数据,按用户和命令分组:

season = int(bid[1])
#   Dataframe
df = pd.read_csv('data.csv', delimiter=';', encoding='utf8')
#     
number_of_users = len(df['id'].unique())
number_of_days = len(df['data'].unique())
#      
df_user = df.groupby(['data', 'id']).count().reset_index().groupby('data').count().reset_index()
list_of_dates_in_df_user = list(df_user['data'])
list_of_number_of_user_in_df_user = list(df_user['id'])
list_of_dates_in_df_user = list_of_dates_in_df_user[-season:]
list_of_number_of_user_in_df_user = list_of_number_of_user_in_df_user[-season:]
#      
df_command = df.groupby(['data', 'command']).count().reset_index()
unique_commands = df['command'].unique()
commands_in_each_day = []
list_of_dates_in_df_command = list(df_command['data'])
list_of_number_of_user_in_df_command = list(df_command['id'])
list_of_name_of_command_in_df_command = list(df_command['command'])
commands_in_this_day = dict()
for i in range(len(list_of_dates_in_df_command)):
     commands_in_this_day[list_of_name_of_command_in_df_command[i]] = list_of_number_of_user_in_df_command[i]
     if i + 1 >= len(list_of_dates_in_df_command) or list_of_dates_in_df_command[i] != list_of_dates_in_df_command[i + 1]:
     commands_in_each_day.append(commands_in_this_day)
     commands_in_this_day = dict()
commands_in_each_day = commands_in_each_day[-season:]

对用户的响应基于上一步的数据:


message_to_user = '    %s %s: \n' % (season, day_type.get(season, ''))
message_to_user += '    %s %s: \n' % (number_of_days, day_type.get(season, ''))
if season > number_of_days:
     season = number_of_days
     message_to_user += '    , \n' \
                        '      \n'
if '' in bid:
    message_to_user += '    : ' + '%s' % number_of_users \
    + ' %s ' % users_type.get(number_of_users, '') + '\n' \
    '   %s %s: \n' % (season, day_type.get(season, ''))
    for days, number, comm_day in zip(list_of_dates_in_df_user, list_of_number_of_user_in_df_user, 
    commands_in_each_day):
      message_to_user += ':%s :%d   :%s\n' % (days, number, comm_day.get('/start', 0))
if '' in bid:
    message_to_user += '    %s %s: \n' %  
    (season,day_type.get(season, ''))
    for days, commands in zip(list_of_dates_in_df_user, commands_in_each_day):
       message_to_user += ':%s\n' % days
       for i in unique_commands:
           if i in commands:
                message_to_user += '%s - %s \n' % (i, commands.get(i))
          else:
                message_to_user += '%s - 0 \n' % i

最后,在编写了响应消息之后,我们检查用户的请求是否存在“ txt”命令,以便决定以哪种格式进行响应:

if 'txt' in bid or '' in bid:
    with open('%s.txt' % user_id, 'w', encoding='UTF-8') as fil:
        fil.write(message_to_user)
        fil.close()
    else:
        return message_to_user

结论


该脚本已经过测试,可以在正常模式下运行。如果您有兴趣了解它在机器人上的实际工作原理,则可以在我的任何机器人上进行测试:@ exchange_minsk_bot,@ pogoda_belarus_bot,@ fast_translate_bot。

关键字:“统计”。

祝您使用愉快!

Source: https://habr.com/ru/post/undefined/


All Articles