Example #1
0
    def greeting(self, message):
        if self.ChatsIDs[self.chat_id][1] == 'g':
            custom_keyboard = [["Да", "Нет"]]
            self.Reply_Markup = telegram.ReplyKeyboardMarkup(custom_keyboard)
            self.send_message("Хотите познакомиться?")
            self.Reply_Markup = telegram.ReplyKeyboardHide()
            self.ChatsIDs[self.chat_id][1] = 'g_0'

        elif self.ChatsIDs[self.chat_id][1] == 'g_0':
            self.Reply_Markup = telegram.ReplyKeyboardHide()
            if message == 'Да':
                self.send_message("Как Вас зовут?")
                self.ChatsIDs[self.chat_id][1] = 'g_1'
            elif message == 'Нет':
                self.send_message("Ваше право!")
                self.ChatsIDs[self.chat_id][0] = 'Аноним'
                self.ChatsIDs[self.chat_id][1] = None
            else:
                self.send_message(
                    "Прошу прощения, я Вас не понял.\nХотите познакомиться?")

        elif self.ChatsIDs[self.chat_id][1] == 'g_1':
            self.ChatsIDs[self.chat_id][0] = message
            self.send_message("Очень приятно, " + message +
                              "! А меня можете называть Бот")
            self.ChatsIDs[self.chat_id][1] = None
Example #2
0
def sendText(bot,
             chat_id,
             messageText,
             replyingMessageID=0,
             keyboardLayout=[],
             killkeyboard=True):
    bot.sendChatAction(chat_id=chat_id, action='typing')
    try:
        print("Sending " + messageText + " to " + str(chat_id))
    except Exception as e:
        print(str(e))

    if replyingMessageID != 0:
        bot.sendMessage(chat_id=chat_id,
                        text=messageText,
                        reply_to_message_id=replyingMessageID,
                        reply_markup=telegram.ReplyKeyboardHide(
                            hide_keyboard=killkeyboard))
    elif keyboardLayout != []:
        print("Sending custom keyboard")
        bot.sendMessage(chat_id=chat_id,
                        text=messageText,
                        reply_markup=telegram.ReplyKeyboardMarkup(
                            keyboard=keyboardLayout,
                            one_time_keyboard=True,
                            resize_keyboard=True))
    else:
        bot.sendMessage(chat_id=chat_id,
                        text=messageText,
                        reply_markup=telegram.ReplyKeyboardHide(
                            hide_keyboard=killkeyboard))
Example #3
0
def confirm_order(message, bot):
    product_ids = json.loads(bot.user_get(message.u_id, 'uber:avaliable_products'))
    if message.text not in product_ids:
        bot.call_handler(message, 'uber-choose-product')
        return

    bot.send_message(message.u_id, ORDERING_CAR,
                     reply_markup=telegram.ReplyKeyboardHide())
    request_data = json.loads(bot.user_get(message.u_id, 'uber:request_data'))
    token = bot.user_get(message.u_id, 'uber:access_token')
    request_data['product_id'] = product_ids[message.text]
    print('Uber request data:', request_data)
    response = requests.post(ORDER_URL, headers={
        'Authorization': 'Bearer {}'.format(token),
        'Content-Type': 'application/json',
    }, data=json.dumps(request_data)).json()
    print(response)
    if 'errors' in response:
        bot.send_message(message.u_id, ORDER_ERROR)
        bot.call_handler(message, 'main-menu')
        return

    bot.user_set(message.u_id, 'uber:request_id', response['request_id'])
    bot.redis.sadd('uber:requested_users', message.u_id)
    bot.user_set(message.u_id, 'uber:request_stage', 'processing')

    bot.call_handler(message, 'main-menu')
    bot.send_message(message.u_id, ORDER_CARD.render(data=response),
                     reply_markup=make_order_keyboard(bot, message.u_id, response),
                     parse_mode=telegram.ParseMode.MARKDOWN)
    bot.uber_slack.chat.post_message('#leonard', text='User {} has successfully confirmed his Uber order'.format(message.u_id))
