def aplying_target(update, context):  # add_crypto_step_3
    """Подтверждаем таргет и выставляем его."""

    if update.message.text != 'Да':
        update.message.reply_text('Хорошо.', reply_markup=main_menu_keyboard())
        clear_all_crypto(update, context)
        return ConversationHandler.END
    else:
        context.user_data['ticker'][1] = context.user_data['ticker'][1][
            0] + f"/{context.user_data['ticker'][1][1]}"
        result = Asset().add_asset(context.user_data['ticker'])
        if result:
            # Забираем ранее сохранённую пару и таргет.
            ticker_pair = context.user_data['ticker'][1]
            target_price = context.user_data['ticker'][5]
            # Формируем сообщение.
            message = f'Вы получите уведомление, когда пара {ticker_pair}\n'
            message += f"дотстигнет цены - {target_price} {ticker_pair.split('/')[1]}"
            update.message.reply_text(message,
                                      reply_markup=main_menu_keyboard())

            # TODO: Передаём в Celery задачу.
            #set_alert.delay(ticker_pair[0], ticker_pair[1], target_price)

            clear_all_crypto(update, context)
            return ConversationHandler.END
def closing_order(update, context):
    """Закрываем ордер."""

    if update.message.text != 'Да':
        update.message.reply_text('Что дальше?',
                                  reply_markup=main_menu_keyboard())
        clear_all_crypto(update, context)
        return ConversationHandler.END

    # Cохраняем выбранный ордер для закрытия.
    order_count_for_close = context.user_data['order_count_for_close']
    # Забираем пару тикеров для закрытия ордера в формате 'ETCUSDT'.
    symbol = context.user_data['open_orders'][order_count_for_close -
                                              1].get('symbol')
    # Забираем 'orderId' ордера для его закрытия.
    orderId = context.user_data['open_orders'][order_count_for_close -
                                               1].get('orderId')

    if binance_client.close_order(symbol, orderId) is None:
        update.message.reply_text('Упс! Возникла ошибка.',
                                  reply_markup=main_menu_keyboard())
    else:
        update.message.reply_text("Ордер закрыт!",
                                  reply_markup=main_binance_keyboard())
        clear_all_crypto(update, context)
        return ConversationHandler.END
def choosing_order_side(update, context):
    """
    Проверяем выбранную сторону сделки.
    Доступны 'Купить', 'Продать'.
    """

    # Забираем ранее сохранённые балансы пар.
    ticker_1_balance = context.user_data['order_info']['ticker_1_balance']
    ticker_2_balance = context.user_data['order_info']['ticker_2_balance']

    if update.message.text not in ORDERS_SIDE:
        update.message.reply_text(
                'Пожалуйста, выберите сторону сделки или нажмите "Отмена".',
                reply_markup=buy_sell_keyboard(ticker_1_balance, ticker_2_balance)
                )
        return 'set_step_3'

    context.user_data['order_info'].pop('ticker_1_balance')
    context.user_data['order_info'].pop('ticker_2_balance')

    # Cохраняем сторону сделки.
    context.user_data['order_info']['order_side'] = update.message.text
    # Возвращаем в начало шага если баланс выбранного тикера равен 0.
    allowed_balance = ''
    if context.user_data['order_info']['order_side'] == 'sell':
        if float(ticker_2_balance.split()[0]) == 0:
            update.message.reply_text(
                'Недостаточно средств.', keyboard_markup=main_menu_keyboard()
                )
            return 'set_step_3'
        allowed_balance += ticker_2_balance
    else:
        if float(ticker_1_balance.split()[0]) == 0:
            update.message.reply_text(
                'Недостаточно средств.', keyboard_markup=main_menu_keyboard()
                )
            return 'set_step_3'
        allowed_balance += ticker_1_balance

    if context.user_data['order_info']['order_type'] == 'limit':
        update.message.reply_text(
            'Введите цену.', reply_markup=cancel_keyboard()
        )
        return 'set_step_4'

    update.message.reply_text(
        f'Выберите количество.\n Доступно - {allowed_balance}',
        reply_markup=quantity_keyboard()
    )
    return 'set_step_5'
Esempio n. 4
0
def unknown_text(update, context):
    """
    Функция, обрабатывающая любой текст, который не является текстом из
    кнопок, которые начинают Conversation
    """
    reply = ("Выберите доступный раздел.")
    update.message.reply_text(reply, reply_markup=main_menu_keyboard())
def choosing_order_for_close(update, context):
    """Спрашиваем у пользователя какой ордер закрыть."""

    # Получаем список открытых ордеров.
    open_orders = binance_client.get_all_open_orders()

    if open_orders:
        # Сохраняем открытые ордера.
        context.user_data['open_orders'] = open_orders
        formated_orders = ""
        order_count = 1
        for order in open_orders:
            formated_orders += f"{order_count}. {order['symbol']}"
            formated_orders += f" {order['type']} {order['side']}"
            formated_orders += f" {float(order['price'])}\n"
            order_count += 1
            # Cохраняем количество отрктых ордеров.
            context.user_data['total_open_orders'] = order_count

        update.message.reply_text(
            f"{formated_orders}\nВыберите ордер для закрытия.",
            reply_markup=numbers_keyboard(order_count))
        return 'close_step_1'

    # Если нет открытых ордеров.
    update.message.reply_text('Нет открытых ордеров.',
                              keyboard_markup=main_menu_keyboard())
    clear_all_crypto(update, context)
    return ConversationHandler.END
