Python telegram.ReplyKeyboardRemove() Examples

The following are 30 code examples of telegram.ReplyKeyboardRemove(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module telegram , or try the search function .
Example #1
Source File: DisAtBot.py    From DisAtBot with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def help(bot, update):
    """
    Help function.
    This displays a set of commands available for the bot.
    """
    user = update.message.from_user
    logger.info("User {} asked for help.".format(user.first_name))
    update.message.reply_text(help_info[LANG],
                              reply_markup=ReplyKeyboardRemove()) 
Example #2
Source File: bot.py    From clist with Apache License 2.0 6 votes vote down vote up
def send_message(self, msg, chat_id=None, reply_markup=None):
        if not isinstance(msg, dict):
            msg = {'text': msg}
        if not msg['text']:
            return
        if len(msg['text']) > self.MAX_LENGTH_MESSAGE:
            msg['text'] = msg['text'][:self.MAX_LENGTH_MESSAGE - 3] + '...'

        msg['chat_id'] = chat_id or self.from_id

        msg['disable_web_page_preview'] = True
        if reply_markup:
            msg['reply_markup'] = reply_markup
        if 'reply_markup' not in msg:
            msg['reply_markup'] = telegram.ReplyKeyboardRemove()
        if reply_markup is False or getattr(self, 'chat_type', None) == 'channel':
            msg.pop('reply_markup', None)

        try:
            ret = self.sendMessage(parse_mode='Markdown', **msg)
        except Exception:
            self.logger.error('Exception send message = %s' % msg)
            ret = self.sendMessage(**msg)
        return ret 
Example #3
Source File: utility.py    From superCodingBot with MIT License 6 votes vote down vote up
def paginate(bot, update, result):
        markup = ReplyKeyboardRemove()
        output = result.output
        time1 = result.time
        memory1 = result.memory
        message1 = result.message
        if time1 is not None:
            time1 = time1[0]
        if memory1 is not None:
            memory1 = memory1[0]
        if output is not None:
            output = output[0]
        else:
            output = ""
        if len(output) <= 2897:
            update.message.reply_text("Output:\n" + str(output) + "\n" + "Time: " + str(time1) + "\nMemory: " + str(
                memory1) + "\nMessage: " + str(message1), reply_markup=markup)
        else:
            with open("out.txt", "w") as text_file:
                text_file.write("Output:\n" + str(output) + "\n" + "Time: " + str(time1) + "\nMemory: " + str(
                    memory1) + "\nMessage: " + str(message1))
            bot.send_document(chat_id=update.message.chat_id, document=open('out.txt', 'rb'), reply_markup=markup)
            os.remove('out.txt')

    # FUNCTION TO CREATE XLSX FILES 
Example #4
Source File: univaq.py    From UnivaqBot with MIT License 6 votes vote down vote up
def inevidenza(bot, update):
    """Defining function that prints 5 news from in evidenza"""

    news_to_string = ""
    for i, item in enumerate(utils.NEWS['univaq'][0:5]):
        news_to_string += (str(i + 1) + ' - <a href="{link}">{title}</a>\n\n').format(**item)

    news_to_string += ('<a href="http://www.univaq.it">'
                       'Vedi le altre notizie</a> e attiva le notifiche con /newson per '
                       'restare sempre aggiornato')

    bot.sendMessage(update.message.chat_id,
                    parse_mode='HTML', disable_web_page_preview=True, text=news_to_string,
                    reply_markup=telegram.ReplyKeyboardRemove())

    return ConversationHandler.END 
Example #5
Source File: telegram.py    From lightnovel-crawler with Apache License 2.0 6 votes vote down vote up
def handle_delete_cache(self, bot, update, user_data):
        app = user_data.get('app')
        user = update.message.from_user
        text = update.message.text
        if text.startswith('No'):
            if os.path.exists(app.output_path):
                shutil.rmtree(app.output_path, ignore_errors=True)
            os.makedirs(app.output_path, exist_ok=True)
            # end if
        # end if

        # Get chapter range
        update.message.reply_text(
            '%d volumes and %d chapters found.' % (
                len(app.crawler.volumes),
                len(app.crawler.chapters)
            ),
            reply_markup=ReplyKeyboardRemove()
        )
        return self.display_range_selection_help(bot, update)
    # end def 
Example #6
Source File: discab.py    From UnivaqBot with MIT License 6 votes vote down vote up
def discab_news(bot, update, section):
    """Defining function that prints 5 news from discab given section"""

    news_to_string = ""
    for i, item in enumerate(utils.NEWS[section]):
        news_to_string += (str(i + 1) + ' - <a href="{link}">{title}</a>\n\n').format(**item)

    news_to_string += ('<a href="http://discab.univaq.it/index.php?id=2004">'
                       'Vedi le altre notizie</a> e attiva le notifiche con /newson per '
                       'restare sempre aggiornato')

    bot.sendMessage(update.message.chat_id,
                    parse_mode='HTML', disable_web_page_preview=True, text=news_to_string,
                    reply_markup=telegram.ReplyKeyboardRemove())

    return ConversationHandler.END 
Example #7
Source File: telegram.py    From lightnovel-crawler with Apache License 2.0 6 votes vote down vote up
def destroy_app(self, bot, update, user_data):
        if user_data.get('job'):
            user_data.pop('job').schedule_removal()
        # end if
        if user_data.get('app'):
            app = user_data.pop('app')
            app.destroy()
            # remove output path
            #shutil.rmtree(app.output_path, ignore_errors=True)
        # end if
        update.message.reply_text(
            'Session closed',
            reply_markup=ReplyKeyboardRemove()
        )
        return ConversationHandler.END
    # end def 
Example #8
Source File: feedback.py    From UnivaqBot with MIT License 6 votes vote down vote up
def send_to_developers(bot, update):
    """Function to send feedback to developers"""

    feedback_user = (('<b>{}</b>\n\n <i>{} {}, {}</i>')
                     .format(update.message.text,
                             update.message.from_user.first_name,
                             update.message.from_user.last_name,
                             update.message.chat_id))

    for admin in os.environ['ADMIN'].split(' '):
        bot.sendMessage(admin, feedback_user, parse_mode='HTML')

    bot.sendMessage(update.message.chat_id, 'Grazie per la collaborazione, '
                                            'il messaggio è stato inviato agli sviluppatori.',
                    reply_markup=telegram.ReplyKeyboardRemove())

    return ConversationHandler.END 
Example #9
Source File: telegram.py    From lightnovel-crawler with Apache License 2.0 5 votes vote down vote up
def handle_crawler_to_search(self, bot, update, user_data):
        app = user_data.get('app')

        link = update.message.text
        if link:
            selected_crawlers = []
            if link.isdigit():
                selected_crawlers += [
                    app.crawler_links[int(link) - 1]
                ]
            else:
                selected_crawlers += [
                    x for i, x in enumerate(app.crawler_links)
                    if '%d - %s' % (i + 1, urlparse(x).hostname) == link
                ]
            # end if
            if len(selected_crawlers) != 0:
                app.crawler_links = selected_crawlers
            # end if
        # end if

        update.message.reply_text(
            'Searching for "%s" in %d sites. Please wait.' % (
                app.user_input, len(app.crawler_links)),
            reply_markup=ReplyKeyboardRemove(),
        )
        update.message.reply_text(
            'DO NOT type anything until I reply.\n'
            'You can only send /cancel to stop this session.'
        )

        app.search_novel()
        return self.show_novel_selection(bot, update, user_data)
    # end def 
Example #10
Source File: conversation_handler.py    From AmbroBot with GNU General Public License v3.0 5 votes vote down vote up
def cancel(bot, update):
    user = update.message.from_user
    logger.info("User %s canceled the conversation.", user.first_name)
    update.message.reply_text('Bye! I hope we can talk again some day.',
                              reply_markup=ReplyKeyboardRemove())

    return ConversationHandler.END 
Example #11
Source File: responses.py    From django-telegram-bot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render(self):
        keyboard = super(KeyboardResponse, self).render()
        if keyboard:
            keyboard = ast.literal_eval(keyboard)
            keyboard = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)
        else:
            keyboard = ReplyKeyboardRemove()
        return keyboard 