Example #4
0
    def conversation_status(self, update):
        self.Bot.sendChatAction(chat_id=self.chat_id,
                                action=telegram.ChatAction.TYPING)

        # Сброс стадии разговора
        if update.message.text == "\\":
            self.Reply_Markup = telegram.ReplyKeyboardHide()
            self.send_message("Данные о разговоре сброшены")
            self.ChatsIDs[self.chat_id][1] = None

        # Обработка команд
        elif self.ChatsIDs[
                self.chat_id][1] != None or update.message.text[0] == "/":

            # Разговор не ведется
            if self.ChatsIDs[self.chat_id][1] == None:
                for (command, args) in self.parse_message(update.message.text):
                    self.last_update_id = update.update_id
                    Commands.commands[command](self, *args)

            # Разговор ведется
            else:
                Commands.commands[Commands.statuses[self.ChatsIDs[
                    self.chat_id][1][0]]](self, update.message.text)

        # Не команда
        else:
            self.not_a_command(update)
Example #5
0
    def reboot(self, chat_id, message):
        if chat_id in self.ChatsIDs.keys():
            if self.ChatsIDs[chat_id][2] == '0':
                custom_keyboard = [["Отмена"]]
                self.Reply_Markup = telegram.ReplyKeyboardMarkup(custom_keyboard)
                self.sendMessage(chat_id, 'Введите пароль для данной операции ' + telegram.Emoji.CAT_FACE_WITH_WRY_SMILE)
                self.ChatsIDs[chat_id][2] = '_0'

            elif self.ChatsIDs[chat_id][2] == '_0':
                self.Reply_Markup = telegram.ReplyKeyboardHide()
                if message == 'admin':
                    self.sendMessage(chat_id, 'rebooting...')
                    self.AI.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.FIND_LOCATION)
                    self.ChatsIDs = {}
                    chatData = open('chatdata.txt', 'r')
                    self.ChatsIDs.update(pickle.load(chatData))
                    chatData.close()
                    self.ChatsIDs[chat_id][2] = '0'
                elif message == "Отмена":
                    self.sendMessage(chat_id, 'Видимо, мне не нужна перезагрузка ' + telegram.Emoji.AMBULANCE)
                    self.ChatsIDs[chat_id][2] = '0'
                else:
                    self.sendMessage(chat_id, "Неверный пароль!")
        else:
            self.ChatsIDs[chat_id] = ['0', '0', '0']
            self.reboot(chat_id,message)
Example #6
0
    def grouplist(self, message=''):
        if self.ChatsIDs[self.chat_id][1] == None:
            custom_keyboard = [["Текст"], ["PDF"]]
            self.Reply_Markup = telegram.ReplyKeyboardMarkup(custom_keyboard)
            result = 'В каком виде прислать список группы?'
            self.ChatsIDs[self.chat_id][1] = 'l_0'

        elif self.ChatsIDs[self.chat_id][1] == 'l_0':
            self.Reply_Markup = telegram.ReplyKeyboardHide()
            if message == 'Текст':
                result = frz.GroupList
                self.ChatsIDs[self.chat_id][1] = None
            elif message == 'pdf':
                self.Bot.sendChatAction(
                    chat_id=self.chat_id,
                    action=telegram.ChatAction.UPLOAD_DOCUMENT)
                self.Bot.sendDocument(self.chat_id,
                                      document=open('GroupList.pdf',
                                                    'rb').encoding('utf-8'),
                                      reply_markup=self.Reply_Markup)
                self.ChatsIDs[self.chat_id][1] = None
            else:
                result = "Прошу прощения, я Вас не понял.\nВ каком виде прислать список группы?"
        self.send_message(result)
        return result
Example #7
0
 def help(self, telegram_bot, update):
     chat_id = update.message.chat_id
     self.refresh_wait_type(self.get_user(chat_id))
     reply_markup = telegram.ReplyKeyboardHide()
     telegram_bot.sendMessage(chat_id=chat_id,
                              text=self.help_message,
                              reply_markup=reply_markup)
