Beispiel #1
0
def inline_handler(bot, update, user_data):  #реализация календаря
    selected, date = telegramcalendar.process_calendar_selection(bot, update)
    if selected:
        bot.send_message(chat_id=update.callback_query.from_user.id,
                         text="Вы выбрали дату %s" %
                         (date.strftime("%d/%m/%Y")),
                         reply_markup=ReplyKeyboardRemove())
def on_select_date(update: Update, context: CallbackContext):
    query = update.callback_query
    query.answer()

    bot = context.bot

    selected, date = telegramcalendar.process_calendar_selection(bot, update)
    if selected:
        user_data = context.user_data
        text = date.strftime("%d/%m/%Y")
        user_data['Дата'] = text

        keyboard = [[
            InlineKeyboardButton("12:00", callback_data='12'),
            InlineKeyboardButton("14:30", callback_data='14'),
            InlineKeyboardButton("16:00", callback_data='16')
        ]]

        reply_markup = InlineKeyboardMarkup(keyboard)

        query.message.reply_text(text='''Вы выбрали %s
Выберите свободное время: ''' % text,
                                 reply_markup=reply_markup)

        return STATE_SELECT_TIME
def cal_inline_handler(update, context):
    selected, date = telegramcalendar.process_calendar_selection(context.bot, update)
    if selected:
        query = update.callback_query
        query.edit_message_text(text='Looking for events on {}...'.format(date.strftime('%d.%m.%Y')))
        search_date(update, context, date.strftime('%d.%m.%Y'))
        query.edit_message_text(text='Events on {}:'.format(date.strftime('%d.%m.%Y')))
Beispiel #4
0
    def change_calendar(self, update, context):
        try:
            query = update.callback_query
            selected, date = telegramcalendar.process_calendar_selection(context.bot, update)

            if selected:
                today = date.today()
                if date.year < today.year:
                    selected = False
                if date.year == today.year:
                    if date.month < today.month:
                        selected = False
                if date.year == today.year:
                    if date.month == today.month:
                        if date.day < today.day:
                            selected = False
                if not selected:
                    self.create_calendar(update, context)


            if selected:
                self.__set_rem.append("%s" % (date.strftime("%d.%m.%y")))
                context.bot.edit_message_text(
                    chat_id=query.message.chat_id,
                    message_id=query.message.message_id,
                    text="Выбрана дата %s" % (date.strftime("%d.%m.%Y"))
                )
                self.__step_create +=1
                self.set_time(update, context)
                return CREATE_TIME
        except Exception as exe:
            return CALENDAR
def inline_handler(update, context):
    selected, date = telegramcalendar.process_calendar_selection(
        update, context)
    if selected:
        context.bot.send_message(chat_id=update.callback_query.from_user.id,
                                 text="You selected %s" %
                                 (date.strftime("%d/%m/%Y")),
                                 reply_markup=ReplyKeyboardRemove())
Beispiel #6
0
def notification_handler(bot, update, user_data):
    selected, date = telegramcalendar.process_calendar_selection(bot, update)
    user_data.update(notification_date=date)
    bot.send_message(chat_id=update.callback_query.from_user.id,
                     text=f"""You selected {date}.
                     Enter notification time in format 'HH:MM'""",
                     reply_markup=ReplyKeyboardRemove())
    return ADD_NOTIFICATION_TIME
def time_check(bot, update, user_data):
    """ Вывод инлайн клавиатуры со временем """

    query = update.callback_query
    if user_data['name'] == 'Вова':
        selected, date = telegramcalendar.process_calendar_selection_vova(
            bot, update)
    elif user_data['name'] == 'Дима':
        selected, date = telegramcalendar.process_calendar_selection_dima(
            bot, update)
    elif user_data['name'] == 'Сергей':
        selected, date = telegramcalendar.process_calendar_selection_serg(
            bot, update)
    else:
        selected, date = telegramcalendar.process_calendar_selection(
            bot, update)

    sql = "SELECT * FROM time_to_barbers"
    cursor.execute(sql)
    data_base = cursor.fetchall()

    sql_2 = "SELECT * FROM record_info"
    cursor.execute(sql_2)
    data_base_2 = cursor.fetchall()

    if selected:
        all_time = [i[0] for i in data_base if user_data.get('name') in i[1]]
        for z in data_base_2:
            if user_data.get('name') in z[1] and date.strftime(
                    "%Y-%m-%d") in z[2] and z[3] in all_time:
                all_time.remove(z[3])
                if len(all_time) < 6:
                    all_time.append('Нет записи')
        keyboard = []
        row = [
            InlineKeyboardButton(i, callback_data=str(i))
            for i in all_time[0:3]
        ]
        keyboard.append(row)
        row = [
            InlineKeyboardButton(i, callback_data=str(i))
            for i in all_time[3:6]
        ]
        keyboard.append(row)
        row = [
            InlineKeyboardButton('Выбрать другой день',
                                 callback_data='Выбрать другой день')
        ]
        keyboard.append(row)

        reply_markup = InlineKeyboardMarkup(keyboard)
        bot.edit_message_text(text='Выберите время: {}'.format(smiles[6]),
                              chat_id=update.callback_query.from_user.id,
                              message_id=query.message.message_id,
                              reply_markup=reply_markup)
    user_data['date'] = date.strftime("%Y-%m-%d")
    print(user_data)
    return FOURTH
