Exemplo n.º 1
0
def student_name_step(message):
    try:
        chat_id = message.chat.id
        name = message.text
        try:
            check_name = Student.query.filter(
                Student.id == str(chat_id)).first().name
            bot.send_message(chat_id,
                             text='Вы уже зарегистрировались как студент ' +
                             str(check_name))
        except AttributeError:
            student = Student(id=chat_id, name=name)
            db.session.add(student)
            db.session.commit()
            keyboard = types.ReplyKeyboardMarkup(one_time_keyboard=False)
            agree = types.KeyboardButton(
                text='Да, я хочу передать свой телефон', request_contact=True)
            decline = types.KeyboardButton(
                text='Нет, я не хочу передавать свой телефон')
            keyboard.add(agree)
            keyboard.add(decline)
            bot.send_message(chat_id,
                             text='Хотите передать свой номер телефона?',
                             reply_markup=keyboard)
    except Exception as e:
        bot.reply_to(message,
                     'Произошла какая-то ошибка, я вас не понял ' + str(e))
Exemplo n.º 2
0
def message_income_handler(message):
    try:
        if message.chat.type == 'group':
            pass
        else:
            # Смотрим, есть ли юзер в одном из чатов, добавленных в БД
            user_in_chats = []
            for chat in Chat.select():
                user_status = bot.get_chat_member(chat_id=chat.chat_id, user_id=message.from_user.id).status
                if user_status != 'left' and user_status != 'kicked':
                    user_in_chats.append(chat)
            # Если есть, то пытаемся распознать событие
            if len(user_in_chats) != 0:
                event_string = bot_event_handler.parse_event(message.text.encode('utf-8'))
                bot.reply_to(message, "Recognized event:\n" + event_string)
            else:
                bot.send_message(message.chat.id, 'Youre not in one of my group chats')
            
                # Если удалось распознать эвент
                    # То отправляем распознанное событие и спрашиваем, все ли так
                        # Если все ок, то добавляем эвент в календарь и завершаем разговор
                        # Если не ок, то просим ввести заново
                # Если не удалось, то пишем, что не удалось и говорим если что обратиться к /help
                # Если все так, то добавляем эвент
            # Если нет, то отвечаем, что не удалось его найти ни в одной из групп, где есть бот
            pass
        ''''''
        pass
    except Exception as e:
        logger.debug(e.message)
Exemplo n.º 3
0
def send_results(message):
    try:
        chat_id = message.chat.id

    except Exception as e:
        bot.reply_to(message,
                     'Произошла какая-то ошибка, я вас не понял ' + str(e))
Exemplo n.º 4
0
def home(message):
    markup = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True)
    markup.add(types.KeyboardButton('Обмен'), types.KeyboardButton('Оператор'))

    bot.reply_to(message,
                 "Добро пожаловать в обменник Tailcoin!",
                 reply_markup=markup)
Exemplo n.º 5
0
def teacher_table_name_step(message, link, reg):
    try:
        chat_id = message.chat.id
        name = message.text

        if not reg:
            table = Tables(url=link, user_id=chat_id, list_name=name)
            db.session.add(table)
            db.session.commit()

        keyboard = types.InlineKeyboardMarkup()
        add_table = types.InlineKeyboardButton(text="Добавить таблицу",
                                               callback_data="link")
        delete_table = types.InlineKeyboardButton(text="Удалить таблицу",
                                                  callback_data="delete1")
        start_test = types.InlineKeyboardButton(text="Начать тест",
                                                callback_data="start test")
        keyboard.add(add_table)
        keyboard.add(delete_table)
        keyboard.add(start_test)
        bot.send_message(chat_id,
                         text='Принято, вот доступные действия:',
                         reply_markup=keyboard)
    except Exception as e:
        bot.reply_to(message,
                     'Произошла какая-то ошибка, я вас не понял ' + str(e))
Exemplo n.º 6
0
def teacher_test_step(message):
    try:
        chat_id = message.chat.id
        name = message.text

    except Exception as e:
        bot.reply_to(message,
                     "Произошла какая-то ошибка, я вас не понял " + str(e))
Exemplo n.º 7
0
def exchange(message):
	markup = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True)
	markup.add(
		types.KeyboardButton('🔄 Обмен'),
		types.KeyboardButton("🔡 Оператор")
	)

	bot.reply_to(message, "🔄 Обмен\n\nЯ гарантирую безопасность сделки, путем обеспечения поддержки на каждом этапе обмена. \n\nВыбирите валюту, которую хотите обменять",   reply_markup=markup)
Exemplo n.º 8
0
def home(message):
    markup = types.ReplyKeyboardMarkup(row_width=2)
    markup.add(types.KeyboardButton('Создать заявку на обмен'),
               types.KeyboardButton('ююОператорю'))

    bot.reply_to(
        message,
        "Добро пожаловать в обменник Tailcoin!. Чтобы вызвать оператора, введите /operator",
        reply_markup=markup)
Exemplo n.º 9
0
def home(message):
    markup = types.ReplyKeyboardMarkup(row_width=2)
    markup.add(types.KeyboardButton('d'), types.KeyboardButton('d'))
    tb.send_message(chat_id, "Choose one letter:", reply_markup=markup)

    bot.reply_to(
        message,
        "Добро пожаловать в обменник Tailcoin!. Чтобы вызвать оператора, введите /operator"
    )
Exemplo n.º 10
0
def stop(msg):
    with app.app_context():
        u = models.User.query.filter(models.User.telegram_chat_id == str(msg.chat.id)).first()
        if u:
            u.telegram_chat_id = None
            db.session.commit()
            reply = "Ok, I will not send you any notifications."
        else:
            reply = "I have no clue who you are..."
    bot.reply_to(msg, reply)
Exemplo n.º 11
0
    def show_hint(self, message: types.Message, hint: Hint):
        """Вывод подсказки

        Arguments:
            message {types.Message} -- Сообщение с опросом на которое нужно ответить
            hint {Hint} -- Подсказка
        """
        bot.reply_to(message,
                     hint.get(),
                     reply_markup=types.ReplyKeyboardRemove())
Exemplo n.º 12
0
    def send_wrong_answer(self, message: types.Message, text="Неправильно :("):
        """Отправляет уведомление о неправильном ответе

        Arguments:
            message {types.Message} -- [Сообщение на которое нужно ответить]

        Keyword Arguments:
            text {str} -- [Текст ответа] (default: {"Правильно!!"})
        """
        bot.reply_to(message, text, reply_markup=types.ReplyKeyboardRemove())
Exemplo n.º 13
0
def send_welcome(message):
    try:
        bot.reply_to(message, 'Hey there! Try texting anything :)')
        user = User.get_or_create(chat_id=message.chat.id,
                                  id=message.from_user.id,
                                  first_name=message.from_user.first_name,
                                  last_name=message.from_user.last_name,
                                  username=message.from_user.username)
        user = user[0]
    except Exception as e:
        current_app.logger.error(f'Error occured in send_welcome handler: {e}')
Exemplo n.º 14
0
def teacher_table_delete_step2(message, tablename):
    try:
        chat_id = message.chat.id
        text = tablename.replace('delete2', '')
        print(text)
        Tables.query.filter(Tables.list_name == str(text)).delete(
            synchronize_session=False)
        db.session.commit()
        msg = bot.send_message(chat_id, text='Таблица ' + text + ' удалена')
        teacher_table_name_step(msg, None, True)
    except Exception as e:
        bot.reply_to(message,
                     'Произошла какая-то ошибка, я вас не понял ' + str(e))
Exemplo n.º 15
0
def register_expert(message):
    senders = models.Expert.query.filter_by(telegram_id=message.from_user.id)
    if (senders.count() == 0): 
        u = models.Expert(telegram_id=message.from_user.id, 
                 username=message.from_user.username,
                 first_name=message.from_user.first_name,
                 last_name=message.from_user.last_name)
        dbs.add(u)
        dbs.flush()
        dbs.commit()
        bot.reply_to(message, "You are expert now!")
    else:
        bot.reply_to(message, "You are already expert!")