Example #8
0
 def slashCommands(self, message, chat_id):
     if message == '/start':
         self.sendMessage(chat_id, random.choice(frz.HelloFrase) + frz.IntroFrase + telegram.Emoji.SMIRKING_FACE)
         self.greeting(chat_id, message)
     elif message == '/help':
         self.sendMessage(chat_id,frz.HelpMessage + telegram.Emoji.KISSING_FACE)
     elif message == '/grouplist':
         self.sendGroupList(chat_id, message)
     elif message == '/reboot':
         self.reboot(chat_id,message)
     elif message == '/save':
         chatData = open('chatdata.txt', 'w')
         pickle.dump(self.ChatsIDs, chatData)
         chatData.close()
         self.sendMessage(chat_id, 'Данные сохранены')
     elif message == '/clear':
         if chat_id in self.ChatsIDs.keys():
             self.ChatsIDs.__delitem__(chat_id)
             self.Reply_Markup = telegram.ReplyKeyboardHide()
             self.sendMessage(chat_id, 'Ваша история общения удалена')
     elif message == '/spam':
         for chatid in self.ChatsIDs:
             self.sendMessage(chatid, 'Ты тут, ' + self.ChatsIDs[chatid][0] + '?')
     else:
         self.sendMessage(chat_id, 'Данная команда не определена')
		def markup(m):
			if not m:
				return telegram.ReplyKeyboardHide()
			elif m == "SAME":
				return None
			else:
				return telegram.ReplyKeyboardMarkup(m, resize_keyboard=keyboard_short)
Example #10
0
def CheckUser(bot, update, arg=None):
    session = DBSession()
    try:
        chat = update.message.chat
    except AttributeError:
        chat = update.callback_query.message.chat
    entry = session.query(UUser).filter(UUser.id == chat.id).first()
    if not entry:
        # Nutzer ist neu
        new_user = UUser(id=chat.id, first_name=chat.first_name, last_name=chat.last_name, username=chat.username,
                         title=chat.title, notifications=True, semester=default_semester, counter=0)
        session.add(new_user)
        session.commit()
        new_usr = copy.deepcopy(new_user)
        message = "This bot gives you access to selected ANU Wattle courses in Sem 2 2018. For more, check out /about"
        bot.sendMessage(chat_id=chat.id, text=message, reply_markup=telegram.ReplyKeyboardHide())
        session.close()
        return new_usr
    else:
        entry.counter += 1
        if arg is not None:
            entry.current_selection = arg
        ent = copy.deepcopy(entry)
        session.commit()
        session.close()
        return ent
def CheckUser(bot, update, arg=None):
    session = DBSession()
    try:
        chat = update.message.chat
    except AttributeError:
        chat = update.callback_query.message.chat
    entry = session.query(UUser).filter(UUser.id == chat.id).first()
    if not entry:
        # Nutzer ist neu
        new_user = UUser(id=chat.id, first_name=chat.first_name, last_name=chat.last_name, username=chat.username,
                         title=chat.title, notifications=True, semester=default_semester, counter=0)
        session.add(new_user)
        session.commit()
        new_usr = copy.deepcopy(new_user)
        message = "Dieser Bot bietet Zugriff auf alle Moodle-Dateien zum Bachelor Elektro- und Informationstechnik ab " \
                  "WS16/17. "
        bot.sendMessage(chat_id=chat.id, text=message, reply_markup=telegram.ReplyKeyboardHide())
        session.close()
        return new_usr
    else:
        entry.counter += 1
        if arg is not None:
            entry.current_selection = arg
        ent = copy.deepcopy(entry)
        session.commit()
        session.close()
        return ent
Example #12
0
    def greeting(self, chat_id, message):
        if chat_id in self.ChatsIDs.keys():
            if self.ChatsIDs[chat_id][0] == '0':
                custom_keyboard = [[ "Да", "Нет" ]]
                self.Reply_Markup = telegram.ReplyKeyboardMarkup(custom_keyboard)
                self.sendMessage(chat_id, "Хотите познакомиться?")
                self.ChatsIDs[chat_id][0] = '_0'

            elif self.ChatsIDs[chat_id][0] == '_0':
                self.Reply_Markup = telegram.ReplyKeyboardHide()
                if message == 'Да':
                    self.sendMessage(chat_id, "Как Вас зовут?")
                    self.ChatsIDs[chat_id][0] = '_1'
                elif message == 'Нет':
                    self.sendMessage(chat_id, "Ваше право!")
                    self.ChatsIDs[chat_id][0] = 'Аноним'
                else:
                    self.sendMessage(chat_id, "Прошу прощения, я Вас не понял")

            elif self.ChatsIDs[chat_id][0] == '_1':
                self.ChatsIDs[chat_id][0] = message
                self.sendMessage(chat_id, "Очень приятно, " + message + "! А меня можете называть Бот")
        else:
            self.ChatsIDs[chat_id] = ['0', '0', '0']
            self.greeting(chat_id,message)