Beispiel #8
0
def inline(bot,update):
    query = update.callback_query
    lang = chat_storage.get_or_create(query.message.chat_id)['language']
    selected,date = telegramcalendar.process_calendar_selection(bot, update)
    if selected:
        criticism_storage.save_c_when(query.message.chat_id, c_when=date.strftime("%d/%m/%Y"))
        bot.send_message(chat_id=query.message.chat_id,
                        text="You selected %s" % (date.strftime("%d/%m/%Y")),
                        reply_markup=ReplyKeyboardRemove())
        bot.send_message(chat_id = query.message.chat_id, text =texts.CRITICISM_Q[lang][5])
Beispiel #9
0
def on_callback_query(update: Update, context: CallbackContext):
    query = update.callback_query
    query.answer()

    bot = context.bot

    selected, date = telegramcalendar.process_calendar_selection(bot, update)
    if selected:
        query.message.reply_text(text="You selected %s" %
                                 (date.strftime("%d/%m/%Y")),
                                 reply_markup=ReplyKeyboardRemove())
Beispiel #10
0
def deadline_handler(bot, update, user_data):
    selected, date = telegramcalendar.process_calendar_selection(bot, update)
    print(type(date))
    user_data['deadline_date'] = date
    user_data['updated_date'] = date
    print(date)
    reply_keyboard = [["Yes", "No"]]
    bot.send_message(
        chat_id=update.callback_query.from_user.id,
        text=f"""You selected {date}. Do you want to get notification?""",
        reply_markup=ReplyKeyboardMarkup(reply_keyboard,
                                         one_time_keyboard=True,
                                         resize_keyboard=True))
    return ADD_NOTIFICATION
Beispiel #11
0
def inline_handler(bot, update):
    user = update.callback_query.from_user.id
    selected, date = telegramcalendar.process_calendar_selection(bot, update)
    if selected:
        bot.send_message(chat_id=update.callback_query.from_user.id,
                         text="Kamu memilih tanggal %s \n\n %s" %
                         (date.strftime("%d/%m/%Y"), ijin_selected[IJIN]),
                         reply_markup=ReplyKeyboardRemove())

        logger.info("Calendar set to {}.".format(date.strftime('%d/%m/%Y')))

    Data_Ijin_Semua.setdefault(user, []).append(date.strftime("%Y-%m-%d"))

    print(Data_Ijin_Semua)

    return ATASAN
Beispiel #12
0
 def inline_handler(self, bot, update):
     """
     Select date
     :param bot:
     :param update:
     :return:
     """
     logger.info("DATE OF PUB")
     selected, date = telegramcalendar.process_calendar_selection(
         bot, update)
     if selected:
         self.date = date
         bot.send_message(chat_id=update.callback_query.from_user.id,
                          text="Please enter the time in HH:MM format",
                          reply_markup=ReplyKeyboardRemove())
         return 3
Beispiel #13
0
def inline_handler(update, context):
    selected, date = telegramcalendar.process_calendar_selection(
        context.bot, update)
    if selected:
        json_editor(str(update.callback_query.from_user.id), "date",
                    date.strftime("%d/%m/%Y"))
        context.bot.send_message(chat_id=update.callback_query.from_user.id,
                                 text="You selected %s" %
                                 (date.strftime("%d/%m/%Y")),
                                 reply_markup=ReplyKeyboardRemove())
        context.bot.send_message(
            chat_id=update.callback_query.from_user.id,
            text=
            "\U0001F553* Установка напоминания *\U0001F553\n\nВо *сколько* вам нужно напомнить?",
            parse_mode="markdown",
            reply_markup=telegramcalendar.create_clock(
                user=update.callback_query.from_user.id))
        return TIME_Q
