Untitled

 avatar
unknown
plain_text
a year ago
16 kB
9
Indexable
import telebot 
from telebot import types
from bs4 import BeautifulSoup
import requests

# Устанавливаем токен бота 
bot = telebot.TeleBot('6744280328:AAHGjkemKCC6IWtSDaU64gNhmg6sxejuNaA') 
user_data = {}
# URL-адрес страницы с курсами валют Тинькофф
tinkoff_url = "https://www.tinkoff.ru/about/exchange/"

# Классы для элементов с курсами валют
buy_class = "grod3t"  # Класс для покупки доллара и евро
sell_class = "crod3t"  # Класс для продажи доллара и евро

# Обработка команды /start
@bot.message_handler(commands=['start'])
def handle_start(message):
    user = message.from_user
    bot.send_message(message.chat.id, f"Привет, {user.first_name}! Я бот, который знакомит с банковскими услугами по ключевым словам. "
                                      f"Чтобы узнать больше о курсах валют, используйте команду /exchange.")

# Обработка команды /exchange
@bot.message_handler(commands=['exchange'])
def handle_exchange(message):
    markup = types.InlineKeyboardMarkup()
    button_usd = types.InlineKeyboardButton("USD", callback_data="usd")
    button_eur = types.InlineKeyboardButton("EUR", callback_data="eur")
    markup.add(button_usd, button_eur)

    bot.send_message(message.chat.id, "Я умею работать с курсами валют. Выберите валюту:", reply_markup=markup)

# Функция для парсинга страницы и получения курсов валют с сайта Тинькофф
def parse_tinkoff_currency_rates():
    response = requests.get(tinkoff_url)
    soup = BeautifulSoup(response.content, 'html.parser')

    # Находим элементы на странице, содержащие информацию о курсах валют
    buy_rate_element = soup.find("div", class_=buy_class)
    sell_rate_element = soup.find("div", class_=sell_class)

    if buy_rate_element and sell_rate_element:
        buy_rate = float(buy_rate_element.text.strip().replace(',', '.'))
        sell_rate = float(sell_rate_element.text.strip().replace(',', '.'))
        return buy_rate, sell_rate
    else:
        return None, None

# Обработка выбора валюты из клавиатуры /exchange
@bot.callback_query_handler(func=lambda call: call.data in ['usd', 'eur'])
def choose_currency(call):
    currency = call.data

    # Получаем курсы покупки и продажи валюты с сайта Тинькофф
    buy_rate, sell_rate = parse_tinkoff_currency_rates()

    

    # Отправляем результат пользователю
    markup = types.InlineKeyboardMarkup()
    button_calculator = types.InlineKeyboardButton("Калькулятор валют", callback_data="calculator")
    button_start = types.InlineKeyboardButton("В начало", callback_data="start")
    markup.add(button_calculator, button_start)

    message_text = f"Курсы валют в банке Тинькофф:\n\nПокупка {currency}: {buy_rate}\nПродажа {currency}: {sell_rate}"
    bot.send_message(call.message.chat.id, message_text, reply_markup=markup)
# Функция для отправки информации о услуге
def send_service_info(chat_id, service_name, service_info):
    if not service_info:
        return

    markup = types.InlineKeyboardMarkup()
    button = types.InlineKeyboardButton("Перейти на сайт", url=service_info['url'])
    markup.add(button)

    bot.send_message(
        chat_id,
        f"{service_name}:\n{service_info['description']}",
        reply_markup=markup
    )
 

@bot.callback_query_handler(func=lambda call: call.data in ['calculator', 'start']) 
def choose_action(call): 
    action = call.data 
 
    if action == "calculator": 
        handle_calculator(call)
    elif action == "start": 
        handle_start(call.message) 
        
@bot.callback_query_handler(func=lambda call: call.data == 'calculator')
def handle_calculator(call):
    markup = types.InlineKeyboardMarkup()
    button_buy = types.InlineKeyboardButton("Купить", callback_data="buy")
    button_sell = types.InlineKeyboardButton("Продать", callback_data="sell")
    button_start = types.InlineKeyboardButton("В начало", callback_data="start")
    markup.add(button_buy, button_sell)
    markup.add(button_start)

    bot.send_message(call.message.chat.id, "Выберите операцию:", reply_markup=markup)
            
