i229194964
@i229194964
Веб разработчик

После решение капчи бот должен предлагать подписаться на каналы почему это не делает?

from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, CallbackContext, MessageHandler, Filters, ConversationHandler
import logging
import random

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)

SHOW_ACTIONS, ENTER_CAPTCHA, SUBSCRIBE_CHANNELS = range(3)

captcha_answers = {}

def start(update: Update, context: CallbackContext) -> int:
    keyboard = [
        [InlineKeyboardButton(" Заработать", callback_data='earn')],
        [InlineKeyboardButton(" Активировать промокод", callback_data='promo')],
        [InlineKeyboardButton(" Баланс", callback_data='balance')],
        [InlineKeyboardButton(" Статистика", callback_data='stats')],
        [InlineKeyboardButton("❓ О боте", callback_data='about')],
        [InlineKeyboardButton(" Получить 100р", callback_data='bonus')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text('Выберите действие:', reply_markup=reply_markup)
    return SHOW_ACTIONS

def button(update: Update, context: CallbackContext) -> None:
    query = update.callback_query
    query.answer()
    data = query.data

    if data == 'earn':
        send_captcha(update, context)
    elif data in ['promo', 'balance', 'stats', 'about', 'bonus']:
        query.edit_message_text(text=f"Вы выбрали {data}. Эта функция находится в разработке.")
    else:
        query.edit_message_text(text="Неизвестная команда.")

def send_captcha(update: Update, context: CallbackContext):
    user_id = update.effective_user.id
    num1 = random.randint(1, 10)
    num2 = random.randint(1, 10)
    captcha_solution = num1 + num2
    captcha_answers[user_id] = captcha_solution
    update.effective_message.reply_text(f'Пожалуйста, решите задачу для верификации: {num1} + {num2} = ?')
    return ENTER_CAPTCHA

def enter_captcha(update: Update, context: CallbackContext) -> int:
    user_answer = int(update.message.text)
    user_id = update.effective_user.id

    if captcha_answers.get(user_id) == user_answer:
        del captcha_answers[user_id]
        show_channels(update, context)
        return SUBSCRIBE_CHANNELS
    else:
        update.effective_message.reply_text("Неправильный ответ. Попробуйте снова.")
        return ENTER_CAPTCHA

def show_channels(update: Update, context: CallbackContext):
    keyboard = [
        [InlineKeyboardButton("Подписаться на канал", url='https://t.me/yourchannel')],
        [InlineKeyboardButton("Я подписался", callback_data='actions')]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.effective_message.reply_text('Пожалуйста, подпишитесь на канал:', reply_markup=reply_markup)

def actions(update: Update, context: CallbackContext):
    # После подписки пользователь может выполнить другие действия
    update.callback_query.answer()
    update.callback_query.edit_message_text(text="Вы успешно подписались. Выберите следующее действие.")

def main():
    TOKEN = ""
    updater = Updater(TOKEN, use_context=True)

    conv_handler = ConversationHandler(
        entry_points=[CommandHandler("start", start)],
        states={
            SHOW_ACTIONS: [CallbackQueryHandler(button)],
            ENTER_CAPTCHA: [MessageHandler(Filters.text & (~Filters.command), enter_captcha)],
            SUBSCRIBE_CHANNELS: [CallbackQueryHandler(actions, pattern='^actions$')],
        },
        fallbacks=[CommandHandler('start', start)]
    )

    updater.dispatcher.add_handler(conv_handler)

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()
  • Вопрос задан
  • 64 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы