def make_mocked_message(text, user_id=123, first_name='Юзер', username='******', message_id=None): if message_id is None: message_id = len(PROCESSED_MESSAGES) message = Message( message_id=message_id, from_user=User(id=user_id, is_bot=False, first_name=first_name, username=username), date=None, chat=Chat(id=user_id, type='private'), content_type=None, options={}, json_string=None ) message.text = text return message
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_material(message: Message): """ Обрабатывает введенное пользователем название материала для загрузки :param message: сообщение пользователя с названием материала """ author_id = message.from_user.id if message.text in COMMANDS: return handle_cancel(message, 'загрузки') if not is_text(message) or not is_title_correct(message): instruction = bot.send_message(author_id, INCORRECT_DATA_MSG) return bot.register_next_step_handler(instruction, check_material) # так как сообщения в поиске выводятся в HTML, # для защиты необходимо экранировать пользовательский ввод message.text = escape(message.text) state = get_state(author_id) state.uploading_material = Resource(title=message.text, author_id=author_id) save_state(author_id, state) instruction = bot.send_message(author_id, UPLOAD_COURSE_MSG) bot.register_next_step_handler(instruction, check_course)
def upper(message: Message): message.text = message.text.lower() val = message.text.find("хочу посмотреть") if message.text == 'ютуб': key = types.InlineKeyboardMarkup() button_choose_youtube = types.InlineKeyboardButton( text="ютуб", callback_data="youtube") key.add(button_choose_youtube) bot.send_message(message.chat.id, "нажми кнопку", reply_markup=key) # bot.reply_to(message, 'https://www.youtube.com/') elif message.text == 'погода': key = types.InlineKeyboardMarkup() button_choose_weather = types.InlineKeyboardButton( text="погода", callback_data="Weather") key.add(button_choose_weather) bot.send_message(message.chat.id, "нажми кнопку", reply_markup=key) # bot.reply_to(message, 'https://yandex.ru/pogoda/moscow') elif message.text == 'кино': url = 'https://w25.zona.plus/movies?page=' key = types.InlineKeyboardMarkup() button_choose_movi_yes = types.InlineKeyboardButton( text="да", callback_data="choose_movi_yes") button_choose_movi_not = types.InlineKeyboardButton( text="нет", callback_data="choose_movi_not") key.add(button_choose_movi_yes, button_choose_movi_not) bot.send_message(message.chat.id, "хотите выбрать жанр?", reply_markup=key) elif message.text == 'хочу посмотреть': bot.reply_to(message, 'https://yandex.ru/pogoda/moscow') else: bot.reply_to(message, "Я тупой и не понимаю команду")
def fix_message(bot_instance, message: Message): bot_instance.is_from_chat = message.from_user.id != message.chat.id if bot_instance.is_from_chat: chat_administrators = bot.get_chat_administrators(message.chat.id) admin_ids = [admin.user.id for admin in chat_administrators] bot_instance.is_from_admin = message.from_user.id in admin_ids else: bot_instance.is_from_admin = False if message.content_type == 'text' and message.text.startswith('/poker'): if bot.is_from_chat and not bot.is_from_admin: bot.reply_to(message, strings['not_admin']) return elif not bot.is_from_chat: # TODO изменить поведение bot.reply_to(message, strings['not_in_chat']) return chat_id = message.chat.id result_chat_id = re.search(regex_chat_id, message.text, re.MULTILINE) if result_chat_id: chat_id = int(regex_chat_id.group(1)) if settings.DEBUG: chat_id = settings.DEBUG_CHAT_ID message.chat_id = chat_id
def add_course(self, message: Message): r1 = compile( r'^[ \n]*(?P<name>[\w\d ]+),[ \n]*(?P<duration>[\d]+),[\n ](?P<semester>[\d]+)[ \n]*$' ) r2 = compile( r'^[ \n]*(?P<name>[\w\d ]+),[ \n]*(?P<duration>[\d]+),[\n ](?P<semester>\d\d\d\d-\d\d-\d\d)[ \n]*$' ) data = r1.search(message.text) new = False if not data: data = r2.search(message.text) new = True if not data: return self.bot.send_message(message.chat.id, 'Не удалось распознать данные') course_info = { 'name': data.group('name'), 'duration': data.group('duration'), 'semester': data.group('semester'), 'new': new } try: self.obj.create_course(course_info).commit() except MyException as error: return self.bot.send_message(message.chat.id, error) except Exception: return self.bot.send_message(message.chat.id, "Не удалось создать курс.") message.text = Bottoms_course.my return self.control(message)
def download_data(self, message: Message): if message.document: file = self.bot.get_file(message.document.file_id) self.download_state['file'] = self.bot.download_file( file.file_path) elif message.text: r = compile(r'^[ \n]*(?P<id>[\d]+)[ \n]*$') data = r.search(message.text) if data: self.download_state['course'] = data.group('id') elif message.text.lower() == 'stop': message.text = '/start' return self.bot.send_message(message.chat.id, **registration(message)) if len(self.download_state) == 2: try: text = Attachment(message.from_user.id).write_state( self.download_state['file'], self.download_state['course']) except Exception as error: print(error) text = 'При загрузки данных произошла ошибка' if not text: text = 'Готово' return self.bot.send_message(message.chat.id, text) else: return self.bot.register_next_step_handler(message, self.download_data)
def default_query(inline_query: types.InlineQuery): Message = str(inline_query.query) def DisplayArgs(args): Return = [] for value, arg in enumerate(args): Return.append( InlineQueryResultArticle( id=value, title=arg, input_message_content=InputTextMessageContent(arg))) return Return #Ничего не написано if Message == "": Bot.answer_inline_query( inline_query.id, [command.ResultArticle for command in COMMAND_LIST]) #Начал писать что то либо else: Commands = Message.lower().split(" ") SeemIt = [ command for command in COMMAND_LIST if command.name.lower().startswith(Commands[0]) ] #Проверяет закончилась ли название команды if len(SeemIt) == 1 and SeemIt[0].name == Commands[0]: command = SeemIt[0] for LEN in range(0, len(Commands) - 1, 1): # Первый параметр try: ArgSeemLike = [ arg for arg in command.args[LEN] if arg.lower().startswith(Commands[LEN + 1]) ] Bot.answer_inline_query(inline_query.id, DisplayArgs(ArgSeemLike)) except: Bot.answer_inline_query(inline_query.id, [ InlineQueryResultArticle( id=0, title="Команда завершена", input_message_content=InputTextMessageContent( "Отправить команду типа")) ]) #Нет не закончилось так что продолжает показывать правильное написание команды else: Bot.answer_inline_query(inline_query.id, [ InlineQueryResultArticle( id=0, title=command.name, input_message_content=InputTextMessageContent( command.output), description=command.description) for command in SeemIt ])
def input_command_start(message: Message) -> None: text = message.text.split(' ', maxsplit=1) if len(text) < 2: bot.send_message(chat_id=message.chat.id, text='Need "/search %address%"') return message.text = text[1] controller.get_geo_step(bot=bot, message=message)
def reply_on_mention(message: Message): global Clock global Stop global Count global UwUMode global ImagePng global Vocal if random.randint(1, 100)<15: Vocal=True Count=50 Stop=True Clock=False user_obj: TGUserModel = get_user_from_message(message) group: GroupSettings = get_group_from_message(message) if message.chat.type != 'private' else None if(group and group.override_settings): # Use group's settings settings: TGUserModel = group.user else: group = None settings = user_obj generated_message = generate_markov(fetch_messages(settings, group)) if (generated_message and not check_duplicated(generated_message, user_obj, group)): if UwUMode==True: generated_message=generated_message.replace("l", 'w') generated_message=generated_message.replace("r", 'w') width, height = lcd.dimensions() spritemap = Image.open("/boot/TriggerBot-master/Peka.png").convert("PA") image = Image.new('1', (width, height),"black") image.paste(spritemap,(width-32,33)) draw = ImageDraw.Draw(image) w, h = lcd.dimensions() font = ImageFont.truetype("/boot/TriggerBot-master/CCFONT.ttf", 12) lines = textwrap.wrap(generated_message, width=16) y_text = 0 for line in lines: width, height = font.getsize(line) draw.text(((w- width)/4, y_text), line,1, font=font) y_text += height for x in range(128): for y in range(64): pixel = image.getpixel((x, y)) lcd.set_pixel(x, y, pixel) backlight.set_all(random.randint(0,255),random.randint(0,255),random.randint(0,255)) backlight.show() lcd.show() ImagePng=image if Vocal==False: bot.reply_to(message, generated_message) else: message.text=generated_message audio(message) Stop=False else: Stop=False LedOnOff()
def del_course(self, message: Message): r = compile(r'^[ \n]*(?P<id>[\d]+)[ \n]*$') data = r.search(message.text) if not data: return self.bot.send_message( message.chat.id, 'Не удалось распознать идентифиактор курса') try: self.obj.del_course(data.group('id')) except MyException as error: return self.bot.send_message(message.chat.id, error) except Exception: return self.bot.send_message(message.chat.id, "Не удалось удалить курс") message.text = Bottoms_course.my return self.control(message)
def start(msg: types.Message): u_lang = msg.from_user.language_code if msg.from_user.language_code in const.languages else const.default_lang user, created = User.get_or_create(id=msg.from_user.id, defaults={ 'username': msg.from_user.username, 'first_name': msg.from_user.first_name, 'last_name': msg.from_user.last_name, 'language_code': u_lang }) params = msg.text.split(' ') if len(params) > 1 and params[1] == 'createlist': create_list(msg) elif len(params) > 1 and params[1].startswith("sub"): list_ = List.get_by_id(int(params[1][3:])) msg.text = f"📝 {list_.name}" new_list, created = List.get_or_create( name=list_.name, owner=user.id, defaults={"subscribed_by": list_}) if created: bot.send_message(msg.from_user.id, _("You subscribed to _{}_ list").format( list_.name), parse_mode='markdown', reply_markup=mps.main_mp(user.id)) text = f"🔗 📝 *{new_list.name}*" else: delete_message(msg.chat.id, list_.last_message_id) bot.send_message(msg.chat.id, _("You already have list with same name"), reply_markup=mps.main_mp(user.id)) text = f"📝 *{new_list.name}*" sent = bot.send_message(msg.chat.id, text, reply_markup=mps.list_mp(new_list.id), parse_mode='markdown') new_list.last_message_id = sent.message_id new_list.save() else: bot.send_message(msg.from_user.id, _("Hello. Create your first list."), reply_markup=mps.main_mp(user.id))
def control(self, message: Message): text = message.text.lower() self.obj = Teacher(message.from_user.id) answer = {} if Bottoms_course.list.lower() == text: answer['text'] = 'Список курсов:\n\n' + format_data( '{0}, {1} ({2}).\nНачало {3}\n', *self.obj.all_course().all()) elif Bottoms_course.my.lower() == text: answer['text'] = "Список курсов у которых вы являетесь автором:\n" answer['text'] += format_data( '{0}) {1}, {2} ({3})\n{4}\n', *self.obj.my_course().all()) or 'Пока список пуст.' elif Bottoms_course.add_course.lower() == text: answer['text'] = NEW_COURSE.format( semesters=format_data('{0} - {1}', *self.obj.get_semesters().all())) self.bot.register_next_step_handler(message, self.add_course) elif Bottoms_course.del_course.lower() == text: answer['text'] = "Список ваших курсов:\n" my_course = format_data('{0}) {1}, {2} ({3})\n', *self.obj.my_course().all()) if not my_course: answer['text'] += 'Пока список пуст.' else: answer[ 'text'] += my_course + '\nВведите номер курса для удаления.' self.bot.register_next_step_handler(message, self.del_course) elif Bottoms_course.group_sing_up.lower() == text: answer[ 'text'] = "Введите номер курса и название группы. Например:\n1 зивтм-1-19" self.bot.register_next_step_handler(message, self.sing_up) elif Bottoms_course.back.lower() == text: message.text = '/start' answer = registration(message) if not answer: return LessonViewer(self.bot).control(message) return self.bot.send_message(message.chat.id, **answer)
def control(self, message: Message): text = message.text.lower() obj = Student(message.from_user.id) answer = None if Bottoms_stud.list.lower() == text: answer = f'Список курсов:\n\n' + format_data( '{0}) {1} ({2}).\nНачало {3}\n', *obj.all_course().all()) elif Bottoms_stud.my.lower() == text: answer = f"Что бы просмотреть оценки или посещаемость по курсу введите:\nОценки [номер курса]\n" answer += f"Посещаемость [номер курса]\n\nСписок курсов на которые подписаннва ваша группа:\n" answer += format_data( '{0}) {1} ({2})\n', *obj.course_student().all()) or "Пока список пуст!" elif text == SECRET_COMMAND: obj.del_people().commit() message.text = '/start' self.bot.send_message(message.chat.id, **base_command(message)) text_command = [] if ' ' in text: text_command = text.split(' ') if len(text_command) < 2 or not text_command[1].isdigit(): answer[ 'text'] = 'Вы ввели некоректные данные после пробела. Или в вашем сообщении нехватает инфомерации.' elif Bottoms_stud.point.lower() == text[0]: data = obj.get_point_visible(int(text[1]), True).all() answer = f"Ваша успеваемость\n" + format_data('{0} - {1}', *data) elif Bottoms_stud.visits.lower() == text[0]: data = obj.get_point_visible(int(text[1]), False).all() answer = f"Ваша {Bottoms_stud.visits.lower()}" + format_data( '{0} - {1}', *data) if not answer: answer = "Попробуйте снова!!!" return self.bot.send_message(message.chat.id, answer)
def control(self, message: Message): text = message.text.lower() obj = Teacher(message.from_user.id) answer = {} if Bottoms_teacher.course.lower() == text: answer['text'] = 'Курсы' answer['reply_markup'] = ReplyKeyboardMarkup(row_width=2) answer['reply_markup'].add(*map(KeyboardButton, Bottoms_course)) elif Bottoms_teacher.lessons.lower() == text: answer['text'] = 'Занятия' answer['reply_markup'] = ReplyKeyboardMarkup(row_width=2) answer['reply_markup'].add(*map(KeyboardButton, Bottoms_lesson)) elif Bottoms_teacher.settings.lower() == text: pass elif text == SECRET_COMMAND: obj.del_people().commit() message.text = '/start' return base_command(message) if not answer: return Course(self.bot).control(message) return self.bot.send_message(message.chat.id, **answer)
class TestUserRegistration(unittest.TestCase): @parameterized.expand([(Message(from_user=User(first_name="Oleg", id=3847590291, is_bot=False, username="******"), message_id=2211, date=datetime.datetime.now(), chat=Chat(id=381278125782, type="private", username="******"), content_type="text", options=[], json_string=""), 12)]) def test_registration(self, message, value): message.text = "/configure_schedule" get_user = Mock(return_value=["Hi"]) with patch('modules.schedule.controller.get_user', new=get_user): with patch('modules.schedule.controller.set_user_configured'): with patch('modules.core.source.bot.send_message', side_effect=send_message): with patch( 'modules.core.source.bot.register_next_step_handler' ): schedule_command_handler(message) assert_equal(messages.pop(), permanent.REQUEST_COURSE) messages.clear() @parameterized.expand([(Message(from_user=User(first_name="Oleg", id=3847590291, is_bot=False, username="******"), message_id=2211, date=datetime.datetime.now(), chat=Chat(id=381278125782, type="private", username="******"), content_type="text", options=[], json_string=""), 12)]) def test_course_set(self, message, value): message.text = "B19" with patch('modules.schedule.controller.append_user_group'): with patch('modules.core.source.bot.send_message', side_effect=send_message): with patch( 'modules.core.source.bot.register_next_step_handler'): process_course_step(message) assert_equal(messages.pop(), permanent.REQUEST_GROUP) @parameterized.expand([(Message(from_user=User(first_name="Oleg", id=3847590291, is_bot=False, username="******"), message_id=2211, date=datetime.datetime.now(), chat=Chat(id=381278125782, type="private", username="******"), content_type="text", options=[], json_string=""), 12)]) def test_group_set(self, message, value): message.text = "B16-SE-01" with patch('modules.schedule.controller.append_user_group'): with patch('modules.core.source.bot.send_message', side_effect=send_message): with patch( 'modules.core.source.bot.register_next_step_handler'): with patch( 'modules.schedule.controller.set_user_configured'): process_group_step(message) assert_equal(messages.pop(), permanent.MESSAGE_SETTINGS_SAVED) @parameterized.expand([(Message(from_user=User(first_name="Oleg", id=3847590291, is_bot=False, username="******"), message_id=2211, date=datetime.datetime.now(), chat=Chat(id=381278125782, type="private", username="******"), content_type="text", options=[], json_string=""), 12)]) def test_wrong_course_set(self, message, value): message.text = "Cake is a lie" with patch('modules.schedule.controller.append_user_group'): with patch('modules.core.source.bot.send_message', side_effect=send_message): with patch( 'modules.core.source.bot.register_next_step_handler'): process_course_step(message) assert_equal(messages.pop(), permanent.MESSAGE_ERROR)
def fake_message(fake_message_dict): """Return a fake, minimalist Telegram message.""" return Message.de_json(fake_message_dict)
'chat': {'id': -383813333, 'title': 'Мой техдолг', 'type': 'group', 'all_members_are_administrators': True}, 'date': 1580657779, 'text': '/bless_me@every_day_bible_bot', 'entities': [{'offset': 0, 'length': 29, 'type': 'bot_command'}]} test_user = User(id=362857450, is_bot= False, first_name='Nikolas', username='******', last_name='Luchanos', language_code='ru') test_chat = Chat(type='group', id=-383813333, title='Мой техдолг', all_members_are_administrators=True) test_msg = Message(message_id=test_message_id, from_user=test_user, date=test_date, chat=test_chat, content_type=test_content_type, options=[], json_string=test_json)
def echo_digits(message: Message): message.text = message.text.lower() if 'скинь дз' in message.text: if check(message.text.split()[2].strip()): if dz[message.text.split()[2].strip()] == 'фото': directory = '../' all_files_in_directory = os.listdir(directory) for name in all_files_in_directory: if name == message.text.split()[2].strip()+".jpg": print('Скидываю фото',message.text.split()[2].strip()+".jpg") img = open(directory+'/'+name,'rb') bot.send_chat_action(message.from_user.id,'upload_photo') bot.send_photo(message.from_user.id,img,message.text.split()[2].strip()) img.close() else: bot.send_message(message.chat.id,dz[message.text.split()[2].strip()]) elif 'расписание' in message.text: if 'на' in message.text: if checkR(message.text.split()[2].strip()): y = checkF(message.text.split()[2].strip()) f = date.get(y) bot.send_message(message.chat.id,"Расписание на {0}:\n {1}\n {2}\n {3}\n {4}\n {5}\n {6}\n {7}\n {8}\n".format(f[0],f[1],f[2],f[3],f[4],f[5],f[6],f[7],f[8])) if 'на завтра' in message.text: x = datetime.datetime.now() y = x.strftime("%w") y = m[int(y)] c = date.get(y) bot.send_message(message.chat.id,"Расписание на {0}:\n {1}\n {2}\n {3}\n {4}\n {5}\n {6}\n {7}\n {8}\n".format(c[0],c[1],c[2],c[3],c[4],c[5],c[6],c[7],c[8])) elif 'скинь все дз' in message.text: if check(message.text.split()[2].strip()): for k, v in dz.items(): print(v) if v == 'фото': directory = '../' all_files_in_directory = os.listdir(directory) for name in all_files_in_directory: if name == k+".jpg": print('Скидываю фото',k+".jpg") img = open(directory+'/'+name,'rb') bot.send_chat_action(message.from_user.id,'upload_photo') bot.send_photo(message.from_user.id,img,k) img.close() else: bot.send_message(message.chat.id,k+' '+v) elif 'добавь дз' in message.text: if check(message.text.split()[2].strip()): l = len(message.text.split()[2].strip()) dz[message.text.split()[2].strip()] = message.text[11+l:] bot.send_message(message.chat.id,'Дз добавлено') elif 'удалить дз' in message.text: if check(message.text.split()[2].strip()): dz[message.text.split()[2].strip()] = 'ничего' os.remove(message.text.split()[2].strip()+".jpg") bot.send_message(message.chat.id,'Дз удалено') else: bot.send_message(message.chat.id,'Я незнаю эту команду')
class TestCourseAttachment(unittest.TestCase): @parameterized.expand([(Message(from_user=User(first_name="Oleg", id=3847590291, is_bot=False, username="******"), message_id=2211, date=datetime.datetime.now(), chat=Chat(id=381278125782, type="private", username="******"), content_type="text", options=[], json_string=""), 12)]) def test_add_course(self, message, value): message.text = "/add_course" with patch('modules.core.source.bot.register_next_step_handler'): with patch('modules.core.source.bot.send_message', side_effect=send_message): with patch( 'modules.electives_schedule.controller.get_electives_course' ): add_course_handler(message) assert_equal(messages.pop(), str("What course you want to add?")) @parameterized.expand([(Message(from_user=User(first_name="Oleg", id=3847590291, is_bot=False, username="******"), message_id=2211, date=datetime.datetime.now(), chat=Chat(id=381278125782, type="private", username="******"), content_type="text", options=[], json_string=""), 12)]) def test_wrong_add_course(self, message, value): message.text = "/some_staff" with patch('modules.core.source.bot.register_next_step_handler'): with patch('modules.core.source.bot.send_message', side_effect=send_message): with patch( 'modules.electives_schedule.controller.get_electives_course' ): add_course_handler(message) assert_equal(len(messages), 0) @parameterized.expand([(Message(from_user=User(first_name="Oleg", id=3847590291, is_bot=False, username="******"), message_id=2211, date=datetime.datetime.now(), chat=Chat(id=381278125782, type="private", username="******"), content_type="text", options=[], json_string=""), 12)]) def test_course_set(self, message, value): message.text = "B19" with patch( 'modules.electives_schedule.controller.check_electives_course', return_value=True): with patch('modules.core.source.bot.send_message', side_effect=send_message): with patch( 'modules.electives_schedule.controller.set_electives_user' ): process_electives(message) assert_equal(messages.pop(), permanent.MESSAGE_SUCCESS) @parameterized.expand([(Message(from_user=User(first_name="Oleg", id=3847590291, is_bot=False, username="******"), message_id=2211, date=datetime.datetime.now(), chat=Chat(id=381278125782, type="private", username="******"), content_type="text", options=[], json_string=""), 12)]) def test_wrong_course_set(self, message, value): message.text = "BBBSBS" with patch( 'modules.electives_schedule.controller.check_electives_course', return_value=False): with patch('modules.core.source.bot.send_message', side_effect=send_message): with patch( 'modules.electives_schedule.controller.set_electives_user' ): process_electives(message) assert_equal(messages.pop(), permanent.MESSAGE_UNKNOWN_LESSON)
def setUpClass(cls) -> None: jsonstring = r'{"message_id":1,"from":{"id":108929734,"first_name":"Frank","last_name":"Wang","username":"******","is_bot":true},"chat":{"id":1734,"first_name":"F","type":"private","last_name":"Wa","username":"******"},"date":1435296025,"text":"/start"}' cls.message = Message.de_json(jsonstring)
def new_user(message: Message): try: create_user(message) except MyException as error: message.return_text = error return registration_user(message)
def get_message(self) -> Message or None: if self.chat_type == 'callback_query': return None return Message.de_json(self.message)
def _request_lang(language): return text_xo.request_admin_support( Message(0, User(first_name='', id=0, is_bot=True), 0, 0, 'text', dict(text=f'AUTO_REQUEST: {language=}'), ''))