Exemplo n.º 16
0
def home(message):
	markup = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True)
	markup.add(
     	types.KeyboardButton('🔄 Обмен'),
     	types.KeyboardButton("🔡 Оператор")
    )

	bot.reply_to(message, """💸💸💸 Добро пожаловать в обменик криптовалют — TailCoin! 💸💸💸

💰 У нас вы сможете обменять криптовалюту по самым лучшим ценам 💰
⚡️ Быстрый обмен и связь с операторами ⚡️
💳 Принимаем перевод с любых банковских карт 💳
🌓 На связи 24/7 🌓
""",  reply_markup=markup)
Exemplo n.º 17
0
def set_expert_video(message):
    senders = models.Expert.query.filter_by(telegram_id=message.from_user.id)
    sender = senders.first()
    if (sender):
        file_info = bot.get_file(message.video.file_id)
        downloaded_file = bot.download_file(file_info.file_path)
        with open(str(message.from_user.id)+'.mp4', 'wb') as new_file:
            new_file.write(downloaded_file)
#        sender.AboutLink = str(message.from_user.id)+'.mp4'
#        dbs.flush()        
#        dbs.commit()
#        expert = models.Expert.query.filter_by(telegram_id=message.from_user.id).first()
        bot.reply_to(message, "You About video saved: ")
    else:
        bot.reply_to(message, "I don't know what I should do!")
Exemplo n.º 18
0
def teacher_table_link_step(message):
    try:
        chat_id = message.chat.id
        link = message.text
        try:
            link = find_url(link)[0]
            msg = bot.send_message(
                chat_id, text='Введите, как таблица будет называться в боте')
            bot.register_next_step_handler(msg, teacher_table_name_step, link,
                                           False)
        except IndexError:
            bot.reply_to(message, 'Введите правильную ссылку на таблицу')
    except Exception as e:
        bot.reply_to(message,
                     'Произошла какая-то ошибка, я вас не понял ' + str(e))
Exemplo n.º 19
0
def teacher_table_delete_step1(message):
    try:
        chat_id = message.chat.id
        keyboard = types.InlineKeyboardMarkup()
        for i in Tables.query.filter(Tables.user_id == str(chat_id)).all():
            name = i.list_name
            keyboard.add(
                types.InlineKeyboardButton(text=name,
                                           callback_data="delete2" +
                                           str(name)))
        bot.send_message(chat_id,
                         text='Выберите таблицу для удаления',
                         reply_markup=keyboard)
    except Exception as e:
        bot.reply_to(message,
                     'Произошла какая-то ошибка, я вас не понял ' + str(e))
Exemplo n.º 20
0
def student_phone_step(message):
    try:
        chat_id = message.chat.id
        student_phone = message.contact.phone_number
        Student.query.filter(
            Student.id == str(chat_id)).first().phone = student_phone
        db.session.commit()
        keyboard = types.ReplyKeyboardMarkup(one_time_keyboard=False)
        change_name = types.KeyboardButton(text='Поменять имя')
        keyboard.add(change_name)
        bot.send_message(chat_id,
                         text='Завершено успешно',
                         reply_markup=keyboard)
    except Exception as e:
        bot.reply_to(message,
                     'Произошла какая-то ошибка, я вас не понял ' + str(e))
Exemplo n.º 21
0
def vote_for_best_student(message):  # TODO голосовалка
    try:
        chat_id = message.chat.id
        student_on_lesson = app.google_tables.tables.students_on_lesson(
            app.google_tables.tables.ranges,
            app.google_tables.tables.sheet_counter)
        poll = types.Poll(question="Кто является самым активным студентом?")
        for i in student_on_lesson:
            poll.add(student_on_lesson[i])
        for j in student_on_lesson:
            student_chat_id = Student.query.filter(
                Student.name == str(student_on_lesson[j])).first().id
            bot.send_poll(chat_id=student_chat_id, poll=poll)
        msg = bot.send_message(chat_id, text='Голосование начато')
        bot.register_next_step_handler(msg, send_results)
    except Exception as e:
        bot.reply_to(message,
                     'Произошла какая-то ошибка, я вас не понял ' + str(e))
Exemplo n.º 22
0
def send_welcome(message):
	logs.add_log("/start executed")
	if message.text == "/start":
		tg_id = message.from_user.id
		logs.add_log("Check user exist")
		# если пользователя не существует в БД, то создаем нового
		if not User.select().where(User.telegram_id == tg_id):
			logs.add_log("Couldn't find user in the db")
			new_user = User(username=message.from_user.username,
			                telegram_id=tg_id)
			logs.add_log(f"{new_user} created")
			new_user.save()
			logs.add_log("New user saved")
		else:
			logs.add_log("User already exist")
		tkeyboard = tools.generate_keyboard()
		bot.reply_to(message,
					WELCOME_MESSAGE,
					parse_mode="markdown",
					reply_markup=tkeyboard)
Exemplo n.º 23
0
def student_change_name_step(message):
    try:
        chat_id = message.chat.id
        new_name = message.text
        Student.query.filter(
            Student.id == str(chat_id)).first().name = new_name
        db.session.commit()
        keyboard = types.ReplyKeyboardMarkup(one_time_keyboard=False)
        change_name = types.KeyboardButton(text='Поменять имя')
        if not Student.query.filter(Student.id == str(chat_id)).first().phone:
            phone = types.KeyboardButton(text='Передать номер телефона',
                                         request_contact=True)
            keyboard.add(phone)
        keyboard.add(change_name)
        bot.send_message(chat_id,
                         text='Завершено успешно',
                         reply_markup=keyboard)
    except Exception as e:
        bot.reply_to(message,
                     'Произошла какая-то ошибка, я вас не понял ' + str(e))
Exemplo n.º 24
0
def teacher_name_step(message):
    try:
        chat_id = message.chat.id
        name = message.text

        try:
            check_name = Student.query.filter(
                Student.id == str(chat_id)).first().name
            bot.send_message(chat_id,
                             text='Вы уже зарегистрировались как студент ' +
                             str(check_name))
        except AttributeError:
            teacher = Teacher(id=chat_id, name=name)
            db.session.add(teacher)
            db.session.commit()
            msg = bot.send_message(chat_id,
                                   text='Введите ссылку на таблицу Google')
            bot.register_next_step_handler(msg, teacher_table_link_step)
    except Exception as e:
        bot.reply_to(message,
                     "Произошла какая-то ошибка, я вас не понял " + str(e))
Exemplo n.º 25
0
def connect_user(msg):
    token = msg.text.split()[1] if len(msg.text.split()) > 1 else None
    if token:
        with app.app_context():
            u = models.User.load_user_from_unique_code(token)
            if u:
                u.telegram_chat_id = msg.chat.id
                db.session.commit()
                reply = "Congratulations {0}, you successfully connect your account.".format(u.username)
            else:
                reply = "I have no clue who you are..."
    else:
        reply = """
        Hi! I'm UniveCalendar Bot. I can notify you about events of
        your university's calendar. Visit our page for more info.

        Available Commands
        /start <TOKEN> - Authorize bot
        /stop - Disconnect your connect

        """
    bot.reply_to(msg, reply)
Exemplo n.º 26
0
def register_client(message):

    logging.debug('message /start')    
    logging.debug('message from user id: '+str(message.from_user.id))
    logging.debug('message: '+str(message))

    clients = models.Client.query.filter_by(telegram_id=message.from_user.id).all()
    
    logging.debug(str(clients))
    logging.debug(str(clients.count()))  
    
    if (clients.count() == 0):