Example #12
Source File: testcases.py    From django-telegram-bot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def assertBotResponse(self, mock_send, command):
        args, kwargs = mock_send.call_args
        self.assertEqual(1, mock_send.call_count)
        self.assertEqual(kwargs['chat_id'], self.update.message.chat.id)
        self.assertEqual(kwargs['parse_mode'], command['out']['parse_mode'])
        if not command['out']['reply_markup']:
            self.assertTrue(isinstance(kwargs['reply_markup'], ReplyKeyboardRemove))
        else:
            self.assertInKeyboard(command['out']['reply_markup'], kwargs['reply_markup'].keyboard)
        if not PY3:
            kwargs['text'] = kwargs['text'].decode('utf-8')
        self.assertIn(command['out']['text'], kwargs['text']) 
Example #13
Source File: admin.py    From sticker-finder with MIT License 5 votes vote down vote up
def test_broadcast(bot, update, session, chat, user):
    """Broadcast a message to all users."""
    message = update.message.text.split(" ", 1)[1].strip()

    call_tg_func(
        bot,
        "send_message",
        [chat.id, message],
        {"parse_mode": "Markdown", "reply_markup": ReplyKeyboardRemove()},
    ) 
Example #14
Source File: bot_example.py    From calendar-telegram with MIT License 5 votes vote down vote up
def inline_handler(bot,update):
    selected,date = telegramcalendar.process_calendar_selection(bot, update)
    if selected:
        bot.send_message(chat_id=update.callback_query.from_user.id,
                        text="You selected %s" % (date.strftime("%d/%m/%Y")),
                        reply_markup=ReplyKeyboardRemove()) 
