تحليلات لبرامج Telegram المكتوبة بلغة Python

في الوقت الحالي ، بدأت الطفرة في إنشاء روبوتات برقية تتلاشى ، لكن موضوع إنشائها لا يفقد أهميته. تمت كتابة العديد من المكتبات لتسهيل التفاعل مع Telegram Bot API ، ولكن بعد إنشاء البوت لم أجد نصًا برمجيًا (مكتبة) للحصول على إحصائيات البوت. لذلك ، قررت كتابة نص برمجي لجميع برامج التتبُّع في Python. سوف نتلقى إحصائيات عن طريق تسجيل إجراءات المستخدم ومعالجة السجلات بطريقة مناسبة.

متطلبات بيئية


لاستخدام البرنامج النصي ، تحتاج إلى تثبيت المكتبات التالية:

pip install datetime
pip install pandas

كيفية تضمين التحليلات في الروبوت الخاص بك؟


قم بتنزيل البرنامج النصي py من المستودع لملف OS و data.csv الخاص بك. ضعهم في المجلد حيث يوجد برنامج الروبوت الخاص بك.

بعد توصيل المكتبات التي تستخدمها في الملف بنص البوت ، أضف السطر:

import tg_analytic

بعد أوامر البوت ، أضف:

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 على النحو التالي:
إحصائيات <عدد الأيام> <طلب معلمات * >>

* - هناك فرق: "مستخدمين" و "فرق" و "طخت". يمكن استخدامها في وقت واحد. يقدم "المستخدمون" إحصاءات عن الأشخاص لعدد الأيام المطلوب. تقدم "الفرق" إحصاءات حول الفرق لعدد الأيام التي تحتاجها. عند تحديد txt ، ستتلقى ملفًا ، وإلا فستكون الإجابة في برقية.

مثال على استخدام الأمر


الاحصائيات 2 مستخدمي الفريق


الاحصائيات 2 فرق


الاحصائيات 2 مستخدمي الفريق


مما يتكون النص؟


بشكل عام ، إذا لم تكن مهتمًا بالبرنامج النصي ، فيمكنك بالفعل في هذه المرحلة الانتهاء من قراءة المقالة والبدء في تنفيذه في برنامج الروبوت الخاص بك.

الجزء الأول من البرنامج النصي هو تسجيل إجراءات المستخدم. قررت حفظ التاريخ ومعرف المستخدم والأمر الذي يستخدمه فقط:

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])

الجزء الثاني هو معالجة البيانات عند الطلب ومخرجات الإحصائيات اللازمة. نقرأ البيانات من csv في Pandas ، مجمعة حسب المستخدمين والأوامر:

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