Exemple #1
0
def process_date_step(message):
    try:
        date = message.text
        if date == 'Отмена':
            cancel_adding_event(message.chat.id)
            return
        chat_id = message.chat.id
        event = event_dict[chat_id]

        date = parse(str(date)).date()
        if date < datetime.date.today():
            # msg = bot.reply_to(message, 'Это прошлое. Введите дату в формате (ДД/ММ/ГГГГ)')
            now = datetime.datetime.now()  # Get the current date
            bot.reply_to(
                message,
                "Это прошлое. Выбери дату",
                reply_markup=telebot_calendar.create_calendar(
                    name=calendar_1.prefix,
                    year=now.year,
                    month=now.month,
                ),
            )

            return

        event.date = date
        markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
        markup.add('Отмена')
        msg = bot.reply_to(message, 'Введите время (ЧЧ:ММ)', reply_markup=markup)
        bot.register_next_step_handler(msg, process_time_step)

    except Exception as e:
        # msg = bot.reply_to(message, 'Введите дату в формате (ДД/ММ/ГГГГ)')
        # bot.register_next_step_handler(msg, process_date_step)
        print(str(e))
Exemple #2
0
def handle_month_query(call):

    info = call.data.split(';')
    month_opt = info[0].split('-')[0]
    year, month = int(info[1]), int(info[2])
    chat_id = call.message.chat.id

    if month_opt == 'PREV':
        month -= 1

    elif month_opt == 'NEXT':
        month += 1

    if month < 1:
        month = 12
        year -= 1

    if month > 12:
        month = 1
        year += 1

    date = (year, month)
    current_shown_dates[chat_id] = date
    markup = create_calendar(year, month)
    bot.edit_message_text(config.messages['reply_send_start_date'],
                          call.from_user.id,
                          call.message.message_id,
                          reply_markup=markup)
Exemple #3
0
def vk_statistic(message):
    now = datetime.datetime.now()
    bot.send_message(
        message.chat.id,
        "Выберите день",
        reply_markup=telebot_calendar.create_calendar(
            name=calendar.prefix,
            year=now.year,
            month=now.month,
        ),
    )
Exemple #4
0
def get_task_desc(message):
    new_task.desc = message.text

    now = datetime.datetime.now()
    bot.send_message(message.chat.id,
    "Выбарите дату, до которой дело должно быть выполнено.",
    reply_markup=telebot_calendar.create_calendar(
        name = task_calendar.prefix,
        year = now.year,
        month = now.month
    ))
Exemple #5
0
def check_other_messages(message):
    now = datetime.datetime.now()  # Get the current date
    bot.send_message(
        message.chat.id,
        "Выберите дату",
        reply_markup=telebot_calendar.create_calendar(
            name=calendar_1.prefix,
            year=now.year,
            month=now.month,  # Specify the NAME of your calendar
        ),
    )
def getFecha(m):
    now = datetime.datetime.now()  # Get the current date
    bot.send_message(
        m.chat.id,
        "Introduce la fecha ",
        reply_markup=telebot_calendar.create_calendar(
            name=calendar_1.prefix,
            year=now.year,
            month=now.month,  # Specify the NAME of your calendar
        ),
    )
Exemple #7
0
def calendar_message(message):
    if message.text == "Забронировать":
        now = datetime.datetime.now()  # Get the current date
        bot.send_message(
            message.chat.id,
            "Выберите дату",
            reply_markup=telebot_calendar.create_calendar(
                name=calendar.prefix,
                year=now.year,
                month=now.month,
            ),
        )
Exemple #8
0
def callback_inline(call: CallbackQuery):
    if call.data == "getdate":
        now = datetime.now()
        bot.edit_message_text(
            chat_id=call.message.chat.id,
            message_id=call.message.message_id,
            text="Selected date",
            reply_markup=telebot_calendar.create_calendar(
                name=calendar.prefix,
                year=now.year,
                month=now.month,
            ),
        )