Beispiel #14
0
def inline_handler(update, context):
    """
    Обработка нажатия кнопок на календаре и вывод пользователю ближайших рейсов к введенной дате
    """
    log.info("отображение календаря")
    query = update.callback_query  # данные которые приходят после нажатия кнопки
    selected, date = telegramcalendar.process_calendar_selection(update, context)
    if selected:
        query.edit_message_text(
            text="Вы выбрали %s" % (date.strftime("%d-%m-%Y"))
        )
        now = datetime.now()
        log.info(f"выбрана дата {date}, сегодня {now}")
        if date > now:
            log.info(f"{date} > {now}")
            check_date_calendar(update, context, date)
            return FLIGHT_CALENDAR
        else:
            log.info(f"{date} < {now}")
            query.edit_message_text(f"На вчера купить билет нельзя!")
            return DATE_OF_DEPARTURE
Beispiel #15
0
    def command_todo_calendar_callback(self, update, context):
        query = update.callback_query

        keyboard = [[
            InlineKeyboardButton("Yes", callback_data='CONFIRM_YES'),
            InlineKeyboardButton("No", callback_data='CONFIRM_NO')
        ]]

        reply_markup = InlineKeyboardMarkup(keyboard)

        selected, date = telegramcalendar.process_calendar_selection(
            context.bot, update)

        if selected:
            if not date:
                query.edit_message_text("No deadline added.\nConfirm?",
                                        reply_markup=reply_markup)
            else:
                self.todoManager.changeDeadline(date)
                query.edit_message_text(text="Deadline: {}\nConfirm?".format(
                    date.strftime("%d-%b-%Y")),
                                        reply_markup=reply_markup)
Beispiel #16
0
def inline(bot,update):
    res = ""
    selected,date = telegramcalendar.process_calendar_selection(bot, update)
    print((date.strftime("%d.%m.%Y")))
    #"Вы выбрали %s" % (date.strftime("%d.%m.%Y"))

    dd = [date.strftime("%d"), date.strftime("%m"), date.strftime("%Y")]

    mes = get_timetable_day(date=dd, login=login, password=password)
    if mes != []:
        for i in mes:
            res += (i + '\n')

        if selected:
            bot.send_message(chat_id=update.callback_query.from_user.id,
                            text= "Вы выбрали %s:" % (date.strftime("%d.%m.%Y")) + "\n" + res,
                            reply_markup=ReplyKeyboardRemove())
    else:
        if selected:
            bot.send_message(chat_id=update.callback_query.from_user.id,
                            text= "Вы выбрали %s:" % (date.strftime("%d.%m.%Y")) + "\n" + 'На этот день нет расписания',
                            reply_markup=ReplyKeyboardRemove())
def graph_for_period(update, context):
    """
    Take two dates from user input in calendar.
    send them to user,
    take current-user data from postgreSQL
    prepare data to graph
    return left arm and right arm graph.png for the choosen period

    """
    selected, date = telegramcalendar.process_calendar_selection(
        update, context)
    str_date = date.strftime("%Y-%m-%d")

    if selected:
        context.bot.send_message(chat_id=update.callback_query.message.chat_id,
                                 text="You selected %s" % str_date,
                                 reply_markup=markup_remove)

    if 'first_date' not in context.user_data:
        context.user_data['first_date'] = str_date

    elif 'second_date' not in context.user_data:
        context.user_data['second_date'] = str_date
        make_graph(update, context)

        text = "What you'd like to do next?"

        context.bot.send_message(chat_id=update.callback_query.message.chat_id,
                                 text=text,
                                 reply_markup=start_markup)

        if 'first_date' in context.user_data:
            del context.user_data['first_date']

        if 'second_date' in context.user_data:
            del context.user_data['second_date']

        return States.START_BUTTON
Beispiel #18
0
def calendar_handler(bot, update):
    print("\n", update)
    selected, date = telegramcalendar.process_calendar_selection(bot, update)
    print("Selected", selected)
    print("Date", date)
    if selected:
        insert = """INSERT INTO reservation VALUES ({0}, '{1}', {2}, {3}, '{4}')""".format(
            1, date, update.callback_query.from_user.id,
            "nextval('reservation_seq')", datetime.today())
        print("Insert query", insert)
        result = insert_query(insert)
        if result:
            bot.send_message(
                chat_id=update.callback_query.from_user.id,
                text="Reserva para o dia {0} efetuada com sucesso!".format(
                    date.strftime("%d/%m/%Y")),
                reply_markup=ReplyKeyboardRemove())
        else:
            bot.send_message(
                chat_id=update.callback_query.from_user.id,
                text=
                "Não foi possível fazer reserva para o dia {0}, tente novamente em outra data"
                .format(date.strftime("%d/%m/%Y")),
            )
