def command(messages, connection): import locals.ru as lang if messages.reply_to_message is None: return ["Error #1"], None result_user = connection.execute("SELECT `Houses` FROM `users` WHERE `tID` = {}".format(messages.reply_to_message.chat.id)) result_extracts = connection.execute("SELECT `Peasants`, `Ready` FROM `extraction` WHERE `tID` = {}".format(messages.reply_to_message.chat.id)) result_user = result_user.fetchone() result_extracts = result_extracts.fetchall() workers = result_user["Houses"] * 3 for i in result_extracts: if i["Ready"] is False: continue workers = workers - i["Peasants"] from telebot.types import ForceReply try: w_int = int(messages.text) if w_int == 0: return [lang.work_cancel], None elif workers < w_int or w_int < 0: return [lang.few_workers, lang.how_count_workes_stone], {"reply_markup": ForceReply()} else: connection.execute("INSERT INTO `extraction` (`tID`, `Peasants`, `Material`) VALUES ({}, {}, \"Stone\")".format(messages.chat.id, messages.text)) connection.commit() return [lang.how_time_workes_stone], {"reply_markup": ForceReply()} except: return [lang.how_count_workes_stone], {"reply_markup": ForceReply()}
def command(messages, connection): import locals.ru as lang from telebot.types import ForceReply try: time = int(messages.text) if time < 1 or time > 10: return [lang.how_time_workes_stone], {"reply_markup": ForceReply()} connection.execute( "UPDATE `extraction` SET `Times` = {}, `TimesAll` = {}, `Ready` = 1 WHERE `tID` = {}" .format(time * 60, time * 60, messages.chat.id)) connection.commit() return [lang.work_add], None except: return [lang.how_time_workes_stone], {"reply_markup": ForceReply()}
def select_educator(message): bot.send_chat_action(message.chat.id, "typing") name = message.text.strip(". ") if not nf.is_correct_educator_name(name): error_answer = "Недопустимые символы!" is_error = True else: data = spbu.search_educator(name) if not data["Educators"] or len(data["Educators"]) > 10: if data["Educators"]: error_answer = "Слишком много преподавателей!" else: error_answer = "Никого не найдено!" is_error = True else: is_error = False error_answer = "" bot.send_message( chat_id=message.chat.id, text="Готово!", reply_markup=ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False).row( "Завершить", "Поддержка")) bot.send_message(chat_id=message.chat.id, text="Выбери преподавателя:", reply_markup=found_educators_keyboard(data)) if is_error: bot.send_message(chat_id=message.chat.id, text=error_answer) bot.send_message(chat_id=message.chat.id, text=ask_to_input_educator_register, reply_markup=ForceReply())
def upload_file(bot, query, current_folder_id): # ask for file to upload and link to the current folder message = bot.send_message(chat_id=query.message.chat.id, text="Upload a file to this folder.", reply_markup=ForceReply(selective=False)) bot.register_next_step_handler(message, process_uploaded_file, current_folder_id, bot)
def registration(message: Message): user = message.from_user.id status_text = str( getattr(message, 'return_text', 'Вы заходите первый раз!\n')) if '/student' in message.text: user_obj = Student text = status_text + NEW_STUDENT bottoms = Bottoms_stud name = [3, 2] else: user_obj = Teacher text = status_text + NEW_TEACHER bottoms = Bottoms_teacher name = [2, 1] user_data = user_obj(user).data if user_data: markup = ReplyKeyboardMarkup(row_width=1) markup.add(*map(KeyboardButton, bottoms)) text = f'Привет {" ".join(user_data[i].capitalize() for i in name)}' else: deque_work(user, 'w', user_obj._type) markup = ForceReply(selective=False) return {'text': text, 'reply_markup': markup}
def educator_schedule_handler(message): bot.send_chat_action(message.chat.id, "typing") answer = "Введи Фамилию преподавателя: <i>(и И. О.)</i>" markup = ForceReply(False) bot.send_message(message.chat.id, answer, reply_markup=markup, parse_mode="HTML")
def input_educator_name_handler(call_back): bot.edit_message_text(text=call_back.data, chat_id=call_back.message.chat.id, message_id=call_back.message.message_id) bot.send_message(chat_id=call_back.message.chat.id, text=ask_to_input_educator_register, reply_markup=ForceReply(), parse_mode="HTML")
def command(messages, connection): import locals.ru as lang mess = messages.text.split('_') len_mess = len(mess) if len_mess == 1: return [lang.menu_workes], {"parse_mode": None} if len_mess >= 2: from telebot.types import ForceReply if mess[1] == "wood": return [lang.how_count_workes_wood], {"reply_markup": ForceReply()} elif mess[1] == "stone": return [lang.how_count_workes_stone], { "reply_markup": ForceReply() } else: return [lang.menu_workes], {"parse_mode": None} return [lang.menu_workes], {"parse_mode": None}
def educator_schedule_handler(message): user = g.current_tbot_user bot.send_chat_action(user.tg_id, "typing") bot.send_message(chat_id=user.tg_id, text=ask_to_input_educator, reply_markup=ForceReply(), parse_mode="HTML")
def welcome(self, message: Message): self.log.msg("introducing myself", user_id=message.from_user.id, user_first_name=message.from_user.first_name, chat_id=message.chat.id) self.bot.reply_to( message, self.lang['welcome'], reply_markup=ForceReply( input_field_placeholder=self.lang['input field placeholder']))
def create_new_folder(bot, query, current_folder_id): # create new folder obj msg = "Creating a new folder in the directory.\n \ Please send me the name of the new folder." message = bot.send_message(chat_id=query.message.chat.id, text=msg, reply_markup=ForceReply(selective=False)) bot.register_next_step_handler(message, process_create_folder, current_folder_id, bot)
def write_educator_name_handler(message): bot.send_chat_action(message.chat.id, "typing") answer = "" name = message.text.strip(". ") if not func.is_correct_educator_name(name): answer = "Недопустимые символы" bot.send_message(message.chat.id, answer, reply_markup=schedule_keyboard) return try: educators_data = spbu.search_educator(name) except spbu.ApiException: answer = "Во время выполнения запроса произошла ошибка." bot.send_message(message.chat.id, answer, reply_markup=schedule_keyboard) return if not educators_data["Educators"]: answer = "Никого не найдено" bot.send_message(message.chat.id, answer, reply_markup=schedule_keyboard) elif len(educators_data["Educators"]) > 200: answer = "Слишком много преподавателей\n" \ "Пожалуйста, <b>уточни</b>" bot.send_message(message.chat.id, answer, parse_mode="HTML") answer = "Введи Фамилию преподавателя: <i>(и И. О.)</i>" markup = ForceReply(False) bot.send_message(message.chat.id, answer, reply_markup=markup, parse_mode="HTML") else: bot.send_message(message.chat.id, "Готово!", reply_markup=schedule_keyboard) educators_keyboard = InlineKeyboardMarkup(row_width=2) educators_keyboard.add(*[ InlineKeyboardButton(text=educator["DisplayName"], callback_data=str(educator["Id"])) for educator in educators_data["Educators"] ]) educators_keyboard.row( InlineKeyboardButton(text="Отмена", callback_data="Отмена")) answer = "{0} Найденные преподаватели:\n\n".format( emoji["mag_right"]) + answer bot.send_message(message.chat.id, answer, reply_markup=educators_keyboard, parse_mode="HTML")
def command(messages, connection): import locals.ru as lang if messages.reply_to_message is None: return ["Error #1"], None if len(messages.text) < 3 or len(messages.text) > 15: from telebot.types import ForceReply return [lang.set_name_length, lang.set_name], { "reply_markup": ForceReply() } result = connection.execute( "SELECT `Nickname` FROM `users` WHERE `Nickname`= \"{}\"".format( messages.text)) if result.fetchone() is not None: from telebot.types import ForceReply return [lang.busy_name], {"reply_markup": ForceReply()} connection.execute( "UPDATE `users` SET `Nickname` = \"{}\" WHERE `tID` = {}".format( messages.text, messages.chat.id)) connection.commit() return [lang.set_name_successfully.format(messages.text)], None
def user_identity_query_handler(call): tb.edit_message_text( f"Ви обрали: *{call.data.split('identity_markup=')[1]}*", call.message.chat.id, call.message.message_id, reply_markup=None, parse_mode='Markdown') tb.answer_callback_query(callback_query_id=call.id) tb.send_message(call.message.chat.id, "Ваше ПІБ?", reply_markup=ForceReply(selective=False))
def _process_specified_stock(message, bot): ticker = message.text chat_id = message.chat.id if _stock_exists(ticker): stock = Stock(ticker.upper()) send_text = stock.get_stock_details() bot.send_message(chat_id, text=send_text, reply_markup=get_stock_markup(ticker.upper())) else: msg = bot.send_message(chat_id, text="Please input a valid stock.", reply_markup=ForceReply()) bot.register_next_step_handler(msg, _process_specified_stock, bot)
def feedback_handler(call_back): markup = ForceReply(False) try: bot.edit_message_text(text="Обратная связь", chat_id=call_back.message.chat.id, message_id=call_back.message.message_id) except ApiException: pass finally: answer = "Напиши мне что-нибудь:" bot.send_message(call_back.message.chat.id, answer, reply_markup=markup)
def feedback_handler(call_back): user = g.current_tbot_user bot.edit_message_text( chat_id=user.tg_id, text="Обратная связь", message_id=call_back.message.message_id ) bot.send_message( chat_id=user.tg_id, text=ask_to_feedback, reply_markup=ForceReply() )
def handle_select_action(bot, query): chat_id = query.message.chat.id message_id = query.message.message_id if query.data == 'psei': stock = Stock('PSEI') send_text = stock.get_stock_details() bot.edit_message_text(text=send_text, chat_id=chat_id, message_id=message_id, reply_markup=get_stock_markup('PSEI')) if query.data == 'stock': send_text = "Input a stock ticker:" msg = bot.send_message(chat_id, text=send_text, reply_markup=ForceReply()) bot.register_next_step_handler(msg, _process_specified_stock, bot)
def process_create_folder(message, folder_id, bot): chat_id = message.chat.id if message.text is None or message.text == "": message = bot.send_message( chat_id=chat_id, text="Please send me the name of the new folder.", reply_markup=ForceReply(selective=False)) bot.register_next_step_handler(message, process_create_folder, folder_id, bot) # add exception handling here db.insert_folder(message.chat.id, message.text, folder_id) bot.send_message(chat_id=chat_id, text="Folder created.") display_folder_contents(bot, chat_id, page=1, folder_id=folder_id)
def callback_func(call): if call.data == 'new_acc': if db.is_exist(tg_id=call.message.chat.id): bot.send_message(call.message.chat.id, dict.ALREADY_EXIST) return _uuid = get_uuid() bot.edit_message_text(text=dict.NEW_ACC_MESSAGE.format(id=_uuid), chat_id=call.message.chat.id, message_id=call.message.id) db.insert_new_connection(_uuid=_uuid, tg_id=call.message.chat.id) elif call.data == 'ex_acc': markup = ForceReply(selective=False) bot.delete_message(call.message.chat.id, call.message.id) bot.send_message(call.message.chat.id, dict.EX_ACC_MESSAGE, reply_markup=markup) def next_handler_step(message): try: __uuid = str(uuid.UUID(message.text)) if db.is_exist(_uuid=__uuid): if not db.get_ids(_uuid=__uuid)[0][2]: db.update_connection({'uuid': __uuid}, {'tgID': message.chat.id}) bot.send_message(message.chat.id, "Your account is full registered") else: bot.send_message( message.chat.id, "This account is already registered!") else: bot.send_message(message.chat.id, 'Wrong id! Try again...') except ValueError: bot.send_message(message.chat.id, 'Wrong id! Try again...') bot.register_next_step_handler(call.message, next_handler_step) elif 'reply_to' in call.data: if db.get_tg_state(call.message.chat.id) == TgUserState.INITIAL: vk_peer_id = call.data[9:] call.data = vk_peer_id get_chat_id(call) else: bot.send_message(call.message.chat.id, 'Something went wrong! Try again') db.insert_or_update_tg_state(call.message.chat.id, TgUserState.INITIAL)
def write_educator_name_handler(message): user = g.current_tbot_user bot.send_chat_action(user.tg_id, "typing") name = message.text.strip(". ") if not nf.is_correct_educator_name(name): answer = "Недопустимые символы." bot.send_message(chat_id=user.tg_id, text=answer, reply_markup=schedule_keyboard()) return try: educators_data = spbu.search_educator(name) except spbu.ApiException: answer = "Во время выполнения запроса произошла ошибка." bot.send_message(chat_id=user.tg_id, text=answer, reply_markup=schedule_keyboard()) return if not educators_data["Educators"]: answer = "Никого не найдено." bot.send_message(chat_id=user.tg_id, text=answer, reply_markup=schedule_keyboard()) elif len(educators_data["Educators"]) > 10: answer = "Слишком много преподавателей.\n" \ "Пожалуйста, <b>уточни</b>." bot.send_message(chat_id=user.tg_id, text=answer, parse_mode="HTML") bot.send_message(chat_id=user.tg_id, text=ask_to_input_educator, reply_markup=ForceReply(), parse_mode="HTML") else: bot.send_message(chat_id=user.tg_id, text="Готово!", reply_markup=schedule_keyboard()) bot.send_message( chat_id=user.tg_id, text="{0} Найденные преподаватели:".format(emoji["mag_right"]), reply_markup=found_educators_keyboard(educators_data, need_cancel=True), parse_mode="HTML")
def schedule_command(msg): person = session.query(Person).filter( Person.telegram_id == msg.chat.id).first() if not person: return tb.send_message(msg.chat.id, "Ви не зареєстровані") args = msg.text.split()[1:] if len(args) == 1: if args[0] == 'change': if person.student: return tb.send_message( msg.chat.id, "В тебе немає доступу до цієї команди! 😡") return tb.send_message(msg.chat.id, "Очікую файл розкладу", reply_markup=ForceReply(selective=False)) elif args[0] == 'show': schedule = None if person.student: schedule = person.student.group.faculty.schedule elif person.head: schedule = person.head.faculty.schedule if not schedule: return tb.send_message(msg.chat.id, "Розкладу поки що немає 😢") return tb.send_message( msg.chat.id, f"Розклад консультацій від *{schedule.created_date.strftime('%Y-%m-%d')}*:\n\n" "\n".join( (f"*Дата*\n" f"{schedule_meeting.meeting.date}\n" f"*Час початку*\n" f"{schedule_meeting.meeting.start_time}\n" f"*Час завершення*\n" f"{schedule_meeting.meeting.end_time}\n" f"*Місце проведення*\n" f"{schedule_meeting.meeting.place}\n" for schedule_meeting in schedule.schedule_meetings)), parse_mode='Markdown') return tb.send_message(msg.chat.id, "Незнайомий аргумент, доступні: <change>, <show>")
def places_command(msg): person = session.query(Person).filter( Person.telegram_id == msg.chat.id).first() if not person: return tb.send_message(msg.chat.id, "Ви не зареєстровані") args = msg.text.split()[1:] if len(args) == 1: if args[0] == 'list': places = session.query(PlaceOfPractice).all() return tb.send_message( msg.chat.id, "Доступні місця практики:\n" f"{os.linesep.join((f'{i + 1}. {place.name}' for (i, place) in enumerate(places)))}", parse_mode='Markdown') elif args[0] == 'take': if person.head: return tb.send_message(msg.chat.id, "Що, керівник, хочеш на практику?)") return tb.send_message(msg.chat.id, "Вкажіть номер практики:", reply_markup=ForceReply(selective=False)) elif args[0] == 'taken': if person.student: return tb.send_message( msg.chat.id, "В тебе немає доступу до цієї команди! 😡") determined_students = session.query(Student).filter( Student.place_of_practice).all() the_rest = session.query(Student).filter( not Student.place_of_practice).all() return tb.send_message( msg.chat.id, f"Вибрали місце практики: {len(determined_students)}\n" f"Не вибрали місце практики:\n" f"{os.linesep.join((f'{i + 1}. {student.person.fullname}' for (i, student) in enumerate(the_rest)))}", parse_mode='Markdown') return tb.send_message( msg.chat.id, "Незнайомий аргумент, доступні: <list>, <take>, <taken>")
def bot_cmd_configuration_vk_add(msg: Message): """ Переводит бота в режим добавления групп ВК, если находится в правильном состоянии. :param Message msg: сообщение """ bot_all_messages(msg) if chat_in_state(msg, chat_state.CONFIGURE_VK_GROUPS): out_msg = "<b>Reply`ем на это сообщение</b> напишите адреса <b>публичных</b> сообществ ВК, " \ "по одному на строку.\n" \ "<i>Желательно без мусорных знаков...</i>" chat_id = msg.chat.id if msg.chat.type == "channel": sent_msg = bot.send_message(chat_id, out_msg, parse_mode="HTML") else: sent_msg = bot.send_message(chat_id, out_msg, reply_markup=ForceReply(), parse_mode="HTML") chat_states[chat_id].state_name = chat_state.CONFIGURE_VK_GROUPS_ADD chat_states[chat_id].message_id_to_reply = sent_msg.message_id
def cb_choose_flavor(call): logger.info(f'[{call.message.chat.id}]|Процесс выбора вкуса табака.') search = Search.objects.get( search_id=call.data.split('|')[1], ) search.extra = get_product_extra(call) search.step = 'flavor' search.save() markup_force_reply = ForceReply(selective=False) text = f'{SEARCH_ID_TEXT.format(id=search.search_id)}' \ f'{search.company} {search.extra}\n\n' \ f'Какой вкус табака найти?\n\n' \ f'_Чтобы найти все вкусы напиши \- _*все*' delete_message(call.message) logger.info(f'[{call.message.chat.id}]|Отправляем сообщение с просьбой написать искомый вкус.') bot.send_message( chat_id=call.message.chat.id, text=text, parse_mode='MarkdownV2', reply_markup=markup_force_reply, )
def standard_keyboard_force_reply(): markup = ForceReply(selective=False) return markup
def send_force_enter_name(message): markup = ForceReply() bot.send_message(message.chat.id, 'Введите свое имя:', reply_markup=markup)
def force_reply(self, function, selective=False): self._reply_function(function) self.reply_markup = ForceReply(selective)
def address_form_handler(message): customer = bot.get_customer(user_id=message.from_user.id) if message.reply_to_message.text == TEXTS['address_add_name']: try: customer.current_address_creation_form = bot.get_default_address() customer.current_address_creation_form.first_name = message.text.title() customer.save() bot.send_message(text=TEXTS['address_add_surname'], chat_id=message.chat.id, reply_markup=ForceReply()) except (ValidationError, ValueError): bot.send_message(text=f"{TEXTS['wrong_format']}", chat_id=message.chat.id) bot.send_message(text=TEXTS['address_add_name'], chat_id=message.chat.id, reply_markup=ForceReply()) elif message.reply_to_message.text == TEXTS['address_add_surname']: try: customer.current_address_creation_form.last_name = message.text.title() customer.save() bot.send_message(text=TEXTS['address_add_phone'], chat_id=message.chat.id, reply_markup=ForceReply()) except (ValidationError, ValueError): bot.send_message(text=f"{TEXTS['wrong_format']}", chat_id=message.chat.id) bot.send_message(text=TEXTS['address_add_surname'], chat_id=message.chat.id, reply_markup=ForceReply()) elif message.reply_to_message.text == TEXTS['address_add_phone']: try: customer.current_address_creation_form.phone_number = message.text customer.save() bot.send_message(text=TEXTS['address_add_city'], chat_id=message.chat.id, reply_markup=ForceReply()) except (ValidationError, ValueError): bot.send_message(text=f"{TEXTS['wrong_format']}. 0123456789", chat_id=message.chat.id) bot.send_message(text=TEXTS['address_add_phone'], chat_id=message.chat.id, reply_markup=ForceReply()) elif message.reply_to_message.text == TEXTS['address_add_city']: try: customer.current_address_creation_form.city = message.text customer.save() bot.send_message(text=TEXTS['address_add_NP_number'], chat_id=message.chat.id, reply_markup=ForceReply()) except (ValidationError, ValueError): bot.send_message(text=f"{TEXTS['wrong_format']}", chat_id=message.chat.id) bot.send_message(text=TEXTS['address_add_city'], chat_id=message.chat.id, reply_markup=ForceReply()) elif message.reply_to_message.text == TEXTS['address_add_NP_number']: try: customer.current_address_creation_form.nova_poshta_branch = int(message.text) customer.add_address(customer.current_address_creation_form) del customer.current_address_creation_form customer.save() row = [InlineKeyboardButton(text=TEXTS['order_proceed'], callback_data='order_proceed')] kb = bot.create_inline_keyboard(row) bot.send_message(text=TEXTS['address_add_success'], chat_id=message.chat.id, reply_markup=kb) except (ValidationError, ValueError): bot.send_message(text=f"{TEXTS['wrong_format']}. 1 - 100000", chat_id=message.chat.id) bot.send_message(text=TEXTS['address_add_NP_number'], chat_id=message.chat.id, reply_markup=ForceReply()) else: bot.send_message(text=TEXTS['not_correct'], chat_id=message.chat.id) kb = bot.get_general_keyboard(customer) bot.send_message(reply_markup=kb, chat_id=message.chat.id, text=f"{message.chat.first_name}, {TEXTS['greeting_message']}", parse_mode='html' )
def address_add_start_form(call): bot.send_message(text=TEXTS['address_disclaimer'], chat_id=call.message.chat.id) bot.send_message(text=TEXTS['address_add_name'], chat_id=call.message.chat.id, reply_markup=ForceReply())