Exemple #9
0
def send_text(message):
    if message.text.lower() == 'новая цель!':
        mci = message.chat.id
        New_task = bot.send_message(
            mci,
            'Нет ничего лучше, чем записывать новые цели! Разве что... ИХ ВЫПОЛНЯТЬ! Записывай: '
        )
        bot.register_next_step_handler(New_task, Set_up_task)
    elif message.text.lower() == 'пока':
        bot.send_message(message.chat.id, 'Надеюсь ты вернёшься скоро!')

    elif message.text.lower() == 'мои задачи':
        with con:
            mci = message.chat.id
            cursor.execute("SELECT * FROM user_tasks WHERE user_id=%s", [mci])

            rows = cursor.fetchall()

            for row in rows:
                bot.send_message(message.chat.id, (f" {row[2]} {row[3]}"),
                                 reply_markup=start_keyboard)

    elif message.text.lower() == 'да!':
        bot.send_message(message.chat.id,
                         'Отлично! вот и новая цель!',
                         reply_markup=start_keyboard)
        cur = con.cursor()
        cur.execute(
            '''INSERT INTO user_tasks (user_id,goal,dline)
        VALUES (%s, %s, %s);
        ''', (sql_id, sql_task, sql_date))
        con.commit()
    elif message.text.lower() == 'выбрать дату':
        now = datetime.datetime.now()
        today = now.strftime('%d.%m.%Y')
        bot.send_message(
            message.chat.id,
            text=f"На какой день планируем?) \nCейчас: {today}",
            reply_markup=telebot_calendar.create_calendar(
                name=calendar_1.prefix,
                year=now.year,
                month=now.month,
            ),
        )

    else:
        bot.send_message(
            message.chat.id,
            'Я бы мог отзывться на подобные сообщения, но удобнее же кнопки! Начнём сначала: ',
            reply_markup=start_button)
def calendar(message):
    if message.text == '/start':
        return start(message)
    SAVED_DATA['schedule']['subject'] = SAVED_DATA['subjects'][message.text]
    now = datetime.datetime.now()
    bot.send_message(
        message.chat.id,
        "Selected date",
        reply_markup=telebot_calendar.create_calendar(
            name=calendar_1.prefix,
            year=now.year,
            month=now.month,
        ),
    )
Exemple #11
0
def task_remind(call):
    bot.delete_message(call.from_user.id, call.message.message_id)
    res = call.data.split('_')
    task_id = res[2]
    task = util.get_task_by_id(task_id)
    if res[1] == 'back':
        bot.send_message(call.from_user.id,
                         create_task_text(task),
                         reply_markup=mark_conf.task_menu(task),
                         parse_mode='HTML')
    elif res[1] == 'remind':
        bot.send_message(call.from_user.id,
                         timer_task(task),
                         reply_markup=mark_conf.set_remind_task(task),
                         parse_mode='HTML')
    elif res[1] == 'setdate':
        EDIT_TASK_REMIND[call.from_user.id] = {}
        EDIT_TASK_REMIND[call.from_user.id]['task_id'] = task_id
        now = datetime.datetime.now()  # Get the current date
        bot.send_message(call.from_user.id,
                         "Выберите дату события:",
                         reply_markup=telebot_calendar.create_calendar(
                             name=calendar_1.prefix,
                             year=now.year,
                             month=now.month))
    elif res[1] == 'settime':
        EDIT_TASK_REMIND[call.from_user.id] = {}
        EDIT_TASK_REMIND[call.from_user.id]['task_id'] = task_id
        EDIT_TASK_REMIND[call.from_user.id]['time'] = datetime.time(hour=12,
                                                                    minute=0)
        bot.send_message(
            call.from_user.id,
            'Выберите время в которое сотрудники должны высылать отчет',
            reply_markup=mark_conf.clock_inline(
                hour=datetime.time.strftime(
                    EDIT_TASK_REMIND[call.from_user.id]['time'], '%H'),
                minute=datetime.time.strftime(
                    EDIT_TASK_REMIND[call.from_user.id]['time'], '%M')))
        msg = bot.send_message(call.from_user.id,
                               msg_text['set_time_and_ok'],
                               reply_markup=mark_conf.create_timer_button(),
                               parse_mode='HTML')
        bot.register_next_step_handler(msg, set_time_remind)
    elif res[1] == 'back':
        bot.send_message(call.from_user.id,
                         create_task_text(task),
                         reply_markup=mark_conf.task_menu(task),
                         parse_mode='HTML')
