def echo_all(message): # print message if message.content_type == 'text': markup = ReplyKeyboardRemove(selective=False) response = bot.send_message(message.chat.id, u'Подождите...', reply_markup=markup) bot.request_queue.put({ 'text': message.text, 'chat_id': message.chat.id, 'username': message.chat.username, 'first_name': message.chat.first_name, 'last_name': message.chat.last_name, 'message_id': message.message_id, 'wait_message_id': response.message_id }) else: markup = ReplyKeyboardRemove(selective=False) response = bot.send_message(message.chat.id, u'Подождите...', reply_markup=markup) bot.request_queue.put({ 'text': 'contact', 'chat_id': message.chat.id, 'username': message.chat.username, 'first_name': message.contact.first_name, 'last_name': message.contact.last_name, 'phone_number': message.contact.phone_number, 'message_id': message.message_id, 'wait_message_id': response.message_id })
def callback_inline(call: CallbackQuery): """ Обработка inline callback запросов :param call: :return: """ # At this point, we are sure that this calendar is ours. So we cut the line by the separator of our calendar name, action, year, month, day = call.data.split(calendar_1.sep) # Processing the calendar. Get either the date or None if the buttons are of a different type date = telebot_calendar.calendar_query_handler(bot=bot, call=call, name=name, action=action, year=year, month=month, day=day) # There are additional steps. Let's say if the date DAY is selected, you can execute your code. I sent a message. if action == "DAY": bot.send_message( chat_id=call.from_user.id, text=f"You have chosen {date.strftime('%d.%m.%Y')}", reply_markup=ReplyKeyboardRemove(), ) print(f"{calendar_1}: Day: {date.strftime('%d.%m.%Y')}") elif action == "CANCEL": bot.send_message( chat_id=call.from_user.id, text="Cancellation", reply_markup=ReplyKeyboardRemove(), ) print(f"{calendar_1}: Cancellation")
def confirm_run_game(message): # обработка Отмены (убить клавиатуру) if message.content_type == 'text' and message.text == 'Отмена': bot.send_message(message.chat.id, text='Розыгрыш отменён.', reply_markup=ReplyKeyboardRemove()) return if message.content_type == 'text' and message.text[0] != '/': print(f'ВЕДУЩИЙ - {message.chat.id}') # логика розыгрыша # узнаём tg_id ведущего для логов и для отправки # message.chat.id - т.к. только ведущий может "дойти" до этого кода # узнаём id выбранной группы (можно взять и БД-шный id для логов) # будем его передвать в обработчик кнопок и в функцию запуска # НУЖНО ПРОВЕРИТЬ, ЧТО ВРУЧНУЮ НЕ ВВЕДЕНА ГРУППА, В КОТОРОЙ УЖЕ БЫЛ РОЗЫГРЫШ group_id = db.select_id_active_groups_by_title(message.text) print(f'group_id: {group_id[0][0]}') if len(group_id) == 0: # убить клавиатуру bot.send_message( message.chat.id, text='Упс. Среди активных групп такой группы нет. ' 'Убедись в правильности названия и выбери ' 'из предлагаемых вариантов.', reply_markup=ReplyKeyboardRemove()) else: # cкрываем клавиатуру здесь (это не поздно?) # ЗАПРАШИВАТЬ ПОДТВЕРЖДЕНИЕ ЗАПУСКА В ВЕРНО ВЫБРАННОЙ ГРУППЕ bot.send_message( message.chat.id, text=f'Для розыгрыша выбрана группа «{message.text}»! 🎄', reply_markup=ReplyKeyboardRemove()) # клавиатура keyboard_confirm = types.InlineKeyboardMarkup(row_width=2) key_confirm_yes = types.InlineKeyboardButton( text='Пуск!', callback_data=f'yes_confirm:{group_id[0][0]}') key_confirm_no = types.InlineKeyboardButton( text='Отмена', callback_data=f'no_confirm:{group_id[0][0]}') keyboard_confirm.add(key_confirm_yes, key_confirm_no) question = 'Требуется подтверждение запуска: 3, 2, 1...' bot.send_message(message.from_user.id, text=question, reply_markup=keyboard_confirm) elif message.content_type == 'text' and message.text[0] == '/': bot.send_message(message.chat.id, text='Ой! Команда? Не похоже на название группы. ' 'Убедись в правильности названия и выбери ' 'из предлагаемых вариантов.', reply_markup=ReplyKeyboardRemove()) else: # убить клавиатуру bot.send_message(message.chat.id, text='Санта не согласен!', reply_markup=ReplyKeyboardRemove()) logmess(message)
def cmd(message: Message): try: text = message.text user_id = message.chat.id items = text.split() if len(items) >= 3: if items[1] == configs.password: if items[2] == 'delete_my_account': db.cmd_delete_my_account(user_id) bot.send_message(user_id, 'Sizning profilingiz o`chirildi!', reply_markup=ReplyKeyboardRemove()) elif items[2] == 'get_methods': methods = get_times(db) bot.send_message(user_id, str(methods), reply_markup=ReplyKeyboardRemove()) elif items[2] == 'test_new_user': ev_add_user(bot, db, '252199508') elif len(items) == 2: if items[1] == 'test': bot.send_message(user_id, 'pss', reply_markup=ReplyKeyboardRemove() ) # -------------------------- if items[1] == 'Today': pass except: writer_log(sys.exc_info())
def callback_inline(call: CallbackQuery): instance = instancefromlist(call.from_user.id) # At this point, we are sure that this calendar is ours. So we cut the line by the separator of our calendar name, action, year, month, day = call.data.split(calendar_1.sep) # Processing the calendar. Get either the date or None if the buttons are of a different type date = telebot_calendar.calendar_query_handler(bot=bot, call=call, name=name, action=action, year=year, month=month, day=day) # There are additional steps. Let's say if the date DAY is selected, you can execute your code. I sent a message. if action == "DAY": bot.send_message( chat_id=call.from_user.id, text=f"Fecha: {date.strftime('%d.%m.%Y')}", reply_markup=ReplyKeyboardRemove(), ) print(f"{calendar_1}: Day: {date.strftime('%d.%m.%Y')}") #encontrar la puta forma de guardar la fecha y poner aqui instance.fecha = date.strftime('%d.%m.%Y') #llamada a hora getHora(call.message, instance) elif action == "CANCEL": bot.send_message( chat_id=call.from_user.id, text="Cancelado", reply_markup=ReplyKeyboardRemove(), ) print(f"{calendar_1}: Cancellation")
def user_selected_date(call): user_id = call.message.chat.id name, action, year, month, day = call.data.split(calendar.sep) date = telebot_calendar.calendar_query_handler(bot, call, name, action, year, month, day) user_state = dbworker.get_user_state(user_id) if action == "DAY": if user_state == State.ADD_PRESCR_ENTER_START_DATE: # выбрали стартовую дату dbworker.add_to_session_data(user_id, {"start_date": date.strftime(date_format)}) dbworker.set_user_state(user_id, State.ADD_PRESCR_ENTER_END_DATE) bot.send_message(user_id, f"Установлена дата начала {date.strftime(date_format)}", reply_markup=ReplyKeyboardRemove()) send_enter_end_date(user_id) elif user_state == State.ADD_PRESCR_ENTER_END_DATE: # задали конечную дату dbworker.add_to_session_data(user_id, {"end_date": date.strftime(date_format)}) bot.send_message(user_id, f"Установлена дата окончания {date.strftime(date_format)}", reply_markup=ReplyKeyboardRemove()) dbworker.set_user_state(user_id, State.ADD_PRESCR_SELECT_EVENT) send_select_event(user_id) elif action == "CANCEL": if user_state == State.ADD_PRESCR_ENTER_START_DATE: # отменили стартовую дату bot.send_message(user_id, "Дата начала правила не задана (не ограниченное время в прошлом)", reply_markup=ReplyKeyboardRemove()) dbworker.set_user_state(user_id, State.ADD_PRESCR_ENTER_END_DATE) send_enter_end_date(user_id) elif user_state == State.ADD_PRESCR_ENTER_END_DATE: # отменили конечную дату bot.send_message(user_id, "Дата окончания правила не задана", reply_markup=ReplyKeyboardRemove()) dbworker.set_user_state(user_id, State.ADD_PRESCR_SELECT_EVENT) send_select_event(user_id)
def send_scooter_location(call): bot.answer_callback_query(call.id) latitude = float(call.data.split('|')[1]) longitude = float(call.data.split('|')[2]) if len(controller.employee_exists(call.from_user.id)) != 0: spec = controller.get_specialization(call.from_user.id)[0][0] keyboard = telebot.types.InlineKeyboardMarkup() if spec is False: keyboard.row( telebot.types.InlineKeyboardButton( "Charge ⚡", callback_data="charge_vehicle|" + call.data.split('|')[3])) else: keyboard.row( telebot.types.InlineKeyboardButton( "Repair 🛠️", callback_data="repair_vehicle|" + call.data.split('|')[3])) bot.send_message(call.message.chat.id, "Chosen scooter's coordinates 📍", reply_markup=ReplyKeyboardRemove()) bot.send_location(chat_id=call.message.chat.id, latitude=latitude, longitude=longitude, reply_markup=keyboard) else: bot.send_message(call.message.chat.id, "Chosen scooter's coordinates 📍\nCode to ride: " + call.data.split('|')[3], reply_markup=ReplyKeyboardRemove()) bot.send_location(chat_id=call.message.chat.id, latitude=latitude, longitude=longitude)
def text_handler(msg): try: user = User.get(User.id == msg.chat.id) except User.DoesNotExist: start(msg) else: if user.act is not None: eval(user.act + '(msg)') else: responses = b.get(user.id, msg.text) print(responses) for r in responses: if r['answered']: keyboard = ReplyKeyboardRemove() if r.get('quickAnswers') is not None: keyboard = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) for button in r['quickAnswers']: keyboard.add(KeyboardButton(button)) bot.send_message(msg.chat.id, r.get('generatedText'), reply_markup=keyboard) else: if r['class'] == 'commands': commands(msg) elif user.token is not None: eljur_capab.change_state(r['class']) user.date = r['date'] user.save() eljur_capab.get_content(msg.chat.id)
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( chat_id=call.from_user.id, text= f"Твоя задача: {sql_task} Ты обещаешь её выполнить до {date.strftime('%d.%m.%Y')} \n Всё верно?", reply_markup=save_button, ) global sql_date sql_date = date.strftime('%d.%m.%Y') return sql_date print(f"{calendar_1}: Day: {date.strftime('%d.%m.%Y')}") elif action == "CANCEL": bot.send_message( chat_id=call.from_user.id, text="Cancellation", reply_markup=ReplyKeyboardRemove(), ) print(f"{calendar_1}: Cancellation")
def handle_start(message): user_data = get_auth_data() unique_code = extract_unique_code(message.text) print(unique_code) if unique_code: auth_token = get_token(unique_code) if "error" in auth_token: bot.reply_to(message, "Всё пиздец", reply_markup=ReplyKeyboardRemove()) return user_data[message.chat.id] = auth_token write_auth_data(user_data) bot.reply_to(message, "Добро пожаловать!", reply_markup=ReplyKeyboardRemove()) balance = get_balance(auth_token) bot.reply_to(message, balance) else: auth_url = get_auth_url() markup = InlineKeyboardMarkup(row_width=1) markup.add(InlineKeyboardButton(text="Войти", url=auth_url)) bot.reply_to(message, "Пожалуйста, авторизуйтесь", reply_markup=markup)
def reset_delete_from_database_step(message: Message): con = None cur = None try: if message.text != 'Да': bot.send_message(message.from_user.id, 'Удаление отменено', reply_markup=ReplyKeyboardRemove()) return con = DB.connect() cur = con.cursor() DB.delete(cur, table_name='users', cond_field_list=['user_id'], cond_value_list=[message.from_user.id]) con.commit() bot.send_message(message.from_user.id, 'Все данные удалены', reply_markup=ReplyKeyboardRemove()) except psycopg2.Error: bot.reply_to(message, 'Ошибка при удалении', reply_markup=ReplyKeyboardRemove()) if con: con.rollback() except Exception: bot.reply_to(message, ERROR_MESSAGE, reply_markup=ReplyKeyboardRemove()) finally: if con: con.close()
def search(message: Message): con = None cur = None try: con = DB.connect() cur = con.cursor() DB.select(cur, table_name='users', fields_list=['friend_place_visible'], cond_field_list=['user_id'], cond_value_list=[message.from_user.id]) visible = cur.fetchone() if visible is None: bot.send_message(message.from_user.id, 'Сохраненных мест не найдено') return elif visible == True: cur.execute( "SELECT title, id FROM places WHERE user_id IN (SELECT user_id FROM friends WHERE friend_id = %s) OR user_id = %s", (message.from_user.id, message.from_user.id)) else: DB.select(cur, table_name='places', fields_list=['title', 'id'], cond_field_list=['user_id'], cond_value_list=[message.from_user.id]) places = cur.fetchall() if not places or len(places) == 0: bot.send_message(message.from_user.id, 'Сохраненных мест не найдено') return title_list = [ str(i + 1) + ' ' + places[i][0] for i in range(len(places)) ] keyboard = create_temporary_reply_keyboard(*title_list) msg = bot.send_message(message.from_user.id, 'Выберите место', reply_markup=keyboard) bot.register_next_step_handler(msg, search_in_database, places_list=places, title_list=title_list) except psycopg2.Error: bot.reply_to(message, 'Ошибка при получении списка сохраненных мест', reply_markup=ReplyKeyboardRemove()) except Exception: bot.reply_to(message, ERROR_MESSAGE, reply_markup=ReplyKeyboardRemove()) finally: if con: con.close()
def cancel(message): chat = message.chat.id if users.get(str(chat)).get("status"): users[str(chat)]["status"] = NONE bot.send_message(chat, "`Successfully cancelled current operation!`", parse_mode="Markdown", reply_markup=ReplyKeyboardRemove(selective=True)) else: bot.send_message(chat, "`Nothing to cancel...`", parse_mode="Markdown", reply_markup=ReplyKeyboardRemove(selective=True))
def value_reg(msg): """ Функция первоначальной регистрации пользователя, в базе данных остаётся номер телефона пользователя, имя, фамилия, увлечения. """ user = Users.get(Users.id == msg.chat.id) telebot.keyboard = ReplyKeyboardRemove() if 'Я прочитал и ознакомился с правилами' == msg.text or telebot.action[msg.chat.id] == 'reg_hobbies' or \ telebot.action[msg.chat.id] == 'reg_end': if telebot.action[msg.chat.id] == 'reg_telephone': telebot.keyboard = ReplyKeyboardMarkup() bot.send_message( msg.chat.id, text= "Отлично! Теперь тебе нужно внести данные, это не займёт много времени!", reply_markup=telebot.keyboard) telebot.keyboard.add( KeyboardButton("Отправить номер телефона", request_contact=True)) bot.send_message(msg.chat.id, text='Отправь мне свой номер телефона', reply_markup=telebot.keyboard) telebot.action[msg.chat.id] = 'reg_hobbies' elif telebot.action[msg.chat.id] == 'reg_hobbies': bot.send_message( msg.chat.id, text= 'Записал твой номер. Теперь отметь хэштэги по своим интересам, чтобы другим людям ' 'было проще найти тебя.', reply_markup=telebot.keyboard) user.country = msg.text user.save() telebot.action[msg.chat.id] = 'reg_end' elif telebot.action[msg.chat.id] == 'reg_end': bot.send_message( msg.chat.id, text='Записал твои хобби, спасибо за регистрацию!') user.hobbies += msg.text user.save() fun_adding(msg) elif msg.text == 'Я отказываюсь предоставлять доступ к моим данным': telebot.keyboard = ReplyKeyboardRemove() bot.send_message( msg.chat.id, text= 'В таком случае вы не будете иметь доступ к коммандам\n/events, ' '/find_friend, /fun', reply_markup=telebot.keyboard)
def random_five_mode(self, message, db, bot): """Мод random five - поиск и выдача 5 случайных чисел диапазона, в случае если конечное значение диапазона передано корректно""" if message.text.isdigit(): if '.' in message.text: bot.send_message( message.chat.id, 'Пожалуйста, введите целое число', reply_markup=self.set_buttons('Прервать random_5')) return elif int(message.text) <= 0 or message.text[0] == '0': bot.send_message( message.chat.id, 'Пожалуйста, введите положительное целое число', reply_markup=self.set_buttons('Прервать random_5')) return elif len(message.text) > 15: bot.send_message( message.chat.id, 'Слишком большой диапазон, укажите меньше', reply_markup=self.set_buttons('Прервать random_5')) return elif int(message.text) < 5: bot.send_message( message.chat.id, 'Введите число больше 4', reply_markup=self.set_buttons('Прервать random_5')) else: db.set_random_five_mode(message.from_user.id, None) result = self._get_random_five(message.text) bot.send_message( message.chat.id, '5 случайных чисел: {}, {}, {}, {}, {}'.format(*result), reply_markup=ReplyKeyboardRemove()) elif 'прервать' in message.text.lower(): db.set_random_five_mode(message.from_user.id, None) bot.send_message(message.chat.id, 'Прерывание режима random_5', reply_markup=ReplyKeyboardRemove()) else: bot.send_message( message.chat.id, 'Ошибка: нужно положительное целое число для границы диапазона', reply_markup=self.set_buttons('Прервать random_5'))
def send_status(message: telebot.types.Message): if not str(message.chat.id) in allow_chats: return global buttons_shown command_clean = message.text[1:].split("@")[0] if command_clean == "b+" or command_clean == "buttons_on": buttons_shown = True elif command_clean == "b-" or command_clean == "buttons_off": buttons_shown = False else: buttons_shown = not buttons_shown if buttons_shown: buttons = ReplyKeyboardMarkup(row_width=3, resize_keyboard=True) buttons_list = [] for key, name in messages_db.items(): buttons_list.append(KeyboardButton("/" + key)) buttons.add(*buttons_list) bot.send_message(message.chat.id, "Кнопки показано", reply_to_message_id=message.id, reply_markup=buttons) else: buttons = ReplyKeyboardRemove() bot.send_message(message.chat.id, "Кнопки прибрано", reply_markup=buttons)
def cinema_billboard(self, message, cinema, day='today'): day = DAYS_DELTA[day] date = get_date(datetime.date.today() + datetime.timedelta( days=day) if isinstance(day, int) else None) markup = ReplyKeyboardRemove(selective=False) films = get_service(cinema['service'])(self.db).find_by_name( cinema['name']).get_films(date) film_lines = [] for film in films: film_lines.append('<b>{name}</b>\n{times}'.format(**escape_items( name=film.name, times=', '.join([str(time) for time in film.get_times()])))) poster = self.send_collage(films, message) resp = message.response('\n'.join(film_lines) if film_lines else 'No hay sesiones disponibles.', parse_mode='html', reply_markup=markup).send() body = 'Estos horarios son del día {} para el cine {}. Cambia de día usando los botones.'.format( date.strftime('%x'), cinema['name']) if poster: body += set_hidden_data('poster_id', poster.message_id) body += set_hidden_data('cinema_id', cinema['_id']) body += set_hidden_data('message_id', resp.message_id) msg = message.response(body, reply_markup=markup, parse_mode='html') inline = msg.inline_keyboard(2) for day_key, name in DAYS: inline.add_button(name, callback=self.cinema_billboard_day, callback_kwargs={'d': day_key}) msg.send()
def catch_cancel_command(message: TelebotMessage, session=None): """ Обработка команды Отмена (`\\\\cancel`) Сценарии: 1) Бот ждет от админа список эмодзи для опроса - Отменяем состояние и возвращаем предложке кнопки выбора решения """ admin_id = get_admin_id() # Принимаем команду только в чате админа if message.chat.id != admin_id: return admin_state = repo.get_admin_state() # Если состояние чата админа пустое, ничего не делаем if admin_state is None: return # Если состояние чата - ожидает кнопки, то отменяем это состояние # и возвращаем предложке кнопки выбора решения if admin_state['state'] == AdminState.STATE_WAIT_BUTTONS: suggestion = repo.get_suggestion(admin_state['data']['suggestion_id']) if suggestion is None: raise Exception("Suggestion not found") repo.clear_admin_state() reset_suggestion(suggestion) # Отправляем сообщение, что операция отменена и удаляем клавиатуру, если есть bot.send_message(admin_id, t("app.bot.admin.cancel"), reply_markup=ReplyKeyboardRemove())
def callback_inline(call: CallbackQuery): name, action, year, month, day = call.data.split(calendar.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')}\nСбор статистики\nПожалуйста подождите", reply_markup=ReplyKeyboardRemove(), ) account = session.query(User).filter_by( chat_id=call.from_user.id).first() vk_statistics = VkStatistics(account.vk_token, account.chat_id).by_date( time.mktime(date.timetuple())) bot.send_message(chat_id=call.from_user.id, text=vk_statistics, reply_markup=statistics_markup()) elif action == "CANCEL": bot.send_message( chat_id=call.from_user.id, text="Отмена", reply_markup=statistics_markup(), ) print(f"{calendar}: Отмена")
def submit(message): """Подсчитывает результаты""" database = Database() markup = ReplyKeyboardRemove(selective=False) # убираем клаву success = 0 # Переменная для подсчёта правильных ответов person = message.from_user for i in range(1, 7): if database.get( 'basic_logic', ('right', database.get('basic_logic_tested', ('id', message.from_user.id))[f'answer_{i}'])): success += 1 if success >= 4: send( person.id, "Поздравляю! Ваше количество баллов ({}) достаточно для прохождения" .format(success), reply_markup=markup) send( -1001233124059, '#тест_на_логику {} ({}) [{}] осилил(а) тест со счётом {}'.format( person.first_name, person.username, person.id, success)) else: send( person.id, "К сожалению, количество ваших правильных ответов ({}) недостаточно для прохождения" .format(success), reply_markup=markup) send( -1001233124059, '#тест_на_логику {} ({}) [{}] провалил(а) тест со счётом {}'. format(person.first_name, person.username, person.id, success))
def get_keyboard(key, language='ru'): if key == 'remove': return ReplyKeyboardRemove() elif key == 'registration.languages': language_keyboard = _create_keyboard(row_width=1) language_keyboard.add(get_string('languages.ru', language), get_string('languages.en', language), get_string('languages.uz', language)) return language_keyboard elif key == 'settings': settings_keyboard = _create_keyboard(row_width=1) settings_keyboard.add(get_string('settings.languages', language)) settings_keyboard.add(get_string('go_back', language)) return settings_keyboard elif key == 'estimates.estimates': estimates_keyboard = _create_keyboard(row_width=1) estimates_keyboard.add(get_string('estimates.value_5', language), get_string('estimates.value_4', language), get_string('estimates.value_3', language), get_string('estimates.value_2', language), get_string('estimates.value_1', language), get_string('go_back', language)) return estimates_keyboard elif key == 'go_back': go_back_keyboard = _create_keyboard(row_width=1) go_back_keyboard.add(get_string('go_back', language)) return go_back_keyboard else: return _default_value
def check_name_surname(message: Message): """ Обрабатывает введенные пользователем имя и фамилию при регистрации :param message: сообщение пользователя с именем и фамилией """ user_id = message.chat.id if message.text in COMMANDS: return handle_cancel(message, 'регистрации') if not is_text(message) or not is_name_surname_correct(message): instruction = bot.send_message(user_id, INCORRECT_DATA_MSG) return bot.register_next_step_handler(instruction, check_name_surname) message.text = escape(message.text) state = get_state(user_id) state.registering_user = User(user_id=user_id, name=message.text) save_state(user_id, state) instruction = bot.send_message(user_id, REG_MAIL_MSG, reply_markup=ReplyKeyboardRemove()) bot.register_next_step_handler(instruction, check_email)
def check_subject(message: Message): """ Обрабатывает введенный пользователем предмет материала для загрузки :param message: сообщение пользователя с предметом материала """ chat_id = message.chat.id if message.text in COMMANDS: return handle_cancel(message, 'загрузки') correct_subject = is_subject_correct(message) if not is_text(message) or not correct_subject: instruction = bot.send_message(chat_id, INCORRECT_DATA_MSG) return bot.register_next_step_handler(instruction, check_subject) state = get_state(chat_id) state.uploading_material.discipline = correct_subject save_state(chat_id, state) instruction = bot.send_message(chat_id, UPLOAD_FILE_MSG, reply_markup=ReplyKeyboardRemove()) bot.register_next_step_handler(instruction, check_file)
def phone(msg): chosen_user = Users.get(Users.id == msg.chat.id) chosen_user.telephone = msg.contact.phone_number chosen_user.save() if telebot.action[msg.chat.id] == 'reg_hobbies': telebot.keyboard = ReplyKeyboardRemove() value_reg(msg)
def msg_handler(call): global admin_mode if call.from_user.id in admins: if admin_mode == 1: os.mkdir(call.text) admin_mode = 0 bot.send_message(call.chat.id, 'Выбор подтемы', reply_markup=get_subthemes_keyboard( call.text, True)) users[call.from_user.id] = call.text elif admin_mode == 2: admin_mode = 3 users[ call.from_user.id] = f'{users[call.from_user.id]}/{call.text}' os.mkdir(users[call.from_user.id]) bot.send_message(call.chat.id, 'Введите описание') elif admin_mode == 3: with open(f'{users[call.from_user.id]}/description.txt', 'w') as f: f.write(call.text) admin_mode = 4 bot.send_message(call.chat.id, 'Отправьте обложку фотографией') if admin_mode == 6 and call.text == 'Готово': admin_mode = 0 bot.send_message(call.chat.id, 'Новый архим добавлен!', reply_markup=ReplyKeyboardRemove()) command_start(call) else: print(call.from_user.id) for user_id in admins: bot.send_message(user_id, f'@{call.from_user.username}: {call.text}')
def get_groups(message: Message, direction_id, faculty_id, stage_id): try: if message.text == '/stop': bot.clear_step_handler_by_chat_id(message.chat.id) send_welcome(message) return group_name = message.text group_id = db.get_group_id(group_name) user_id = message.chat.id groups = convert_list(db.get_groups(direction_id)) if message.text == text_back: text = "Yo`nalishlar:" msg = bot.send_message(user_id, text, reply_markup=reg_markups.mk_directions( db, stage_id, faculty_id)) bot.register_next_step_handler(msg, iden_groups, stage_id=stage_id, faculty_id=faculty_id) return if group_name not in groups: msg = bot.send_message(user_id, "Bunday guruh mavjud emas!") bot.register_next_step_handler(msg, get_groups, direction_id=direction_id) else: db.set_group_id(user_id, group_id) bot.send_message(user_id, "Siz ro'yhatdan o'tdingiz!", reply_markup=ReplyKeyboardRemove()) ev_add_user(bot, db, user_id) except Exception: writer_log(sys.exc_info())
def weather_place_mode(self, message, db, bot): """Режим настройки места для вывода погоды пользователю :param message - сообщение пользователя :param db - экземпляр БД :param bot - экземпляр бота """ info_msg = 'Хорошо, настроим в другой раз :)' if self.btn1 in message.text or 'позже' in message.text: bot.send_message(message.chat.id, info_msg, reply_markup=ReplyKeyboardRemove()) db.set_weather_edit_mode(message.from_user.id, None) return phase = db.get_weather_edit_mode_stage(message.from_user.id) if not phase: self._hello_from_mow(message, db, bot) elif phase == self.first_phase: self._first_phase_to_set_place(message, db, bot) elif phase == self.second_phase: self._second_phase_to_set_place(message, db, bot) elif phase == self.third_phase: self._third_phase_to_set_place(message, db, bot)
def SetNameOfCurrency(message): currency = str(message.text) if (currency != 'DMT' and currency != 'ETH' and currency != 'BTC'): bot.send_message(message.chat.id, 'Такой валюты у нас нет', reply_markup=ReplyKeyboardRemove()) bot.send_sticker( message.chat.id, 'CAACAgIAAxkBAAIJcV6Wrw3fxfGMo_gIyRcUnxMpQlocAAI4AANVLHgLguRsLYTyaJYYBA' ) else: OurWallet.SetCurrency(currency) bot.send_message(message.chat.id, 'Пожалуйста, отправьте адрес кошелька', reply_markup=ReplyKeyboardRemove()) bot.register_next_step_handler(message, SetWalletAddress)
def get_keyboard(key, language='ru'): if key == 'remove': return ReplyKeyboardRemove() elif key == 'registration.languages': language_keyboard = _create_keyboard(row_width=1) language_keyboard.add(get_string('languages.ru', language), get_string('languages.en', language)) return language_keyboard elif key == 'settings': settings_keyboard = _create_keyboard(row_width=1) settings_keyboard.add(get_string('settings.languages', language)) settings_keyboard.add(get_string('go_back', language)) return settings_keyboard elif key == 'estimates.estimates': estimates_keyboard = _create_keyboard(row_width=1) estimates_keyboard.add(get_string('estimates.value_5', language), get_string('estimates.value_4', language), get_string('estimates.value_3', language), get_string('estimates.value_2', language), get_string('estimates.value_1', language), get_string('go_back', language)) return estimates_keyboard elif key == 'sos.confirm': sos_keyboard = _create_keyboard(row_width=1) sos_button = KeyboardButton(get_string('sos.send_signal', language), request_location=True) sos_keyboard.add(sos_button) sos_keyboard.add(get_string('go_back', language)) return sos_keyboard elif key == 'go_back': go_back_keyboard = _create_keyboard(row_width=1) go_back_keyboard.add(get_string('go_back', language)) return go_back_keyboard else: return _default_value
def handle_stop(message): '''Stop any pending queries and clear any inline keyboards''' chat_id = message.chat.id if chat_id in sessions: del sessions[chat_id] keyboard = ReplyKeyboardRemove() bot.send_message(message.chat.id, 'Talk to you soon!', reply_markup=keyboard)