Exemple #1
0
def planet(update, context):
    get_or_create_user(db, update.effective_user, update.message.chat.id)
    print(context.args)
    logging.info(context.args)
    if context.args[0].lower() == 'марс':
        logging.info('вызвана команда /planet Марс')
        now = datetime.datetime.now()
        mars = ephem.Mars(now)
        stars = ephem.constellation(mars)
        star_planet = (f'Сегодняшняя дата {now.strftime("%d-%m-%Y %H:%M")}.\n'
                       f'Планета Марс находится в созвездии {stars[1]}')
        update.message.reply_text(star_planet, reply_markup=main_keyboard())
    elif context.args[0].lower() == 'юпитер':
        logging.info('вызвана команда /planet Юпитер')
        now = datetime.datetime.now()
        jupiter = ephem.Jupiter(now)
        stars = ephem.constellation(jupiter)
        star_planet = (f'Сегодняшняя дата {now.strftime("%d-%m-%Y %H:%M")}.\n'
                       f'Планета Юпитер находится в созвездии {stars[1]}')
        update.message.reply_text(star_planet, reply_markup=main_keyboard())
    elif context.args[0].lower() == 'венера':
        logging.info('вызвана команда /planet Венера')
        now = datetime.datetime.now()
        venus = ephem.Venus(now)
        stars = ephem.constellation(venus)
        star_planet = (f'Сегодняшняя дата {now.strftime("%d-%m-%Y %H:%M")}.\n'
                       f'Планета Венера находится в созвездии {stars[1]}')
        update.message.reply_text(star_planet, reply_markup=main_keyboard())
    else:
        logging.info('вызвана команда неизвестная планета')
        update.message.reply_text('Такой планеты нет в моём списке!',
                                  reply_markup=main_keyboard())
Exemple #2
0
def user_settings_start(update, context):
    logging.info('Вызван /settings')

    get_or_create_user(db, update.effective_user, update.message.chat.id)
    update.message.reply_text(
        'Привет пользователь! Давай настроим твоего бота. Выбери актив, который '
        'ты хочешь настроить',
        reply_markup=assets_keyboard())
    return 'set_asset'
Exemple #3
0
def guess_number(update, context):
    get_or_create_user(db, update.effective_user, update.message.chat.id)
    logging.info('Вызван /guess')
    if context.args:
        try:
            user_number = int(context.args[0])
            message = play_random_numbers(user_number)
        except (TypeError, ValueError):
            message = 'Введите целое число'
    else:
        message = 'Введите число'
    update.message.reply_text(message, reply_markup=main_keyboard())
def detect_defects(update, context):
    """ detect defects """
    get_or_create_user(DB, update.effective_user, update.message.chat.id)
    os.makedirs("downloads", exist_ok=True)
    if "last_image" not in context.user_data:
        update.message.reply_text("Загрyзите изображение")
        return
    image = context.user_data["last_image"]
    print(f"Ищем дефекты на {image}")
    result, y_pred = process_picture(DEFECTS_MODEL, LABEL_ENCODER, image)
    user_id = update.effective_user.id
    save_detected_defects(DB, user_id, y_pred, result, img_name=image)
    update.message.reply_text("Это " + result, reply_markup=main_keyboard())
Exemple #5
0
def anketa_get_name(bot, update, user_data):
    user = get_or_create_user(db, update.effective_user, update.message)
    user = get_or_create_user(db, update.effective_user, update.message)
    user_name = update.message.text
    if len(user_name.split(" ")) != 2:
        update.message.reply_text("Пожалуйста введите имя и фамилию")
        return "name"
    else:
        user_data['anketa_name'] = user_name
        reply_keyboard = [["1", "2", "3", "4", "5"]]
        update.message.reply_text("Оцените нашего бота от 1 до 5",
                                  reply_markup=ReplyKeyboardMarkup(
                                      reply_keyboard, one_time_keyboard=True))
        return "rating"
Exemple #6
0
def check_user_photo(update, context):
    get_or_create_user(db, update.effective_user, update.message.chat.id)
    update.message.reply_text('Обрабатываем фотографию')
    os.makedirs('downloads', exist_ok=True)
    user_photo = context.bot.getFile(update.message.photo[-1].file_id)
    file_name = os.path.join('downloads', f'{user_photo.file_id}.jpg')
    user_photo.download(file_name)
    if is_cat(file_name):
        update.message.reply_text('Обнаружен мемасик, добавляю в библиотеку')
        new_filename = os.path.join('images', f'meme_{user_photo.file_id}.jpg')
        os.rename(file_name, new_filename)
    else:
        update.message.reply_text('МЕМАС НЕ ОБНАРУЖЕН!!')
        os.remove(file_name)