Example #13
0
 def __init__(self, token = "131812558:AAF5R9TJsowf4-8LRxj8Z38VIZvrLEYPgFo", last_update_id = None):
     self.Token = token
     self.Last_Update_ID = last_update_id
     self.Reply_Markup = telegram.ReplyKeyboardHide()
     self.AI = telegram.Bot(self.Token)
     self.ChatsIDs = {}
     logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Example #14
0
def done(bot, update, user_data):
    valid = query(user_data['Неделя'], user_data['День'], user_data['Корпус'],
                  user_data['Время'])
    response = 'Свободны:' + ',  '.join(valid)
    update.message.reply_text(response,
                              reply_markup=telegram.ReplyKeyboardHide())
    user_data.clear()
    return ConversationHandler.END
Example #15
0
 def unknown(self, telegram_bot, update):
     chat_id = update.message.chat_id
     self.refresh_wait_type(self.get_user(chat_id))
     reply_markup = telegram.ReplyKeyboardHide()
     text = "Sorry, I didn't understand that command." + self.help_message
     telegram_bot.sendMessage(chat_id=chat_id,
                              text=text,
                              reply_markup=reply_markup)
Example #16
0
def message(bot, update):
    telegramuser, created = TelegramUser.get_or_create(
        chat_id=update.message.chat_id)
    state = telegramuser.state

    if state == "main":
        if update.message.text == "Создать визитку":
            telegramuser.state = "question1"
            telegramuser.save()
            bot.sendMessage(update.message.chat_id,
                            reply_markup=telegram.ReplyKeyboardHide(),
                            text="Как Вас зовут?")
            return

        elif update.message.text == "Посмотреть визитку":
            telegramuser.state = "main"
            telegramuser.save()
            bot.sendMessage(update.message.chat_id,
                            text=getcard(update.message.chat_id),
                            parse_mode='HTML')
            return
        else:
            bot.sendMessage(update.message.chat_id, text="Я вас не понял")

    elif state == "question1":
        telegramuser.state = "question2"
        telegramuser.first_name = update.message.text
        telegramuser.save()
        bot.sendMessage(update.message.chat_id, text="Какая Ваша должность?")

    elif state == "question2":
        telegramuser.state = "question3"
        telegramuser.post = update.message.text
        telegramuser.save()
        bot.sendMessage(update.message.chat_id, text="Ваш email?")

    elif state == "question3":
        telegramuser.state = "question4"
        telegramuser.email = update.message.text
        telegramuser.save()
        KEYBOARD = [[telegram.KeyboardButton("Телефон", request_contact=True)]]
        reply_markup = telegram.ReplyKeyboardMarkup(KEYBOARD)
        bot.sendMessage(update.message.chat_id,
                        reply_markup=reply_markup,
                        text="Ваш телефон?")

    elif state == "question4":
        telegramuser.state = "main"
        if update.message.contact:
            telegramuser.phone = update.message.contact.phone_number
        else:
            telegramuser.phone = update.message.text
        telegramuser.save()
        KEYBOARD = [["Создать визитку"], ["Посмотреть визитку"]]
        reply_markup = telegram.ReplyKeyboardMarkup(KEYBOARD)
        bot.sendMessage(update.message.chat_id,
                        reply_markup=reply_markup,
                        text="Визитка сохранена!")
Example #17
0
def send_message(bot, update, text):
    chat_id = update.message.chat_id
    hide_kb = telegram.ReplyKeyboardHide()
    # logger.debug(text)
    if len(text) > 3000: # The theoretical limit is 4096
        for chunk in textwrap.wrap(text, 3000):
            bot.sendMessage(chat_id=chat_id, text=chunk, reply_markup=hide_kb)
    else:
        bot.sendMessage(chat_id=chat_id, text=text, reply_markup=hide_kb)
Example #18
0
 def clear(self):
     if chat_id in self.ChatsIDs.keys():
         self.ChatsIDs.__delitem__(self.chat_id)
         self.Reply_Markup = telegram.ReplyKeyboardHide()
         result = 'Ваша история общения удалена'
     else:
         result = 'Вас и так не было в базе :)'
     self.send_message(result)
     return result