Exemple #12
0
def choose_date(call):
    """
    :param message:
    :return:
    """

    now = datetime.datetime.now()  # Get the current date
    bot.edit_message_text(
        chat_id=call.message.chat.id,
        message_id=call.message.message_id,
        text="Выберите дату отчета:",
        reply_markup=telebot_calendar.create_calendar(
            name=calendar_1.prefix,
            year=now.year,
            month=now.month,
        ),
    )
Exemple #13
0
def check_other_messages(message):
    """
    Catches a message with the command "start" and sends the calendar

    :param message:
    :return:
    """

    now = datetime.datetime.now()  # Get the current date
    bot.send_message(
        message.chat.id,
        "Selected date",
        reply_markup=telebot_calendar.create_calendar(
            name=calendar_1.prefix,
            year=now.year,
            month=now.month,  # Specify the NAME of your calendar
        ),
    )
Exemple #14
0
def add_new_event_proc(message):
    try:
        description = str(message.text)
        if description == 'Отмена':
            cancel_adding_event(message.chat.id)
            return

        event = Event(description)
        event_dict[message.chat.id] = event
        # msg = bot.reply_to(message, 'Введите дату в формате  (ДД/ММ/ГГГГ)')
        now = datetime.datetime.now()  # Get the current date
        bot.reply_to(
            message,
            "Выбери дату",
            reply_markup=telebot_calendar.create_calendar(
                name=calendar_1.prefix,
                year=now.year,
                month=now.month,  # Specify the NAME of your calendar
            ),
        )
        # bot.register_next_step_handler(msg, process_date_step)
    except Exception as e:
        print(str(e))