@bot.callback_query_handler(func=lambda call: call.data in ['buy', 'sell'])
def handle_currency_operation(call):
    currency_operation = call.data
    user_id = call.message.chat.id

    user_data_entry = user_data.get(user_id, {})
    user_data_entry["currency_operation"] = currency_operation
    user_data[user_id] = user_data_entry

    currencies_markup = types.InlineKeyboardMarkup()
    button_usd = types.InlineKeyboardButton("USD", callback_data="USD")
    button_eur = types.InlineKeyboardButton("EUR", callback_data="EUR")
    currencies_markup.add(button_usd, button_eur)

    bot.send_message(user_id, "Выберите валюту:", reply_markup=currencies_markup)


@bot.callback_query_handler(func=lambda call: call.data in ['USD', 'EUR'])
def handle_currency_selection(call):
    currency = call.data
    user_id = call.message.chat.id

    user_data_entry = user_data.get(user_id, {})
    user_data_entry["currency"] = currency
    user_data[user_id] = user_data_entry

    bot.send_message(user_id, "Введите сумму в выбранной валюте (например, 100):")


@bot.message_handler(func=lambda message: message.text.isdigit())
def handle_amount_input(message):
    user_id = message.chat.id
    amount = float(message.text)

    user_data_entry = user_data.get(user_id, None)
    if user_data_entry:
        currency_operation = user_data_entry.get("currency_operation")
        currency = user_data_entry.get("currency")

        if currency_operation and currency:
            buy_rate, sell_rate = parse_tinkoff_currency_rates()

            if buy_rate and sell_rate:
                if currency_operation == "buy":
                    result_rub = amount * buy_rate
                else:
                    result_rub = amount * sell_rate

                bot.send_message(
                    user_id,
                    f"Сумма в рублях: {result_rub:.2f} RUB\n\n"
                    f"Сравнение:\n"
                    f"При {currency_operation} {amount} {currency}, вы потратите:\n"
                    f"USD: {amount * buy_rate:.2f} RUB\n"
                    f"EUR: {amount * sell_rate:.2f} RUB"
                )
            else:
                bot.send_message(user_id, "Не удалось получить курсы валют.")
        else:
            bot.send_message(user_id, "Ошибка. Пожалуйста, начните сначала.")
    else:
        bot.send_message(user_id, "Ошибка. Пожалуйста, начните сначала.")
        
# Обработка текстовых сообщений
@bot.message_handler(func=lambda message: True)
def handle_text(message):
    print(f"Received message: {message.text}")
    # Перечень ключевых слов для каждой услуги
    keywords = {
    "Кредиты": ["кредит", "займ", "кредитная карта", "потребительский кредит", "кредит наличными"],
    "Депозиты": ["депозит", "вклад", "вклады с высокими процентами", "сберегательный счет", "долгосрочный депозит"],
    "Ипотека": ["ипотека", "жилье", "недвижимость", "ипотечное кредитование", "ипотечный калькулятор"],
    "Кредитные карты": ["кредитная карта", "пластиковая карта", "кредитный лимит", "карта с кэшбэком", "бесконтактная карта"],
    "Вклады": ["вклад", "депозит", "вклад с капитализацией процентов", "краткосрочный вклад", "вклад на пенсию"],
}

    # Поиск ключевых слов в тексте сообщения
    found_services = []
    for service, service_keywords in keywords.items():
        if any(keyword.lower() in message.text.lower() for keyword in service_keywords):
            found_services.append(service)

# Если найдены ключевые слова, отправляем информацию о найденных услугах
    if found_services:
        for service_name in found_services:
            service_info = get_service_info(service_name)  
            send_service_info(message.chat.id, service_name, service_info)
      
def get_service_info(service_name):
    services_info = {
        "Кредиты":{ "description": "Кредит — это финансовые обязательства двух сторон, одна из которых предоставляет наличные или другие ресурсы, а вторая обещает вернуть их согласно принципам срочности, платности и возвратности.","url": "https://www.tinkoff.ru/credits/"}, 
        "Депозиты":{ "description": "Депозит — один из способов получения прибыли от размещения в банке финансовых активов.","url": "https://www.tinkoff.ru/deposits/"},
        "Ипотека":{ "description": "Ипотека — это залог недвижимости. То есть ипотечный кредит означает, что вы берете у банка деньги под процент (кредит), а гарантией того, что вы вернете эти деньги, становится залог вашего недвижимого имущества: дома, квартиры, земельного участка. Ипотеку обычно воспринимают как кредит на приобретение жилья.","url": "https://www.tinkoff.ru/mortgage/"},
        "Кредитные карты":{ "description": "Кредитная карта — это пластиковый носитель, позволяющий распоряжаться средствами на кредитном счете держателя.","url": "https://www.tinkoff.ru/credit-cards/"},
        "Вклады":{ "description": "Вклад () — сумма средств, которую банк принимает от клиента на определенный или неопределенный срок. Согласно Гражданскому кодексу, обязуется возвратить сумму вклада и выплатить проценты на нее на условиях и в порядке, предусмотренных договором.","url": "https://www.tinkoff.ru/deposits/"},
    }
    return services_info.get(service_name, {}) 