#    if True:
#        c = models.Client(telegram_id=message.from_user.id, 
#                 username=message.from_user.username,
#                 first_name=message.from_user.first_name,
#                 last_name=message.from_user.last_name)
#        dbs.add(c)
#        dbs.commit()
        bot.reply_to(message, "Welcome!")
    else:
        bot.reply_to(message, "Welcome back!")
    logging.debug('register_client done')
Exemplo n.º 27
0
def send_question(message):
    try:
        row = Question.query.count()
        question = Question.query.filter_by(id=randint(1, row)).first()
        markup = types.ReplyKeyboardMarkup(one_time_keyboard=True,
                                           resize_keyboard=True)
        itembtna = types.KeyboardButton(question.question_answer_varian1)
        itembtnb = types.KeyboardButton(question.question_answer_varian2)
        itembtnc = types.KeyboardButton(question.question_answer_varian3)
        itembtnd = types.KeyboardButton(question.question_answer_varian4)
        itembtne = types.KeyboardButton(question.question_answer_varian5)
        itembtnf = types.KeyboardButton(question.question_answer_varian6)
        markup.row(itembtna, itembtnb, itembtnc)
        markup.row(itembtnd, itembtne, itembtnf)
        msg = bot.send_message(message.chat.id,
                               str(question.question_text),
                               reply_markup=markup,
                               parse_mode='HTML')
        bot.register_next_step_handler(msg,
                                       process_answer_step,
                                       questid=question.id)
    except Exception as e:
        bot.reply_to(message, 'Something wrong!')
Exemplo n.º 28
0
def echo_message(message):
    user = User.query.filter_by(id=message.chat.id).first()
    if user is None:
        user = User(id=message.chat.id,
                    first_name=message.from_user.first_name,
                    last_name=message.from_user.last_name)

        db.session.add(user)
        db.session.commit()
        bot.reply_to(message, 'Вы зарегистрированы!')
    else:
        bot.reply_to(message, f'Всего пользователей {User.query.count()}')
        for user in User.query.all():
            bot.reply_to(message, f'{user.first_name} {user.last_name}')
Exemplo n.º 29
0
def operator(message):
    sql.Customer.insert(chat_id=message.from_user.id,
                        first_name=message.from_user.first_name,
                        want_help='yes',
                        link="~").on_conflict('replace').execute()
    bot.reply_to(message, "Ожидайте! Скоро с вами свяжется наш оператор")
Exemplo n.º 30
0
def send_welcome(message):
    bot.reply_to(message, "Howdy, how are you doing?")
Exemplo n.º 31
0
def home(message):
	bot.reply_to(message, "Добро пожаловать в обменник Tailcoin!. Чтобы вызвать оператора, введите /operator")
Exemplo n.º 32
0
def start(message):
    bot.reply_to(message, 'Hello, ' + message.from_user.first_name)