Exemple #15
0
def get_text_messages(message):
    if user.known(message.from_user.id):
        if message.text.lower() in ['привет', 'ghbdtn', '/start', 'старт']:
            bot.send_message(
                message.from_user.id,
                get_hello_start() + user.name(message.from_user.id))
            bot.send_message(message.from_user.id,
                             command.hello_mess(message.from_user.id))
        else:
            if command.number(message.from_user.id, message.text.lower())[0]:
                command_id = command.number(message.from_user.id,
                                            message.text.lower())[1]
                bot.send_message(
                    message.from_user.id,
                    random.choice(commands[command_id].hello_words))
                if commands[command_id].ask_day:
                    calendar_1 = CallbackData("calendar_1", "action", "year",
                                              "month", "day")
                    bot.send_message(
                        message.from_user.id,
                        'с помощью клавиатуры',
                        reply_markup=telebot_calendar.create_calendar(
                            name=calendar_1.prefix,
                            year=datetime.datetime.now().year,
                            month=datetime.datetime.now().month))

                    @bot.callback_query_handler(func=lambda call: call.data.
                                                startswith(calendar_1.prefix))
                    def callback_inline(call: CallbackQuery):
                        name, action, year, month, day = call.data.split(
                            calendar_1.sep)
                        date = telebot_calendar.calendar_query_handler(
                            bot=bot,
                            call=call,
                            name=name,
                            action=action,
                            year=year,
                            month=month,
                            day=day)
                        if action == "DAY":
                            bot.send_message(
                                chat_id=call.from_user.id,
                                text=f"Вы выбрали {date.strftime('%d.%m.%Y')}",
                                reply_markup=ReplyKeyboardRemove(),
                            )
                            bot.send_message(
                                call.from_user.id,
                                commands[command_id].procedure_name)
                            result = create_tred(
                                commands[command_id].procedure_name, date)
                            bot.send_message(call.from_user.id, result[1])
                            if call.from_user.id != user.master():
                                bot.send_message(
                                    user.master(),
                                    'Хозяин, для пользователя ' +
                                    user.name(call.from_user.id) +
                                    ' было выполнено задание ' +
                                    str(command_id))
                        elif action == "CANCEL":
                            bot.send_message(
                                chat_id=call.from_user.id,
                                text="Вы решили ничего не выбирать",
                                reply_markup=ReplyKeyboardRemove(),
                            )
                else:
                    result = create_tred(commands[command_id].procedure_name,
                                         commands[command_id].procedure_arg)
                    if result[0]:
                        if commands[command_id].return_file:
                            for file in result[1].split(';'):
                                bot.send_document(message.from_user.id,
                                                  open(file, 'rb'))
                                os.remove(file)
                            if message.from_user.id != user.master():
                                bot.send_message(
                                    user.master(),
                                    'Хозяин, для пользователя ' +
                                    user.name(message.from_user.id) +
                                    ' было выполнено задание ' +
                                    str(command_id))
                        else:
                            bot.send_message(message.from_user.id, result[1])
                            if message.from_user.id != user.master():
                                bot.send_message(
                                    user.master(),
                                    'Хозяин, для пользователя ' +
                                    user.name(message.from_user.id) +
                                    ' было выполнено задание ' +
                                    str(command_id))
                    else:
                        bot.send_message(message.from_user.id, result[1])
                        if message.from_user.id != user.master():
                            bot.send_message(user.master(),\
                                'Хозяин, что-то сломалось при выполнении задания ' + str(command_id) + ' для пользователя ' + user.name(message.from_user.id) )
                            bot.send_message(user.master(), result[1])
            else:
                bot.send_message(
                    message.from_user.id,
                    'Возможно, у Вас нет прав на выполнение данной операции')
                if message.from_user.id != user.master():
                    bot.send_message(
                        user.master(), 'Хозяин, пользователь ' +
                        user.name(message.from_user.id) + ' прислал мне это:')
                    bot.send_message(user.master(), message.text.lower())
    else:
        bot.send_message(message.from_user.id, 'Я вас не знаю!')
        bot.send_message(user.master(), 'Мне написал неизвесный пользователь!')
        bot.send_message(user.master(), str(message.from_user.id))
Exemple #16
0
def send_enter_date(user_id, text):
    now = datetime.datetime.now()
    calendar_keyboard = telebot_calendar.create_calendar(calendar.prefix, now.year, now.month)
    bot.send_message(user_id, text, reply_markup=calendar_keyboard)
Exemple #17
0
def define_date(message):
    now = datetime.now()
    bot.send_message(message.chat.id,
                     "Выбери дату",
                     reply_markup=telebot_calendar.create_calendar(
                         now.year, now.month))
Exemple #18
0
import locale
import random
import string
import threading
from apscheduler.schedulers.background import BackgroundScheduler

import config

bot = telebot.TeleBot(config.TOKEN)
print(bot.get_me())

now = datetime.datetime.now()
locale.setlocale(locale.LC_ALL, "ru_RU")
calendar_1 = CallbackData("calendar_1", "action", "year", "month", "day")
my_calend = telebot_calendar.create_calendar(name=calendar_1.prefix,
                                             year=now.year,
                                             month=now.month)