Exemple #7
0
def greet_user(update, context):
    logging.info('Вызван /start')

    get_or_create_user(db, update.effective_user, update.message.chat.id)
    currency_list = ', '.join(CURRENCY_LIST)
    update.message.reply_text(
        'Привет, пользователь! Ты вызвал команду /start.\n'
        'Это бот, который покажет интересующие тебя курсы валют, '
        'акций и криптовалют.\n\n'
        '/settings - для настройки бота\n\n'
        '/notice <валюта> <значение> - для настройки выдачи уведомлений.'
        'Например: комманда </notifications USD 75.4> '
        'выдаст вам уведомление если курс валюты станет больше или меньше 75.4 рублей\n\n'
        f'Список доступных валют: {currency_list}',
        reply_markup=main_keyboard())
def unsubscribe(bot, update):
    user = get_or_create_user(db, update.effective_user, update.message)
    if user.get('subscribed'):
        toggle_subscription(db, user)
        update.message.reply_text("Вы отписались")
    else:
        update.message.reply_text("Вы не подписаны, нажмите /subscribe чтобы подписаться")
Exemple #9
0
def talk_to_me(update, context):
    user = get_or_create_user(db, update.effective_user, update.message)
    emo = get_user_emo(user)
    user_text = f'Привет {user["first_name"]} {emo} Ты написал: {update.message.text}'
    logging.info("User: %s, Chat id: %s, Message: %s", user['username'],
                 update.message.chat.id, update.message.text)
    update.message.reply_text(user_text, reply_markup=get_keyboard())
Exemple #10
0
def bye_user(bot, update, user_data):
    user = get_or_create_user(db, update.effective_user, update.message)
    text = 'Вызван STOP!'
    print(text)
    bot.send_message(chat_id=update.message.chat_id,
                     text='Stop',
                     reply_markup=get_keyboard())
Exemple #11
0
def greet_user(bot, update, user_data):
    user = get_or_create_user(db, update.effective_user, update.message)
    emo = get_user_emo(db, user)
    text = 'Привет, {} {}'.format(update.message.chat.first_name, emo)
    update.message.reply_text(text, reply_markup=get_keyboard())
    logging.info('{}({}): /start'.format(update.message.chat.username,
                                         update.message.chat.first_name))
def user_subscribe(update, context):
    context.user_data = get_or_create_user(db, update.effective_user,
                                           update.message)
    print(user)
    subsctibers.add(update.message.chat_id)
    update.message.reply_text(
        "Вы подписались, наберите /unsubscribe чтобы отписаться")
def received_book_information(update, context):

    user = get_or_create_user(db, update.message)
    username = user['username']
    user_books_count = user['books_count']
    user_id = user['user_id']

    user_data = context.user_data
    user_text = update.message.text
    goal_choice = user_data['choice']
    user_data[goal_choice] = user_text
    del user_data['choice']

    logger.info('Updating books count in MONGO by user %s', username)

    try:
        user_text = int(user_text)
        db.users.update_one({'user_id': user_id},
                            {'$set': {
                                'books_count': user_text
                            }})
        update.message.reply_text(
            'Ты собрался прочитать {} книг, желаю удачи!'.format(user_text),
            reply_markup=markup_main)

    except ValueError:
        update.message.reply_text('Кажется ты ввел не число, попробуй еще раз',
                                  reply_markup=markup_main)

    return CHOOSING_MAIN
Exemple #14
0
def unsubscribe(bot, update):
    user = get_or_create_user(db, update.effective_user, update.message)
    if user.get('subscribed'):
        toggle_subscription(db, user)
        update.message.reply_text('Вы отписались!')
    else:
        update.message.reply_text('Вы не подписаны')
Exemple #15
0
def send_cat_picture(bot, update, user_data):
    user = get_or_create_user(db, update.effective_user, update.message)
    cat_list = glob('images/cat*.jp*g')
    cat_pic = choice(cat_list)
    bot.send_photo(chat_id=update.message.chat.id,
                   photo=open(cat_pic, 'rb'),
                   reply_markup=get_keyboard())
Exemple #16
0
def greet_user(update, context):
    user = get_or_create_user(db, update.effective_user, update.message.chat.id)
    print("Вызван /start")
    update.message.reply_text(
        f"Здравствуй, пользователь {user['emoji']}!",
        reply_markup=main_keyboard()
    )
Exemple #17
0
def unsubscribe(bot, update):
    user = get_or_create_user(db, update.effective_user, update.message)
    if user.get('subscribed'):
        toggle_subscription(db, user)
        update.message.reply_text('Подписка отключена')
    else:
        update.message.reply_text('Подписка не активна, нажмите /subscribe чтобы подписаться')
def add_book_variables(update, context):

    user_text = update.message.text
    context.user_data['choice'] = user_text
    update.message.reply_text('Выберите вариант добавления книги',
                              reply_markup=markup_add_book)
    user = get_or_create_user(db, update.message)