# Функция для отправки информации о услуге
def send_service_info(chat_id, service_name, service_info):
    if not service_info:
        return

    markup = types.InlineKeyboardMarkup()
    button = types.InlineKeyboardButton("Перейти на сайт", url=service_info['url'])
    markup.add(button)

    bot.send_message(
        chat_id,
        f"{service_name}:\n{service_info['description']}",
        reply_markup=markup
    )
 

@bot.callback_query_handler(func=lambda call: call.data in ['calculator', 'start']) 
def choose_action(call): 
    action = call.data 
 
    if action == "calculator": 
        handle_calculator(call)
    elif action == "start": 
        handle_start(call.message) 
        
@bot.callback_query_handler(func=lambda call: call.data == 'calculator')
def handle_calculator(call):
    markup = types.InlineKeyboardMarkup()
    button_buy = types.InlineKeyboardButton("Купить", callback_data="buy")
    button_sell = types.InlineKeyboardButton("Продать", callback_data="sell")
    button_start = types.InlineKeyboardButton("В начало", callback_data="start")
    markup.add(button_buy, button_sell)
    markup.add(button_start)

    bot.send_message(call.message.chat.id, "Выберите операцию:", reply_markup=markup)
            
@bot.callback_query_handler(func=lambda call: call.data in ['buy', 'sell'])
def handle_currency_operation(call):
    currency_operation = call.data
    user_id = call.message.chat.id

    user_data_entry = user_data.get(user_id, {})
    user_data_entry["currency_operation"] = currency_operation
    user_data[user_id] = user_data_entry

    currencies_markup = types.InlineKeyboardMarkup()
    button_usd = types.InlineKeyboardButton("USD", callback_data="USD")
    button_eur = types.InlineKeyboardButton("EUR", callback_data="EUR")
    currencies_markup.add(button_usd, button_eur)

    bot.send_message(user_id, "Выберите валюту:", reply_markup=currencies_markup)


@bot.callback_query_handler(func=lambda call: call.data in ['USD', 'EUR'])
def handle_currency_selection(call):
    currency = call.data
    user_id = call.message.chat.id

    user_data_entry = user_data.get(user_id, {})
    user_data_entry["currency"] = currency
    user_data[user_id] = user_data_entry

    bot.send_message(user_id, "Введите сумму в выбранной валюте (например, 100):")


@bot.message_handler(func=lambda message: message.text.isdigit())
def handle_amount_input(message):
    user_id = message.chat.id
    amount = float(message.text)

    user_data_entry = user_data.get(user_id, None)
    if user_data_entry:
        currency_operation = user_data_entry.get("currency_operation")
        currency = user_data_entry.get("currency")

        if currency_operation and currency:
            buy_rate, sell_rate = parse_tinkoff_currency_rates()

            if buy_rate and sell_rate:
                if currency_operation == "buy":
                    result_rub = amount * buy_rate
                else:
                    result_rub = amount * sell_rate

                bot.send_message(
                    user_id,
                    f"Сумма в рублях: {result_rub:.2f} RUB\n\n"
                    f"Сравнение:\n"
                    f"При {currency_operation} {amount} {currency}, вы потратите:\n"
                    f"USD: {amount * buy_rate:.2f} RUB\n"
                    f"EUR: {amount * sell_rate:.2f} RUB"
                )
            else:
                bot.send_message(user_id, "Не удалось получить курсы валют.")
        else:
            bot.send_message(user_id, "Ошибка. Пожалуйста, начните сначала.")
    else:
        bot.send_message(user_id, "Ошибка. Пожалуйста, начните сначала.")
 
# Запуск бота 
bot.polling(none_stop=True)
Leave a Comment