Esempio n. 6
0
def save_feedback(update: Update, context: CallbackContext):
    message = update.message.text
    user = update.message.from_user

    feedback_logger.info(
        "User %s %s username:%s: left message:\n%s",
        user.first_name,
        user.last_name,
        user.username,
        message,
    )

    context.bot.send_message(
        chat_id=update.message.chat_id, text=context.user_data['localisation']['FEEDBACKTHANKYOU']
    )
    reply_keyboard = keyboards.main_menu_keyboard(context)

    update.message.reply_text(
        context.user_data['localisation']['HELLO'],
        reply_markup=ReplyKeyboardMarkup(
            reply_keyboard, one_time_keyboard=True, resize_keyboard=True
        ),
    )

    return dk.MENU
Esempio n. 7
0
def change_lang(update: Update, context: CallbackContext):
    user = update.message.from_user
    logger.info(
        "User %s %s username:%s: change_lang to %s",
        user.first_name,
        user.last_name,
        user.username,
        context.user_data['localisation']['LANGUAGE'],
    )

    if context.user_data['lang'] == 'ru':
        context.user_data['localisation'] = languages.localisation_en
        context.user_data['lang'] = 'en'
    else:
        context.user_data['localisation'] = languages.localisation_ru
        context.user_data['lang'] = 'ru'

    reply_keyboard = keyboards.main_menu_keyboard(context)

    update.message.reply_text(
        context.user_data['localisation']['HELLO'],
        reply_markup=ReplyKeyboardMarkup(reply_keyboard,
                                         one_time_keyboard=True,
                                         resize_keyboard=True),
    )

    return dk.MENU
Esempio n. 8
0
def operation_cancel(update, context):
    """
    Функция fallback команды "Отмена" - удаляет данные из контекстов и
    завершает текущий Conversation
    """
    context.user_data.pop('location', None)

    update.message.reply_text('Операция прервана',
                              reply_markup=main_menu_keyboard())
    return ConversationHandler.END
Esempio n. 9
0
def get_my_stat(update, context):

    user_id = update.effective_user.id
    User().add_user(user_id)
    user_data = User().get_balance(user_id)

    message = 'На Вашем счету:\n'
    for data in user_data:
        message += f'Green Points-{data[0]}\n'
        message += f'Доступно билетов-{data[1]}'
    update.message.reply_text(message, reply_markup=main_menu_keyboard())
Esempio n. 10
0
def greet_user(update, context):

    try:
        name = update.effective_user['first_name']
    except KeyError:
        name = update.effective_user['username']

    update.message.reply_text(f"""Привет <b>{name}</b>! \n
    Ты можешь найти ближайший пукнт для переработки.
    Или проверить свои бонусы в личном кабинете.""",
                              reply_markup=main_menu_keyboard(),
                              parse_mode=ParseMode.HTML)
Esempio n. 11
0
def greet_user(update, context):

    clear_all_shares(update, context)
    clear_all_crypto(update, context)

    try:
        name = update.effective_user['first_name']
    except KeyError:
        name = update.effective_user['username']

    update.message.reply_text(f"Привет <b>{name}</b>! Выбери нужный раздел.",
                              reply_markup=main_menu_keyboard(),
                              parse_mode=ParseMode.HTML)
Esempio n. 12
0
def operation_cancel(update, context):
    """
    Функция fallback команды "Отмена" - удаляет данные из контекстов и
    завершает текущий Conversation
    """

    # shares_context
    clear_all_shares(update, context)

    # binance_context
    clear_all_crypto(update, context)

    update.message.reply_text('Операция прервана',
                              reply_markup=main_menu_keyboard())
    return ConversationHandler.END
Esempio n. 13
0
def get_route(update, context):
    """
    Записываем локацию юзера
    """
    location = update.message.location
    if location is not None:
        context.user_data['location'] = update.message.location
        url = get_simple_url()
        update.message.reply_text(f'Прокладываю маршрут! {url}',
                                  reply_markup=main_menu_keyboard())

        return ConversationHandler.END
    else:
        update.message.reply_text(
            'Без локации мы не сможешь Вам помочь. Попробуй ещё раз или нажми "Отмена"',
            reply_markup=location_and_cancel_keyboard())
        return '2'
Esempio n. 14
0
def send_pdf(update: Update, context: CallbackContext):
    user = update.message.from_user
    logger.info("User %s %s username:%s: send_pdf", user.first_name,
                user.last_name, user.username)

    context.bot.send_document(chat_id=update.message.chat_id,
                              document=open(dk.PROGRAM_PATH, 'rb'))

    reply_keyboard = keyboards.main_menu_keyboard(context)

    update.message.reply_text(
        context.user_data['localisation']['HELLO'],
        reply_markup=ReplyKeyboardMarkup(reply_keyboard,
                                         one_time_keyboard=True,
                                         resize_keyboard=True),
    )

    return dk.MENU