Example #19
0
def execute(cmd, bot, chat_id):
    global LAST_MESSAGE, IS_KEYBOARD_WORKING, sessions

    if cmd.startswith('/start'):
        bot.sendMessage(chat_id=chat_id,
                        text='Welcome to Stack Overflow search bot!')

    elif cmd.startswith('/ok'):
        if chat_id in sessions.keys():
            log_results(sessions[chat_id], True)
            bot.sendMessage(
                chat_id=chat_id,
                parse_mode=telegram.ParseMode.MARKDOWN,
                text="I'm glad to help you!"
            )
        else:
            bot.sendMessage(
                chat_id=chat_id,
                parse_mode=telegram.ParseMode.MARKDOWN,
                text="You don't need much for happiness, do you?"
            )

    elif cmd.startswith('/more'):
        if chat_id in sessions.keys():
            log_results(sessions[chat_id], False)
            if sessions[chat_id]['current_answer'] < (len(sessions[chat_id]['search_results']) - 1):
                sessions[chat_id]['current_answer'] += 1
                bot.sendMessage(
                    chat_id=chat_id,
                    parse_mode=telegram.ParseMode.MARKDOWN,
                    text=prepare_answer_from_search_output(
                        sessions[chat_id]['search_results'],
                        sessions[chat_id]['current_answer']
                    )
                )
            else:
                bot.sendMessage(
                    chat_id=chat_id,
                    text="Sorry, I'm out of good guesses - try different one!"
                )
        else:
            bot.sendMessage(
                chat_id=chat_id,
                text="Hey, ask me something first!"
            )

    elif cmd.startswith('/exit'):
        if IS_KEYBOARD_WORKING:
            bot.sendMessage(chat_id=chat_id, text="Exited successfully!",
                            reply_markup=telegram.ReplyKeyboardHide())
            IS_KEYBOARD_WORKING = False
        else:
            bot.sendMessage(chat_id=chat_id, text="Nothing to exit")

    else:
        bot.sendMessage(chat_id=chat_id, text="Unknown command")
Example #20
0
def oauth_start(message, bot):
    keyboard = telegram.InlineKeyboardMarkup([
        [telegram.InlineKeyboardButton(
            'Connect to Uber 🚘',
            url=short_user_link(message.u_id, AUTH_URL.format(CLIENT_ID))
        )],
        [telegram.InlineKeyboardButton(bot.MENU_BUTTON, callback_data='main-menu-callback')]
    ])
    bot.send_message(message.u_id, OAUTH_START_INVITE_FIRST, reply_markup=telegram.ReplyKeyboardHide())
    bot.send_message(message.u_id, OAUTH_START_INVITE_SECOND, reply_markup=keyboard)
    def message(self, bot, update, **kwargs):
        username = update.message.from_user.username
        print('[+] %s [%s]: %s' %
              (username, update.message.chat_id, update.message.text))

        if getattr(update.message, 'document', None):
            self.document(bot, update)
            return

        if update.message.text == "I'm done":
            reply_markup = telegram.ReplyKeyboardHide()
            return bot.sendMessage(chat_id=update.message.chat_id,
                                   text="Fine",
                                   reply_markup=reply_markup)

        # check if it's a blueprint
        try:
            yaml = j.data.serializer.yaml.loads(update.message.text)

            def generate_unique_name():
                name = '%s.yaml' % j.data.time.getLocalTimeHRForFilesystem()
                path = '%s/%s' % (self._currentBlueprintsPath(username), name)
                while j.sal.fs.exists(path):
                    time.sleep(1)
                    name = '%s.yaml' % j.data.time.getLocalTimeHRForFilesystem(
                    )
                    path = '%s/%s' % (self._currentBlueprintsPath(username),
                                      name)
                return name

            custom = generate_unique_name()

            if not self._currentProject(username):
                message = "You need to create a project before sending me blueprint. See /project"
                return bot.sendMessage(chat_id=update.message.chat_id,
                                       text=message)

            # saving blueprint
            local = '%s/%s' % (self._currentBlueprintsPath(username), custom)
            j.sal.fs.writeFile(local, update.message.text)

            message = "This look like a blueprint, I saved it to: %s. Let me initialize it." % custom
            bot.sendMessage(chat_id=update.message.chat_id, text=message)

            return self._ays_sync(bot, update, ["init"])

        except e:
            print(e)
            print("[-] not a blueprint message")
            pass

        message = "Sorry, I can only match on some commands. Try /help to have more help :)"
        # reply_markup = telegram.ReplyKeyboardHide()
        # bot.sendMessage(chat_id=update.message.chat_id, text=message, reply_markup=reply_markup)
        bot.sendMessage(chat_id=update.message.chat_id, text=message)