Beispiel #19
0
def inline_handler(bot, update, user_data):
    component = update.callback_query.data.split(";")[0]

    if component == telegramcalendar.COMPONENT:
        selected, date = telegramcalendar.process_calendar_selection(
            bot, update)
        if selected:
            if not user_data.get('start'):
                user_data['start'] = date.strftime("%Y-%m-%d")
                update.effective_message.reply_text(
                    "Выбери вторую дату: ",
                    reply_markup=telegramcalendar.create_calendar())
            else:
                user_data['end'] = date.strftime("%Y-%m-%d")
                date_range = "{} {}".format(user_data['start'],
                                            user_data['end'])
                keyboard = [[
                    InlineKeyboardButton(f'/add_schedule {date_range}')
                ]]
                reply_markup = ReplyKeyboardWithCancel(keyboard,
                                                       one_time_keyboard=True)
                bot.send_message(
                    chat_id=update.callback_query.from_user.id,
                    text=
                    f"Выбраны даты: {user_data['start']} - {user_data['end']}",
                    reply_markup=reply_markup)
    elif component == student_lists.COMPONENT:
        selected, user_id = student_lists.process_user_selection(bot, update)
        if selected:
            user_data['student_id'] = user_id
            keyboard = [[InlineKeyboardButton('Запиши меня')]]
            reply_markup = ReplyKeyboardWithCancel(keyboard,
                                                   one_time_keyboard=True)
            bot.send_message(chat_id=update.callback_query.from_user.id,
                             text=f"Добавляем студента: {user_id}",
                             reply_markup=reply_markup)
Beispiel #20
0
def inline_master_pressed(bot, update, user_data):
    conn = sqlite3.connect('mydatabase.db')
    cursor = conn.cursor()
    sql = "SELECT * FROM table_barbers"
    cursor.execute(sql)
    data_base = cursor.fetchall()

    sql_1 = "SELECT * FROM table_barbers2services"
    cursor.execute(sql_1)
    data_base_1 = cursor.fetchall()

    sql_2 = "SELECT * FROM table_services"
    cursor.execute(sql_2)
    data_base_2 = cursor.fetchall()

    counter = []
    query = update.callback_query
    name = query.data

    # Запрос контактов
    if len(query.data) == 5:
        contact_button = KeyboardButton('Контактные данные',
                                        request_contact=True)
        my_keyboard = ReplyKeyboardMarkup([[contact_button]],
                                          resize_keyboard=True,
                                          one_time_keyboard=True)
        bot.send_message(
            chat_id=update.callback_query.from_user.id,
            text="Отправьте Ваши контактные данные для уточнения заказа:",
            reply_markup=my_keyboard)
        bot.delete_message(chat_id=update.callback_query.from_user.id,
                           message_id=query.message.message_id)

        # Запись всех данных в БД
        global p
        p = query.data
        user_data['time'] = p
        # print(user_data)
        cort_1 = (user_data.get('name'), )
        cort_2 = cort_1 + (user_data.get('service'), )
        cort_3 = cort_2 + (user_data.get('date'), )
        cort_4 = cort_3 + (user_data.get('time'), )
        print(cort_4)
        data = []
        data.append(cort_4)
        cursor.executemany("INSERT INTO info VALUES (?,?,?,?)", data)
        conn.commit()

# Клавиатура с услугами
    counter = []
    for masters in data_base:
        if name in masters:
            global c
            c = query.data
            a = masters[0]
            for master_id in data_base_1:
                if a in master_id:
                    b = master_id[2]
                    for service_id in data_base_2:
                        if b in service_id:
                            all_services = []
                            all_services.append(service_id[2])
                            keyboard = []
                            row = []
                            for i in all_services:
                                row.append(
                                    InlineKeyboardButton(i,
                                                         callback_data=str(i)))
                                counter = row + counter
    list_1 = []
    list_1.append(counter)
    reply_markup = InlineKeyboardMarkup(list_1)
    bot.edit_message_text(chat_id=update.callback_query.from_user.id,
                          text="Выберите услугу: ",
                          message_id=query.message.message_id,
                          reply_markup=reply_markup)
    global d
    d = query.data

    # Календарь
    sql_3 = "SELECT service_name FROM table_services"
    cursor.execute(sql_3)
    data_base_3 = cursor.fetchall()
    for z in data_base_3:
        if query.data == z[0]:
            bot.edit_message_text(
                chat_id=update.callback_query.from_user.id,
                text="Выберите дату: ",
                message_id=query.message.message_id,
                reply_markup=telegramcalendar.create_calendar())
            global e
            e = query.data

