コード例 #1
0
 def test_collect_additional_context(self, app):
     handler = self.make_default_handler(self.callback_regex2,
                                         filters=filters.Regex("one")
                                         & filters.Regex("two"))
     context = CallbackContext(application=app)
     handler.collect_additional_context(context=context,
                                        update=None,
                                        application=app,
                                        check_result=None)
     assert context.args is None
コード例 #2
0
    async def test_context_multiple_regex(self, app, message):
        handler = MessageHandler(
            filters.Regex("one") & filters.Regex("two"), self.callback_regex2)
        app.add_handler(handler)

        async with app:
            message.text = "not it"
            await app.process_update(Update(0, message))
            assert not self.test_flag

            message.text += " one two now it is"
            await app.process_update(Update(0, message))
            assert self.test_flag
コード例 #3
0
def main() -> None:
    """Run the bot."""
    # Create the Application and pass it your bot's token.
    application = Application.builder().token("TOKEN").build()

    # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler("start", start)],
        states={
            GENDER:
            [MessageHandler(filters.Regex("^(Boy|Girl|Other)$"), gender)],
            PHOTO: [
                MessageHandler(filters.PHOTO, photo),
                CommandHandler("skip", skip_photo)
            ],
            LOCATION: [
                MessageHandler(filters.LOCATION, location),
                CommandHandler("skip", skip_location),
            ],
            BIO: [MessageHandler(filters.TEXT & ~filters.COMMAND, bio)],
        },
        fallbacks=[CommandHandler("cancel", cancel)],
    )

    application.add_handler(conv_handler)

    # Run the bot until the user presses Ctrl-C
    application.run_polling()
def main() -> None:
    """Run the bot."""
    # Create the Application and pass it your bot's token.
    persistence = PicklePersistence(filepath="conversationbot")
    application = Application.builder().token("TOKEN").persistence(
        persistence).build()

    # Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler("start", start)],
        states={
            CHOOSING: [
                MessageHandler(
                    filters.Regex(
                        "^(Age|Favourite colour|Number of siblings)$"),
                    regular_choice),
                MessageHandler(filters.Regex("^Something else...$"),
                               custom_choice),
            ],
            TYPING_CHOICE: [
                MessageHandler(
                    filters.TEXT
                    & ~(filters.COMMAND | filters.Regex("^Done$")),
                    regular_choice)
            ],
            TYPING_REPLY: [
                MessageHandler(
                    filters.TEXT
                    & ~(filters.COMMAND | filters.Regex("^Done$")),
                    received_information,
                )
            ],
        },
        fallbacks=[MessageHandler(filters.Regex("^Done$"), done)],
        name="my_conversation",
        persistent=True,
    )

    application.add_handler(conv_handler)

    show_data_handler = CommandHandler("show_data", show_data)
    application.add_handler(show_data_handler)

    # Run the bot until the user presses Ctrl-C
    application.run_polling()
コード例 #5
0
def main() -> None:
    """Start the bot."""
    # Create the Application and pass it your bot's token.
    application = Application.builder().token("TOKEN").build()

    # More info on what deep linking actually is (read this first if it's unclear to you):
    # https://core.telegram.org/bots#deep-linking

    # Register a deep-linking handler
    application.add_handler(
        CommandHandler("start", deep_linked_level_1,
                       filters.Regex(CHECK_THIS_OUT)))

    # This one works with a textual link instead of an URL
    application.add_handler(
        CommandHandler("start", deep_linked_level_2, filters.Regex(SO_COOL)))

    # We can also pass on the deep-linking payload
    application.add_handler(
        CommandHandler("start", deep_linked_level_3,
                       filters.Regex(USING_ENTITIES)))

    # Possible with inline keyboard buttons as well
    application.add_handler(
        CommandHandler("start", deep_linked_level_4,
                       filters.Regex(USING_KEYBOARD)))

    # register callback handler for inline keyboard button
    application.add_handler(
        CallbackQueryHandler(deep_link_level_3_callback,
                             pattern=KEYBOARD_CALLBACKDATA))

    # Make sure the deep-linking handlers occur *before* the normal /start handler.
    application.add_handler(CommandHandler("start", start))

    # Run the bot until the user presses Ctrl-C
    application.run_polling()
