Search code examples
pythontelegramtelegram-bottelebot

/stats command not working in telegram bot


I am writing a bot that will display messages found by keywords in the LAN - this system is fully functional, but I decided to add the /stats command and the bot ignores it!

Even print does not output anything, as if the command does not exist at all

import telebot
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
import time

# Вставьте здесь токен вашего бота
bot_token = ''

# Создаем экземпляр бота
bot = telebot.TeleBot(bot_token)

# Словарь для хранения статистики
statistics = {}
total_messages = 0
unique_users = set()

# Обработчик для команды /start
@bot.message_handler(commands=['start'])
def send_welcome(message):
    bot.reply_to(message, "Привет! Я бот, который будет отправлять сообщения из группы, в личную переписку!")

# Обработчик для всех входящих сообщений
@bot.message_handler(func=lambda message: True)
def echo_all(message):
    global total_messages
    
    # Здесь указываем слова и хештеги, по которым будем искать
    keywords = ['сайт']
    
    # Проверяем, содержит ли сообщение указанные слова или хештеги
    for keyword in keywords:
        if keyword.lower() in message.text.lower() or f'#{keyword}' in message.text:
            # Отправляем сообщение в личную переписку
            chat_id = 'CHAT_ID'
            username = message.from_user.username
            text = f"Найдено сообщение с ключевым словом/хештегом '{keyword}':\n\n{message.text}"
            keyboard = [[InlineKeyboardButton("Написать заказчику", url=f"https://t.me/{username}")]]
            reply_markup = InlineKeyboardMarkup(keyboard)
            bot.send_message(chat_id, text, reply_markup=reply_markup)

            # Увеличиваем счетчик статистики для данного ключевого слова
            if keyword in statistics:
                statistics[keyword] += 1
            else:
                statistics[keyword] = 1
            
            # Увеличиваем общий счетчик сообщений
            total_messages += 1
            
            # Добавляем пользователя в список уникальных пользователей
            unique_users.add(message.from_user.id)

            break

@bot.message_handler(commands=['stats'])
def send_stats(message):
    # Генерируем текст статистики
    stats_text = "Статистика по ключевым словам:\n\n"
    for keyword, count in statistics.items():
        stats_text += f"{keyword}: {count}\n"

    # Добавляем информацию о количестве уникальных пользователей
    unique_users_count = len(unique_users)
    stats_text += f"\nКоличество уникальных пользователей: {unique_users_count}"

    # Добавляем информацию о общем количестве сообщений
    stats_text += f"\nОбщее количество сообщений: {total_messages}"

    # Выводим статистику на консоль
    print(stats_text)

    # Отправляем статистику в личную переписку
    chat_id = 'CHAT_ID'
    bot.send_message(chat_id, stats_text)

# Запускаем бота
bot.polling()

I tried to change the command, changed the system of counters, added logging via txt and added print for tracking. However, everything is empty: none of these methods helped me track down what the problem is, the bot simply ignores this command, does not read it


Solution

  • I didn't use telebot but it seems the problem is that you define echo_all first, which intercepts all updates (@bot.message_handler(func=lambda message: True)).

    Try putting the definition of send_stats before echo_all