Example #22
0
    def echo(self, telegram_bot, update):
        chat_id = update.message.chat_id
        user = self.get_user(chat_id)
        text = update.message.text.strip()

        if user.wait_for() == WaitingTypes.DATE:

            if text not in DAYS:
                reply_markup = self.get_date_keyboard()
                telegram_bot.sendMessage(
                    chat_id=update.message.chat_id,
                    text="Please, choose date for the task",
                    reply_markup=reply_markup)
                return

            delta = timedelta(days=0)
            if text == DAYS[1]:
                delta = timedelta(days=1)
            elif text == DAYS[2]:
                delta = timedelta(days=7)
            date = update.message.date + delta

            if text == DAYS[3]:
                user.add_task(DAYS[3])
            else:
                user.add_task(date)

            reply_markup = telegram.ReplyKeyboardHide()
            if text != DAYS[3]:
                telegram_bot.sendMessage(
                    chat_id=update.message.chat_id,
                    text="Task was successfully added at the"
                    " {:%d, %b %Y}".format(date),
                    reply_markup=reply_markup)
            else:
                telegram_bot.sendMessage(
                    chat_id=update.message.chat_id,
                    text="Task was successfully added at Someday",
                    reply_markup=reply_markup)

            self.save()
        elif user.wait_for() == WaitingTypes.NUMBER:
            telegram_bot.sendMessage(
                chat_id=update.message.chat_id,
                text="Please, enter numbers for done tasks in the"
                "following format:\n'/done done_task_number"
                " another_task_number'")
            return
        else:
            telegram_bot.sendMessage(chat_id=update.message.chat_id,
                                     text="If you want add task with title '" +
                                     text +
                                     "' you should send task in the following "
                                     "format:\n'/add task_title'")
Example #23
0
    def show_task_in_date(tasks, date, chat_id, task_counter, telegram_bot):
        text = "Tasks for " + date
        for task in tasks[date]:
            text += "\n " + str(task_counter) + ") " + task.get_title()
            task_counter += 1

        reply_markup = telegram.ReplyKeyboardHide()
        telegram_bot.sendMessage(chat_id=chat_id,
                                 text=text,
                                 reply_markup=reply_markup)
        return task_counter
Example #24
0
def sendMessage(chat_id, message, reply_markup=None):
    try:
        bot.sendChatAction(chat_id, ChatAction.TYPING)
        if reply_markup is None:
            bot.sendMessage(chat_id,
                            message,
                            reply_markup=telegram.ReplyKeyboardHide())
        else:
            bot.sendMessage(chat_id, message, reply_markup=reply_markup)
    except Exception as e:
        print message
        print str(e)
Example #25
0
    def done(self, telegram_bot, update):
        chat_id = update.message.chat_id
        user = self.get_user(chat_id)
        self.refresh_wait_type(user)
        reply_markup = telegram.ReplyKeyboardHide()

        if update.message.text.strip() == "/done":
            if len(user.get_tasks()) != 0:
                telegram_bot.sendMessage(
                    chat_id=chat_id,
                    text="Please, enter done tasks' numbers separated by space "
                    "in the following format:\n'/done done_task_number"
                    " another_task_number'",
                    reply_markup=reply_markup)

            self.show(telegram_bot, update)
            user.set_wait_type(WaitingTypes.NUMBER)
        else:
            numbers = update.message.text[6:].strip().split()

            try:
                for i in range(len(numbers)):
                    numbers[i] = int(numbers[i])
                numbers = list(set(numbers))
            except ValueError:
                telegram_bot.sendMessage(
                    chat_id=chat_id,
                    text="There are no tasks with such numbers",
                    reply_markup=reply_markup)
                return

            deleted_tasks = []
            for i in range(len(numbers)):
                result = user.delete_task(numbers[i])
                if result != "":
                    deleted_tasks.append(result)
                    for j in range(len(numbers)):
                        if i != j and numbers[j] > numbers[i]:
                            numbers[j] -= 1

            if len(deleted_tasks) != 0:
                text = "Next tasks were deleted:\n"
                for task in deleted_tasks:
                    text += "- " + task + "\n"
            else:
                text = "There are no tasks with such numbers"

            user.set_wait_type(WaitingTypes.NOTHING)
            telegram_bot.sendMessage(chat_id=chat_id,
                                     text=text,
                                     reply_markup=reply_markup)

        self.save()