Example #15
Source File: main.py    From Python-BlackJackBot with GNU General Public License v3.0 5 votes vote down vote up
def hide_cmd(bot, update):
    """Hides the keyboard in the specified chat."""
    update.message.reply_text("\U0001F44D", reply_markup=ReplyKeyboardRemove()) 
Example #16
Source File: DisAtBot.py    From DisAtBot with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def set_lang(bot, update):
    """
    First handler with received data to set language globally.
    """
    # Set language:
    global LANG
    LANG = update.message.text
    user = update.message.from_user

    logger.info("Language set by {} to {}.".format(user.first_name, LANG))
    update.message.reply_text(lang_selected[LANG],
                              reply_markup=ReplyKeyboardRemove())

    return MENU 
Example #17
Source File: telegram.py    From lightnovel-crawler with Apache License 2.0 5 votes vote down vote up
def get_novel_info(self, bot, update, user_data):
        app = user_data.get('app')
        user = update.message.from_user

        update.message.reply_text(app.crawler.novel_url)

        # TODO: Implement login feature. Create login_info_dict of (email, password)
        # if app.can_do('login'):
        #     app.login_data = login_info_dict.get(app.crawler.home_url)
        # # end if

        update.message.reply_text('Reading novel info...')
        app.get_novel_info()

        if os.path.exists(app.output_path):
            update.message.reply_text(
                'Local cache found do you want to use it',
                reply_markup=ReplyKeyboardMarkup([
                    ['Yes', 'No']
                ], one_time_keyboard=True),
            )
            return 'handle_delete_cache'
        else:
            os.makedirs(app.output_path, exist_ok=True)
            # Get chapter range
            update.message.reply_text(
                '%d volumes and %d chapters found.' % (
                    len(app.crawler.volumes),
                    len(app.crawler.chapters)
                ),
                reply_markup=ReplyKeyboardRemove()
            )
            return self.display_range_selection_help(bot, update)
        # end if
    # end def 
Example #18
Source File: telegram.py    From lightnovel-crawler with Apache License 2.0 5 votes vote down vote up
def handle_output_format(self, bot, update, job_queue, user_data):
        app = user_data.get('app')
        user = update.message.from_user

        text = update.message.text.strip().lower()
        app.output_formats = {}
        if text in available_formats:
            for x in available_formats:
                if x == text:
                    app.output_formats[x] = True
                else:
                    app.output_formats[x] = False
                # end if
            # end for
        elif text != 'all':
            update.message.reply_text('Sorry, I did not understand.')
            return
        # end if

        job = job_queue.run_once(
            self.process_download_request,
            1,
            context=(update, user_data),
            name=str(user.id),
        )
        user_data['job'] = job

        update.message.reply_text(
            'Your request has been received.'
            'I will generate book in "%s" format' % text,
            reply_markup=ReplyKeyboardRemove()
        )

        return ConversationHandler.END
    # end def 