Exemple #19
0
def break_start(update, context):
    try:
        reply_keyboard = [['Закончить выполнение']]
        user = get_or_create_user(db, update.effective_user,
                                  update.message.chat.id)
        context.job_queue.run_once(break_continue,
                                   600,
                                   context=update.message.chat_id)
        update.message.reply_text(f"Перерыв начался в {datetime.now()}",
                                  reply_markup=ReplyKeyboardMarkup(
                                      reply_keyboard,
                                      one_time_keyboard=True,
                                      resize_keyboard=True))
        db.users.update_one({'_id': user['_id']},
                            {'$set': {
                                'break_start': datetime.now()
                            }})
        db.users.update_one({'_id': user['_id']},
                            {'$inc': {
                                'number_of_breaks': 1
                            }})

        return "finish_break"
    except (IndexError, ValueError):
        update.message.reply_text("В")
Exemple #20
0
def talk_to_me(update, context):
    user = get_or_create_user(db, update.effective_user,
                              update.message.chat_id)
    text = update.message.text
    print(text)
    update.message.reply_text(f'{text} {user["emoji"]}',
                              reply_markup=main_keyboard())
Exemple #21
0
def greet_user(bot, update, user_data):
    user = get_or_create_user(db, update.effective_user, update.message)
    emo = get_user_emo(db, user)
    user_data['emo'] = emo
    text = 'Привет {}'.format(emo)
    logging.info(text)
    update.message.reply_text(text, reply_markup=get_keyboard())
def set_alarm(bot, update, args, job_queue):
    user = get_or_create_user(db, update.effective_user, update.message)
    try:
        seconds = abs(int(args[0]))
        job_queue.run_once(alarm, seconds, context=update.message.chat_id)
    except (IndexError, ValueError):
        update.message.reply_text("Введите число секунд после команды /alarm")
def anketa_rating(bot, update, user_data):
    user = get_or_create_user(db, update.effective_user, update.message)
    user_data["anketa_rating"] = update.message.text

    update.message.reply_text("""Оставьте комментарий в свободной форме 
        или пропустите этот шаг, введя /skip""")
    return "comment"
Exemple #24
0
def chenge_avatar(update, context):
    user = get_or_create_user(db, update.effective_user, update.message)

    if 'emo' in user:
        del user['emo']
    emo = get_user_emo(user)
    update.message.reply_text(f'Готово {emo}', reply_markup=get_keyboard())
Exemple #25
0
def unsubscribe(bot, update):
    user = get_or_create_user(db, update.effective_user, update.message)
    if user.get('subscribed'):
        toogle_subscription(db, user)
        update.message.reply_text('Вы отписались')
    else:
        update.message.reply_text('Вы не подписаны :) Можете набрать /sub чтобы подписаться')
def add_my_book_goal(update, context):

    user = get_or_create_user(db, update.message)
    username = user['username']
    user_id = user['user_id']
    user_books_count = user['books_count']

    text = update.message.text
    context.user_data['choice'] = text
    user_choice = context.user_data['choice']

    if user_choice == 'Удалить цель':
        db.users.update_one({'user_id': user_id}, {'$set': {'books_count': 0}})
        update.message.reply_text(
            'Кажется у тебя больше нет цели. Это очень грустно.',
            reply_markup=markup_main)
        return CHOOSING_MAIN

    elif user_choice == 'Посмотреть цель':
        update.message.reply_text(f'Твоя цель - {user_books_count} книг(и)',
                                  reply_markup=markup_main)
        return CHOOSING_MAIN

    else:
        update.message.reply_text(
            'Укажи количество книг, которые ты хочешь прочитать')
        return ADD_MY_GOAL
Exemple #27
0
def user_coordinates(update, context):
    user = get_or_create_user(db, update.effective_user, update.message.chat.id)
    coords = update.message.location
    update.message.reply_text(
        f"Ваши координаты {coords} {user['emoji']}!",
        reply_markup=main_keyboard()
    )
Exemple #28
0
def anketa_skip_comment(bot, update, user_data):
    user = get_or_create_user(db, update.effective_user, update.message)
    text = """
<b>Ваше имя и фамилия: </b>{anketa_name}
<b>Ваша оценка: </b>{anketa_rating}""".format(**user_data)
    update.message.reply_text(text, reply_markup=get_keyboard(), parse_mode=ParseMode.HTML)
    return ConversationHandler.END
Exemple #29
0
def change_avatar(bot, update, user_data):
    user = get_or_create_user(db, update.effective_user, update.message)
    if 'emo' in user:
        del user['emo']
    emo = get_user_emo(db, user)
    update.message.reply_text('Готово: {}'.format(emo),
                              reply_markup=get_keyboard())
Exemple #30
0
def subscribe(bot, update):
    user = get_or_create_user(db, update.effective_user, update.message)
    if not user.get('subscribed'):
        toogle_subscription(db, user)
        update.message.reply_text('Вы подписались')
    elif user.get('subscribed'):
        update.message.reply_text('Вы уже подписаны :)')