Example #26
0
 def enviarMensaje(self, update, respuesta):
     chat_id = update.message.chat_id
     nombre_usuario = update.message.from_user.first_name
     alias = update.message.from_user.username
     print "Protobot dice a " + nombre_usuario.encode(
         'utf-8') + " (" + alias.encode('utf-8') + "): " + respuesta
     reply_markup = telegram.ReplyKeyboardHide(hide_keyboard=True)
     self.bot.sendChatAction(chat_id=chat_id,
                             action=telegram.ChatAction.TYPING)
     self.bot.sendMessage(chat_id=chat_id,
                          text=respuesta,
                          reply_markup=reply_markup)
Example #27
0
    def start(self, telegram_bot, update):
        chat_id = update.message.chat_id
        reply_markup = telegram.ReplyKeyboardHide()
        text = "ToDo List Bot for easy and effective task management.\n" + self.help_message
        telegram_bot.sendMessage(chat_id=chat_id,
                                 text=text,
                                 reply_markup=reply_markup)

        if update.message.chat_id not in self.users:
            self.users[chat_id] = User()

        self.refresh_wait_type(self.get_user(chat_id))
        self.save()
Example #28
0
def send_mess(answer, kb):

    if kb == 'SURENO':
        custom_kb = [["Конечно", "В другой раз"]]
        reply = telegram.ReplyKeyboardMarkup(custom_kb)
    elif kb == 'check':
        custom_kb = [["Играть"], ["Попрощаться"]]
        reply = telegram.ReplyKeyboardMarkup(custom_kb)
    elif kb == 'rulescommands':
        custom_kb = [["Правила"], ["Команды"]]
        reply = telegram.ReplyKeyboardMarkup(custom_kb)
    else:
        reply = telegram.ReplyKeyboardHide()
    bot.sendMessage(chat_id=chat_id, text=answer, reply_markup=reply)
Example #29
0
def msg_handler_recipient(bot, update):
    global RECIPIENT
    chat_id = update.message.chat_id
    text = update.message.text
    if text in CONTACTS:
        RECIPIENT = CONTACTS[text]
    else:
        if __valid_phone_number(text):
            RECIPIENT = text
        else:
            RECIPIENT = 'NONUMBER'
    hide_kb = telegram.ReplyKeyboardHide()
    bot.sendMessage(chat_id=chat_id, text='What do I send {}?'.format(RECIPIENT), reply_markup=hide_kb)
    bot_controller.set_message_handler(msg_handler_content)
def sendText(bot, chat_id, messageText, replyingMessageID=0, keyboardLayout=[], killkeyboard=True):
    bot.sendChatAction(chat_id=chat_id, action='typing')
    try:
        print messageText + " at " + str(chat_id)
    except Exception:
        print "Sent something with weird characters to " + str(chat_id)

    if replyingMessageID != 0:
        bot.sendMessage(chat_id=chat_id, text=messageText, reply_to_message_id=replyingMessageID, reply_markup=telegram.ReplyKeyboardHide(hide_keyboard=killkeyboard))
    elif keyboardLayout != []:
        print "Sending keyboard at " + str(chat_id)
        bot.sendMessage(chat_id=chat_id, text=messageText, reply_markup=telegram.ReplyKeyboardMarkup(keyboard=keyboardLayout, one_time_keyboard=True, resize_keyboard=True))
    else:
        bot.sendMessage(chat_id=chat_id, text=messageText, reply_markup=telegram.ReplyKeyboardHide(hide_keyboard=killkeyboard))