Example #19
Source File: raiwalletbot.py    From NanoWalletBot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hide_keyboard(bot, chat_id, text):
	reply_markup = ReplyKeyboardRemove()
	try:
		bot.sendMessage(chat_id=chat_id, text=text, reply_markup=reply_markup)
	except:
		sleep(1)
		bot.sendMessage(chat_id=chat_id, text=text, reply_markup=reply_markup) 
Example #20
Source File: worker.py    From greed with GNU Affero General Public License v3.0 5 votes vote down vote up
def __graceful_stop(self, stop_trigger: StopSignal):
        """Handle the graceful stop of the thread."""
        log.debug("Gracefully stopping the conversation")
        # If the session has expired...
        if stop_trigger.reason == "timeout":
            # Notify the user that the session has expired and remove the keyboard
            self.bot.send_message(self.chat.id, self.loc.get('conversation_expired'),
                                  reply_markup=telegram.ReplyKeyboardRemove())
        # If a restart has been requested...
        # Do nothing.
        # Close the database session
        # End the process
        sys.exit(0) 
Example #21
Source File: admin.py    From ultimate-poll-bot with MIT License 5 votes vote down vote up
def test_broadcast(bot, update, session, user):
    """Send the broadcast message to the admin for test purposes."""
    message = update.message.text.split(" ", 1)[1].strip()

    bot.send_message(
        user.id, message, parse_mode="Markdown", reply_markup=ReplyKeyboardRemove(),
    ) 
Example #22
Source File: osmbot.py    From osmbot with GNU General Public License v3.0 5 votes vote down vote up
def set_only_mention(self, message, user_id, chat_id, user):
        """
        Manages the set only mention requests

        :param message: Str with the message (Yes or No)
        :param user_id: User id
        :param chat_id: Chat ud
        :param user: Dict with user configuration
        :return: None
        """
        onlymentions = message == 'Yes'
        if self.get_group():
            user.set_field(chat_id, 'onlymentions', onlymentions, group=self.get_group())
            user.set_field(chat_id, 'mode', 'normal', group=self.get_group())
        else:
            user.set_field(user_id, 'onlymentions', onlymentions, group=self.get_group())
            user.set_field(user_id, 'mode', 'normal', group=self.get_group())
        if not onlymentions:
            text = self._get_template('only_mention.md').render()
            self.telegram_api.sendMessage(
                chat_id,
                text,
                'Markdown',
                reply_markup=ReplyKeyboardRemove())
        else:
            template = self._get_template('answer_always.md')
            text = template.render(is_rtl=self.get_is_rtl())
            self.telegram_api.sendMessage(
                chat_id,
                text,
                'Markdown',
                reply_markup=ReplyKeyboardRemove()) 
Example #23
Source File: osmbot.py    From osmbot with GNU General Public License v3.0 5 votes vote down vote up
def set_language_command(self, message, user_id, chat_id, u):
        """
        Answers the language command

        :param message: Message
        :param user_id: User identifier
        :param chat_id: Chat identifier
        :param u: User object
        :return: None
        """
        if message in self.get_languages():
            if self.get_group():
                u.set_field(chat_id, 'lang', self.get_languages()[message], group=self.get_group())
                u.set_field(chat_id, 'mode', 'normal', group=self.get_group())
            else:
                u.set_field(user_id, 'lang', self.get_languages()[message], group=self.get_group())
                u.set_field(user_id, 'mode', 'normal', group=self.get_group())
            self.load_language(self.get_languages()[message])
            template = self._get_template('new_language.md')
            text = template.render(is_rtl=self.get_is_rtl())
            k = ReplyKeyboardRemove()
            self.telegram_api.sendMessage(
                chat_id,
                text,
                'Markdown',
                reply_markup=k)

        else:
            if self.get_group():
                u.set_field(chat_id, 'mode', 'normal', group=True)
            else:
                u.set_field(user_id, 'mode', 'normal')
            temp = self._get_template('cant_talk_message.md')
            text = temp.render()
            self.telegram_api.sendMessage(chat_id, text, 'Markdown') 
Example #24
Source File: discab.py    From UnivaqBot with MIT License 5 votes vote down vote up
def discaboff(bot, update, section):
    """Defining the command to disable notification for discab"""

    if update.message.chat_id in utils.USERS[section]:
        utils.unsubscribe_user(update.message.chat_id, section)
        bot.sendMessage(update.message.chat_id,
                        text='Notifiche Disattivate!',
                        reply_markup=telegram.ReplyKeyboardRemove())
    else:
        bot.sendMessage(update.message.chat_id,
                        text='Per disattivare le notifiche dovresti prima attivarle.',
                        reply_markup=telegram.ReplyKeyboardRemove())

    return ConversationHandler.END 