コード例 #6
0
def main() -> None:
    config = configparser.ConfigParser()
    config.read("bot.ini")

    defaults = Defaults(parse_mode=ParseMode.HTML,
                        disable_web_page_preview=True)
    application = (ApplicationBuilder().token(
        config["KEYS"]["bot_api"]).defaults(defaults).post_init(
            post_init).job_queue(RulesJobQueue()).build())

    application.bot_data["search"] = Search(
        github_auth=config["KEYS"]["github_auth"])

    # Note: Order matters!

    # Don't handle messages that were sent in the error channel
    application.add_handler(
        MessageHandler(filters.Chat(chat_id=ERROR_CHANNEL_CHAT_ID),
                       raise_app_handler_stop),
        group=-2,
    )
    # Leave groups that are not maintained by PTB
    application.add_handler(
        MessageHandler(
            filters.ChatType.GROUPS
            & ~filters.StatusUpdate.LEFT_CHAT_MEMBER
            & ~(filters.Chat(username=ALLOWED_USERNAMES)
                | filters.Chat(chat_id=ALLOWED_CHAT_IDS)),
            leave_chat,
        ),
        group=-2,
    )

    application.add_handler(MessageHandler(~filters.COMMAND,
                                           rate_limit_tracker),
                            group=-1)
    application.add_handler(
        MessageHandler(
            filters.SenderChat.CHANNEL
            & ~filters.IS_AUTOMATIC_FORWARD
            & ~filters.Chat(chat_id=ERROR_CHANNEL_CHAT_ID),
            ban_sender_channels,
            block=False,
        ))

    # Simple commands
    # The first one also handles deep linking /start commands
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("rules", rules))

    # Stuff that runs on every message with regex
    application.add_handler(
        MessageHandler(
            filters.Regex(r"(?i)[\s\S]*?((sudo )?make me a sandwich)[\s\S]*?"),
            sandwich))
    application.add_handler(
        MessageHandler(filters.Regex("/(on|off)_topic"), off_on_topic))

    # Tag hints - works with regex
    application.add_handler(MessageHandler(TagHintFilter(), tag_hint))

    # We need several matches so filters.REGEX is basically useless
    # therefore we catch everything and do regex ourselves
    application.add_handler(
        MessageHandler(
            filters.TEXT & filters.UpdateType.MESSAGES & ~filters.COMMAND,
            reply_search))

    # Status updates
    application.add_handler(
        MessageHandler(
            filters.Chat(username=[ONTOPIC_USERNAME, OFFTOPIC_USERNAME])
            & filters.StatusUpdate.NEW_CHAT_MEMBERS,
            delete_new_chat_members_message,
            block=False,
        ),
        group=1,
    )

    # Inline Queries
    application.add_handler(InlineQueryHandler(inlinequeries.inline_query))

    # Captcha for userbots
    application.add_handler(
        CommandHandler(
            "say_potato",
            say_potato_command,
            filters=filters.Chat(
                username=[ONTOPIC_USERNAME, OFFTOPIC_USERNAME]),
        ))
    application.add_handler(
        CallbackQueryHandler(say_potato_button, pattern="^POTATO"))

    # Join requests
    application.add_handler(
        ChatJoinRequestHandler(callback=join_request_callback, block=False))
    application.add_handler(
        CallbackQueryHandler(join_request_buttons, pattern="^JOIN"))

    # Error Handler
    application.add_error_handler(error_handler)

    application.run_polling(allowed_updates=Update.ALL_TYPES, close_loop=False)
    # Can be used in AppBuilder.post_shutdown once #3126 is released
    asyncio.get_event_loop().run_until_complete(post_shutdown(application))
コード例 #7
0
 async def test_context_multiple_regex(self, app, command):
     """Test CHs with context-based callbacks and filters combined"""
     handler = self.make_default_handler(self.callback_regex2,
                                         filters=filters.Regex("one")
                                         & filters.Regex("two"))
     await self._test_context_args_or_regex(app, handler, command)
コード例 #8
0
 async def test_context_regex(self, app, command):
     """Test CHs with context-based callbacks and a single filter"""
     handler = self.make_default_handler(self.callback_regex1,
                                         filters=filters.Regex("one two"))
     await self._test_context_args_or_regex(app, handler, command)
コード例 #9
0
 async def test_context_multiple_regex(self, app, prefix_message_text):
     handler = self.make_default_handler(self.callback_regex2,
                                         filters=filters.Regex("one")
                                         & filters.Regex("two"))
     await self._test_context_args_or_regex(app, handler,
                                            prefix_message_text)