# Выбор времени
    selected, date = telegramcalendar.process_calendar_selection(bot, update)
    if selected:
        inline_keyboard = [[
            InlineKeyboardButton('10:00', callback_data='10:00'),
            InlineKeyboardButton('11:00', callback_data='11:00')
        ],
                           [
                               InlineKeyboardButton('12:00',
                                                    callback_data='12:00'),
                               InlineKeyboardButton('13:00',
                                                    callback_data='13:00')
                           ],
                           [
                               InlineKeyboardButton('14:00',
                                                    callback_data='14:00'),
                               InlineKeyboardButton('15:00',
                                                    callback_data='15:00')
                           ]]
        reply_markup = InlineKeyboardMarkup(inline_keyboard)
        bot.edit_message_text(
            chat_id=update.callback_query.from_user.id,
            text="Вы выбрали дату: %s. Выберите удобное для Вас время: " %
            (date.strftime("%d/%m/%Y")),
            message_id=query.message.message_id,
            reply_markup=reply_markup)

# Запись данных в user_data
    user_data['name'] = c
    user_data['date'] = date.strftime("%d/%m/%Y")
    user_data['service'] = e
Beispiel #21
0
def keyboard_regulate(update: Update, context: CallbackContext):
    """
    This method is handler of keyboard
    :param update:
    :param context:
    """
    user_name = update.effective_user.first_name
    query = update.callback_query
    current_callback = query.data
    current_link = database.get_item(user_name)[0][1]
    date_range = [database.get_item(user_name)[0][3], database.get_item(user_name)[0][4]]
    # case: "Chart of posts history"
    if current_callback == "chart":
        update.callback_query.edit_message_text(text="Downloading...")
        view_data = request.download_all(current_link, date_range)
        chart_with_dates(view_data)
        update.callback_query.edit_message_text(text=f"Message history of {current_link}")
        context.bot.send_photo(chat_id=update.callback_query.from_user.id, photo=open("img/photo.png", 'rb'))
        context.bot.send_message(chat_id=update.callback_query.from_user.id,
                                 text="Function menu", reply_markup=generate_keyboard())
        os.remove("img/photo.png")
    # case "Full posts history"
    elif current_callback == "download_all":
        current_link = current_link.split("https://t.me/")
        current_link = current_link[len(current_link) - 1]
        update.callback_query.edit_message_text(text="Sending...")
        view_data = request.download(current_link, date_range)
        make_exsel(view_data, current_link)
        time.sleep(5)
        update.callback_query.edit_message_text(text=f"Full message history of {current_link}")
        context.bot.send_document(chat_id=update.callback_query.from_user.id,
                                  document=open(f"{current_link}-history.xlsx", 'rb'))
        os.remove(f"{current_link}-history.xlsx")
        context.bot.send_message(chat_id=update.callback_query.from_user.id,
                                 text="Function menu", reply_markup=generate_keyboard())
    # case "The most viewed post"
    elif current_callback == "most_viewed":
        update.callback_query.edit_message_text(text="Downloading...")
        values = request.most_viewed_post(current_link, date_range)
        context.bot.send_message(chat_id=update.callback_query.from_user.id,
                                 text=f"The most popular post \nViews: {values[2]}" + "\nDate: " + "%s" % values[1])
        context.bot.send_message(chat_id=update.callback_query.from_user.id,
                                     text=f"{values[0]}")

        context.bot.send_message(chat_id=update.callback_query.from_user.id,
                                 text="Function menu", reply_markup=generate_keyboard())

    try:
        selected, date = telegramcalendar.process_calendar_selection(context, update)
        if "start" in update.callback_query.message['text']:
            if date < datetime.datetime.now():
                context.bot.send_message(chat_id=update.callback_query.from_user.id,
                                         text="You selected start %s" % str(date.strftime("%d %m %Y")),
                                         reply_markup=ReplyKeyboardRemove())
                database.edit_item([user_name, "_", "_", "%s" % str(date.strftime("%d %m %Y")), "_"])
            else:
                context.bot.send_message(chat_id=update.callback_query.from_user.id,
                                         text="Impossible value",
                                         reply_markup=ReplyKeyboardRemove())

        elif "end" in update.callback_query.message['text']:
            context.bot.send_message(chat_id=update.callback_query.from_user.id,
                                     text="You selected end %s" % str(date.strftime("%d %m %Y")),
                                     reply_markup=ReplyKeyboardRemove())
            database.edit_item([user_name, "_", "_", "_", "%s" % str(date.strftime("%d %m %Y"))])
    except Exception:
        pass