temp_date = {
}  # Временная дата после выбора на календаре (ожидает подтверждения) с привязкой к ид юзера
for_reminder = {
}  # Итоговый словарь с данными обо всех датах и текстах напоминаний всех юзеров
once_or_periodic = {
}  # Одноразовая (1) или регулярная (2) проверка с привязкой к ид юзера
text_or_time = {
}  # Указывает декоратору-обработчику вводимого текста, обрабатывать его как интервал или
# как текст-напоминание (с привязкой к ид юзера)
latest_time = {
}  # Выбранное время (дата, интервал) до введения текста-напоминания (временный контейнер)
# с привязкой к ид юзера
key_to_edit = {
Exemple #19
0
def get_text_messages(message):
    if message.chat.id == int(os.getenv('id_chat_parus')):
        if 'долг' in message.text.lower() and user.known(message.from_user.id):
            try:
                id_cov = int(message.text.lower().split(' ')[1])
            except:
                return 1
            else:
                if id_cov in [33,36,37,38,51]:
                    bot.delete_message(message.chat.id,message.message_id)
                    bot.send_message(user.master(), 'запускаю поиск должников' )
                    send_Debtors(id_cov)
                    #result = create_tred('send_Debtors',id_cov)
                else:
                    return 1
        return 1
    if user.known(message.from_user.id):
        #bot.send_message(user.master(), str(message.chat.id) )
        if message.text.lower() in ['привет', 'ghbdtn','/start','старт']:
            bot.send_message(message.from_user.id, get_hello_start() + user.name(message.from_user.id))
            bot.send_message(message.from_user.id,command.hello_mess(message.from_user.id))
        elif message.text.lower() in ['Вода','djlf','вода']:
            mes = bot.reply_to(message, 'Здравствуйте '+ user.name(message.from_user.id) + ' напишите номер бутылочки.')
            bot.register_next_step_handler(mes, voda)
            
        else:
            if command.number(message.from_user.id,message.text.lower())[0]:
                command_id = command.number(message.from_user.id,message.text.lower())[1]
                bot.send_message(message.from_user.id,random.choice(commands[command_id].hello_words))
                if commands[command_id].ask_day:
                    calendar_1 = CallbackData("calendar_1", "action", "year", "month", "day")
                    bot.send_message(message.from_user.id,'с помощью клавиатуры',reply_markup=telebot_calendar.create_calendar(
                                    name=calendar_1.prefix,
                                    year=datetime.datetime.now().year,
                                    month=datetime.datetime.now().month ) )
                    @bot.callback_query_handler(func=lambda call: call.data.startswith(calendar_1.prefix))
                    def callback_inline(call: CallbackQuery):
                        name, action, year, month, day = call.data.split(calendar_1.sep)
                        date = telebot_calendar.calendar_query_handler(
                                        bot=bot, call=call, name=name, action=action, year=year, month=month, day=day
                                            )
                        if action == "DAY":
                            bot.send_message(chat_id=call.from_user.id,
                                            text=f"Вы выбрали {date.strftime('%d.%m.%Y')}",
                                            reply_markup=ReplyKeyboardRemove(),)
                            command_id = command.number(message.from_user.id,message.text.lower())[1]
                            bot.send_message(call.from_user.id,commands[command_id].procedure_name)
                            result = create_tred(commands[command_id].procedure_name,date)
                            bot.send_message(call.from_user.id,result[1])
                            logi(call.from_user.id,command_id,result)
                        elif action == "CANCEL":
                            bot.send_message(chat_id=call.from_user.id,
                                    text="Вы решили ничего не выбирать",reply_markup=ReplyKeyboardRemove(),)
                else:
                    result = create_tred(commands[command_id].procedure_name,commands[command_id].procedure_arg)
                    if result[0]:
                        if commands[command_id].return_file:
                            for file in result[1].split(';'):
                                bot.send_document(message.from_user.id, open(file, 'rb'))
                                os.remove(file)
                            logi(message.from_user.id,command_id,result)
                        else:
                            bot.send_message(message.from_user.id, result[1])
                            logi(message.from_user.id,command_id,result)
                    else:
                        bot.send_message(message.from_user.id, result[1])
                        logi(message.from_user.id,command_id,result)
            else:
                bot.send_message(message.from_user.id,'Возможно, у Вас нет прав на выполнение данной операции')
                if message.from_user.id != user.master():
                    bot.send_message(user.master(), 'Хозяин, пользователь ' + user.name(message.from_user.id) + ' прислал мне это:' )
                    bot.send_message(user.master(),message.text.lower())
    else:
        bot.send_message(message.from_user.id,'Я вас не знаю!')
        bot.send_message(user.master(),'Мне написал неизвесный пользователь!')
        bot.send_message(user.master(),str(message.from_user.id))
        bot.send_message(user.master(),str(message.from_user.username))
Exemple #20
0
def text_handler(message):
    user = users.search(Query().chatId == message.chat.id)
    if user:
        user = user[0]

        if user['stage'] == 'name_input':
            if len(message.text) > 2 and message.text.isalpha():
                users.update({'name': message.text},
                             Query().chatId == message.chat.id)

                users.update({'stage': 'phone_input'},
                             Query().chatId == message.chat.id)
                bot.send_message(message.chat.id,
                                 config.messages['reply_send_phone'])
            else:
                bot.send_message(message.chat.id,
                                 config.messages['reply_send_name_wrong'])

        if user['stage'] == 'phone_input':
            if len(message.text) >= 7:
                users.update({'phone': message.text},
                             Query().chatId == message.chat.id)

                for admin in config.admin:
                    try:
                        bot.send_message(admin, 'Новый пользователь в базе')
                    except:
                        pass

                users.update(
                    {'date': datetime.datetime.now().strftime('%d/%m/%Y %X')},
                    Query().chatId == message.chat.id)
                users.update({'stage': 'email_input'},
                             Query().chatId == message.chat.id)
                bot.send_message(message.chat.id,
                                 config.messages['reply_send_email'])
            else:
                bot.send_message(message.chat.id,
                                 config.messages['reply_send_phone_wrong'])

        if user['stage'] == 'email_input':
            if re.match(
                    '^(?!.*@.*@.*$)(?!.*@.*\-\-.*\..*$)(?!.*@.*\-\..*$)(?!.*@.*\-$)(.*@.+(\..{1,11})?)$',
                    message.text):
                users.update({'email': message.text},
                             Query().chatId == message.chat.id)

                users.update({'stage': 'country_input'},
                             Query().chatId == message.chat.id)
                bot.send_message(message.chat.id,
                                 config.messages['reply_send_country'])
            else:
                bot.send_message(message.chat.id,
                                 config.messages['reply_send_email_wrong'])

        if user['stage'] == 'country_input':
            users.update({'country': message.text},
                         Query().chatId == message.chat.id)
            if len(message.text) >= 4:
                users.update({'stage': 'start_date_input'},
                             Query().chatId == message.chat.id)
                now = datetime.datetime.now()
                chat_id = message.chat.id

                date = (now.year, now.month)
                current_shown_dates[chat_id] = date

                markup = create_calendar(now.year, now.month)

                bot.send_message(message.chat.id,
                                 config.messages['reply_send_start_date'],
                                 reply_markup=markup)
                #bot.send_message(message.chat.id, config.messages['reply_send_start_date'])
            else:
                bot.send_message(message.chat.id,
                                 config.messages['reply_send_country_short'])

        if user['stage'] == 'beds':
            try:
                users.update({'beds': int(message.text)},
                             Query().chatId == message.chat.id)
                users.update({'stage': 'budget'},
                             Query().chatId == message.chat.id)
                bot.send_message(message.chat.id,
                                 config.messages['reply_send_budget'])
            except ValueError:
                bot.send_message(message.chat.id,
                                 config.messages['reply_send_number_error'])

        if user['stage'] == 'budget':
            try:
                users.update({'budget': int(message.text)},
                             Query().chatId == message.chat.id)

                users.update({'stage': 'yacht_type'},
                             Query().chatId == message.chat.id)
                markup = telebot.types.InlineKeyboardMarkup()
                for y_type in config.yacht_types:
                    kb = telebot.types.InlineKeyboardButton(
                        text=y_type, callback_data=y_type)
                    markup.add(kb)
                bot.send_message(message.chat.id,
                                 config.messages['reply_send_yacht_type'],
                                 reply_markup=markup)
            except ValueError:
                bot.send_message(message.chat.id,
                                 config.messages['reply_send_number_error'])