Example #1
0
    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)
Example #2
0
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)
Example #3
0
    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)
Example #4
0
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)
Example #5
0
File: bot.py Project: Alex6430/bot
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, "Я тупой и не понимаю команду")
Example #6
0
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)
Example #7
0
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()
Example #8
0
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
Example #9
0
    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)
Example #10
0
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))
Example #11
0
    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)
Example #12
0
    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)
Example #13
0
    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)
Example #14
0
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,'Я незнаю эту команду')