Example #25
Source File: app.py    From selfmailbot with MIT License 5 votes vote down vote up
def reset_email(bot, update: Update, user, render):
    user.email = None
    user.is_confirmed = False
    user.save()

    update.message.reply_text(text=render('email_is_reset'), reply_markup=ReplyKeyboardRemove()) 
Example #26
Source File: news_commands.py    From UnivaqBot with MIT License 5 votes vote down vote up
def close(bot, update):
    """Defining Function for remove keyboard"""

    bot.sendMessage(update.message.chat_id,
                    'Ho chiuso le news!',
                    reply_markup=telegram.ReplyKeyboardRemove())

    return ConversationHandler.END 
Example #27
Source File: disim.py    From UnivaqBot with MIT License 5 votes vote down vote up
def disim(bot, update):
    """Defining the command to retrieve 5 news
    Now we store the last 10 news into the database,
    the comparison to send notifications is made between
    the last 5 pulled news from disim site and the news stored into the db.
    This decision was made to avoid repeated news, in fact, if some news(from first to fifth)
    is deleted the sixth(that now has become the fifth) news will be sent again even if it is
    already been sent in the past because it will appear in the pulled news and it
    is no more present into the database at the moment of the comparison.
    """

    news_to_string = ""
    for i, item in enumerate(utils.NEWS['disim'][0:5]):
        suffix = '...' if len(item['description']) > 75 else ''
        news_to_string += (str(i + 1) + ' - <a href="{link}">{title}</a>\n'
                           '\t<i>{description:.75}{}</i>\n\n').format(suffix, **item)

    news_to_string += ('<a href="http://www.disim.univaq.it/main/news.php?entrant=1">'
                       'Vedi le altre notizie</a> e attiva le notifiche con /newson per '
                       'restare sempre aggiornato')

    bot.sendMessage(update.message.chat_id,
                    parse_mode='HTML', disable_web_page_preview=True, text=news_to_string,
                    reply_markup=telegram.ReplyKeyboardRemove())

    return ConversationHandler.END 
Example #28
Source File: disim.py    From UnivaqBot with MIT License 5 votes vote down vote up
def disimon(bot, update):
    """Defining the command to enable notification for disim"""

    if update.message.chat_id not in utils.USERS['disim']:
        utils.subscribe_user(update.message.chat_id, 'disim')
        bot.sendMessage(update.message.chat_id,
                        text='Notifiche Abilitate!',
                        reply_markup=telegram.ReplyKeyboardRemove())
    else:
        bot.sendMessage(update.message.chat_id,
                        text='Le notifiche sono già abilitate!',
                        reply_markup=telegram.ReplyKeyboardRemove())

    return ConversationHandler.END 
Example #29
Source File: disim.py    From UnivaqBot with MIT License 5 votes vote down vote up
def disimoff(bot, update):
    """Defining the command to disable notification for disim"""

    if update.message.chat_id in utils.USERS['disim']:
        utils.unsubscribe_user(update.message.chat_id, 'disim')
        bot.sendMessage(update.message.chat_id,
                        text='Notifiche Disattivate!',
                        reply_markup=telegram.ReplyKeyboardRemove())
    else:
        bot.sendMessage(update.message.chat_id,
                        text='Per disattivare le notifiche dovresti prima attivarle.',
                        reply_markup=telegram.ReplyKeyboardRemove())

    return ConversationHandler.END 
Example #30
Source File: univaq.py    From UnivaqBot with MIT License 5 votes vote down vote up
def univaqon(bot, update):
    """Defining the command to enable notification for univaq"""

    if update.message.chat_id not in utils.USERS['univaq']:
        utils.subscribe_user(update.message.chat_id, 'univaq')
        bot.sendMessage(update.message.chat_id,
                        text='Notifiche Abilitate!',
                        reply_markup=telegram.ReplyKeyboardRemove())
    else:
        bot.sendMessage(update.message.chat_id,
                        text='Le notifiche sono già abilitate!',
                        reply_markup=telegram.ReplyKeyboardRemove())

    return ConversationHandler.END