Exemplo n.º 33
0
def message_handler(message):
	# находим пользователя в БД
	user = User.get(User.telegram_id == message.from_user.id)
	# если у него есть 3 предупреждения, то игнорим
	if user.warns == 3:
		logs.add_log(f"{user} blocked and trying to send a message to the bot")
		return
	# проверяем сообщение на спам
	try:
		# если пользователь отправляем больще 1 запроса в секунду, то выдаем варн
		if time.time() - message_list[
		    message.from_user.id]["last_message"] < 1 and not user.is_admin():
			user.warns += 1
			user.save()
			logs.add_log(f"Add warn to {user}")
			bot.send_message(
			    message.from_user.id,
			    f"Вам выдано предупреждение за спам.\nПредупреждений: {user.warns}"
			)
			if user.warns == 3:
				bot.send_message(
				    message.from_user.id,
				    "Вы были *забанены* за нарушение правил.\nКонтакты: @fdnflm",
				    parse_mode="markdown")
			return
		else:
			# если не спам, то добавляем время отправки в словарь
			message_list[message.from_user.id] = {"last_message": time.time()}
	except KeyError:
		# если в словаре нет времени, то создаем ключ
		message_list[message.from_user.id] = {"last_message": time.time()}
		logs.add_error(f"{user} doesn't have last_message dict")
	if message.text == "📝 Статьи" or message.text == "⬅️ К статьям":
		tkeyboard = tools.generate_keyboard("articles")
		bot.send_message(message.from_user.id,
		                 "Выберите категорию",
		                 reply_markup=tkeyboard)
	elif message.text == "⭐️ Избранное":
		# получаем избранные посты из БД
		posts = Favorite.select().where(Favorite.user_id == user.id)
		completed_message = ""
		# проверка на наличие публикаций
		if len(posts) == 0:
			completed_message = "У вас нет избранных публикаций 🙁"
			bot.send_message(message.from_user.id, completed_message)
		else:
			# генерируем сообщение со всеми публикациями
			completed_message = "*Избранные публикации:*\n\n"
			completed_message += "\n\n".join(
			    f"{i+1}. [{posts[i].title}]({posts[i].liked_url})"
			    for i in range(len(posts)))
			# генерируем inline кнопку для удаления публикации из избранного
			tkeyboard = tools.generate_keyboard("delete_element")
			bot.send_message(message.from_user.id,
			                 completed_message,
			                 parse_mode="markdown",
			                 reply_markup=tkeyboard,
			                 disable_web_page_preview=True)
	# Лучшие публикации за определённый период
	elif message.text == "📈 Лучшие статьи":
		tkeyboard = tools.generate_keyboard("date")
		bot.send_message(message.from_user.id,
		                 "Выберите период",
		                 reply_markup=tkeyboard)
	# отправляем сгенерованное сообщение по дате пользователю
	elif message.text == "🟢 Сутки":
		bot.send_message(message.from_user.id,
		                 tools.generate_posts("day"),
		                 parse_mode="markdown")
	elif message.text == "🔵 Неделя":
		bot.send_message(message.from_user.id,
		                 tools.generate_posts("week"),
		                 parse_mode="markdown")
	elif message.text == "🟣 Месяц":
		bot.send_message(message.from_user.id,
		                 tools.generate_posts("month"),
		                 parse_mode="markdown")
	# последние сообщения
	elif message.text == "Все подряд":
		#tkeyboard = tools.generate_keyboard("pages")
		bot.send_message(message.from_user.id,
		                 tools.generate_posts("all"),
		                 parse_mode="markdown")
	elif message.text == "⬅️ На главную":
		tkeyboard = tools.generate_keyboard()
		bot.reply_to(message,
		             "Главная",
		             parse_mode="markdown",
		             reply_markup=tkeyboard)
	# обработка запроса на чтение публикации
	elif message.text.startswith("/read"):
		# если пользователь превысил лимит запросов в сутки, то уведомляем его
		if (user.status == 0 and user.requests <= 150) or user.status == 1:
			user.requests += 1
			user.save()
			# получаем публикацию из кэша
			link = tools.get_link(message)
			tkeyboard = None
			favorite = Favorite.select().where(
			    Favorite.liked_url == link.split("\n\n")[1])
			if len(favorite) == 0:  # проверка есть ли публикация в избранном
				tkeyboard = tools.generate_keyboard("favorite")
			else:
				tkeyboard = tools.generate_keyboard("unfavorite")
			bot.send_message(message.from_user.id,
			                 link,
			                 reply_markup=tkeyboard,
			                 parse_mode="markdown")
		else:
			bot.send_message(
			    message.from_user.id,
			    "Лимиты на запросы в день превышены. Ждём вас завтра! :)")
Exemplo n.º 34
0
def home(message):
	bot.reply_to(message, "Добро пожаловать в телеграм бота. Чтобы вызвать оператора, введите /operator")
Exemplo n.º 35
0
def function_name(message):
    bot.reply_to(message, "This is a message handler")
Exemplo n.º 36
0
def handle_all(message):
    bot.reply_to(message, "Some message")