Esempio n. 15
0
def get_location(update, context):
    """
    Если выбран валидный тип продолжаем.
    Добавляем юзера в БД, если ранее не было.
    """

    text = update.message.text
    if text in TRASH_TYPES:
        update.message.reply_text(
            'Сейчас покажу что рядом, только мне нужно узнать где ты находишься.',
            reply_markup=location_keyboard())

        user_id = update.effective_user.id
        user_id = User().add_user(user_id)
        return '2'
    else:
        update.message.reply_text("""
            Если Вашей категории нет - обратитесь, пожалуйста, к админам.\n
            https://t.me/Stefs""",
                                  reply_markup=main_menu_keyboard())
        return ConversationHandler.END
Esempio n. 16
0
def beginning(update: Update, context: CallbackContext):
    user = update.message.from_user
    logger.info(
        "Chat_id %s User %s %s username:%s started the conversation.",
        update.message.chat_id,
        user.first_name,
        user.last_name,
        user.username,
    )

    if 'event_list' not in context.user_data:
        context.user_data['event_list'] = dk.create_user_event_list(
            update.message.chat_id)

    if 'marked_list' not in context.user_data:
        context.user_data['marked_list'] = dk.create_user_marked_list(
            update.message.chat_id, context.user_data['event_list'])

    if 'notified_list' not in context.user_data:
        context.user_data['notified_list'] = [
            talk for talk in context.user_data['marked_list'] if talk.notified
        ]

    if 'lang' not in context.user_data:
        context.user_data['lang'] = 'ru'
        context.user_data['localisation'] = languages.localisation_ru

    reply_keyboard = keyboards.main_menu_keyboard(context)

    update.message.reply_text(
        context.user_data['localisation']['HELLO'],
        reply_markup=ReplyKeyboardMarkup(reply_keyboard,
                                         one_time_keyboard=True,
                                         resize_keyboard=True),
    )

    return dk.MENU
def making_order(update, context):

    if update.message.text not in ORDERS_SIDE:
        update.message.reply_text(
            'Подвтердите сделку или нажмите "Отмена"',
            reply_markup=aply_order_keyboard(
                context.user_data['order_info']['order_side']
            )
        )
        return 'set_step_6'

    (ticker_pair, order_type, price, balance, order_side, quantity) = context.user_data['order_info'].values()

    # Минимально допустимая сумма сделки в $
    min_order_summ_in_usdt = 10

    def __preaparing_order_summ(price=price):
        """
        Если ордер создаётся для пары без $
        Например BNB/BTC - расчитываем price в $
        """
        if ticker_pair[1] != 'USDT' and order_type == 'limit':
            summ_in_usdt = binance_client.get_average_price(
                ticker_pair[0], 'USDT'
            )
            price *= float(summ_in_usdt.split()[0])

        elif ticker_pair[1] != 'USDT' and order_type == 'market':
            result_usdt = binance_client.get_average_price(
                ticker_pair[0], 'USDT'
            )
            price = float(result_usdt.split()[0])

        elif order_type == 'market':
            result_usdt = binance_client.get_average_price(
                ticker_pair[0], 'USDT'
            )
            price = float(result_usdt.split()[0])

        current_order_summ = price*quantity
        return current_order_summ

    # Сумма ордера.
    current_order_summ = __preaparing_order_summ()

    # Проверяем сумму ордера и если она меньше 10$ отправляем обратно.
    if current_order_summ < min_order_summ_in_usdt:
        message = f'Ордер должен быть не меньше {min_order_summ_in_usdt}$'
        message += f'\nВаш - {current_order_summ}$'
        update.message.reply_text(
            message,
            reply_markup=cancel_keyboard()
            )
        return 'set_step_4'

    if order_type == 'market' and order_side == 'sell':
        result = binance_client.set_order_market_sell(ticker_pair[0], ticker_pair[1], quantity)

    elif order_type == 'market' and order_side == 'buy':
        result = binance_client.set_order_market_buy(ticker_pair[0], ticker_pair[1], quantity)

    elif order_type == 'limit' and order_side == 'sell':
        result = binance_client.set_order_limit_sell(ticker_pair[0], ticker_pair[1], quantity, price)

    elif order_type == 'limit' and order_side == 'buy':
        result = binance_client.set_order_limit_buy(ticker_pair[0], ticker_pair[1], quantity, price)

    if result is not None:
        update.message.reply_text(
            'Ордер выставлен!', reply_markup=main_menu_keyboard()
        )

        clear_all_crypto(update, context)
        return ConversationHandler.END

    update.message.reply_text(
        'Возникла ошибка.',
        reply_markup=cancel_keyboard()
    )
    clear_all_crypto(update, context)
    return ConversationHandler.END