Ejemplo n.º 1
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.
    application = Application.builder().token("TOKEN").build()

    # simple start function
    application.add_handler(CommandHandler("start", start_callback))

    # Add command handler to start the payment invoice
    application.add_handler(
        CommandHandler("shipping", start_with_shipping_callback))
    application.add_handler(
        CommandHandler("noshipping", start_without_shipping_callback))

    # Optional handler if your product requires shipping
    application.add_handler(ShippingQueryHandler(shipping_callback))

    # Pre-checkout handler to final check
    application.add_handler(PreCheckoutQueryHandler(precheckout_callback))

    # Success! Notify your user!
    application.add_handler(
        MessageHandler(filters.SUCCESSFUL_PAYMENT,
                       successful_payment_callback))

    # Run the bot until the user presses Ctrl-C
    application.run_polling()
Ejemplo n.º 3
0
def main():
    with open('.token') as f:
        token = f.read().strip()

    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=logging.DEBUG,
        filename='/var/log/pisie/tgsanebot.log',
        filemode='w+')

    application = Application.builder().base_url(
        'http://localhost:8081/bot').token(token).build()

    # COMMON COMMANDS
    application.add_handler(CommandHandler('start', start))
    application.add_handler(CommandHandler('help', help))

    # UPLOAD COMMANDS
    application.add_handler(MessageHandler(filters.Document.ALL, document))
    application.add_handler(CommandHandler('ls', ls))
    application.add_handler(CommandHandler('rm', rm))
    application.add_handler(CommandHandler('mv', mv))

    # ROUTE COMMANDS
    application.add_handler(CommandHandler('routes', routes))
    application.add_handler(CommandHandler('add', add))
    application.add_handler(CommandHandler('remove', remove))

    # ADMIN COMMANDS
    application.add_handler(CommandHandler('rrc', rrc))
    application.add_handler(CommandHandler('pxlpass', pxlpass))

    application.run_polling()
def main() -> None:
    """Run the bot."""
    # Create the Application and pass it your bot's token.
    application = Application.builder().token("TOKEN").build()

    application.add_handler(CommandHandler("start", start))
    application.add_handler(CallbackQueryHandler(button))
    application.add_handler(CommandHandler("help", help_command))

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

    application.add_handler(CommandHandler("start", start))
    application.add_handler(
        MessageHandler(filters.StatusUpdate.WEB_APP_DATA, web_app_data))

    # Run the bot until the user presses Ctrl-C
    application.run_polling()
def main() -> None:
    """Run the bot."""
    context_types = ContextTypes(context=CustomContext, chat_data=ChatData)
    application = Application.builder().token("TOKEN").context_types(context_types).build()

    # run track_users in its own group to not interfere with the user handlers
    application.add_handler(TypeHandler(Update, track_users), group=-1)
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CallbackQueryHandler(count_click))
    application.add_handler(CommandHandler("print_users", print_users))

    application.run_polling()
Ejemplo n.º 7
0
def main() -> None:
    """Run bot."""
    # Create the Application and pass it your bot's token.
    application = Application.builder().token("TOKEN").build()

    # on different commands - answer in Telegram
    application.add_handler(CommandHandler(["start", "help"], start))
    application.add_handler(CommandHandler("set", set_timer))
    application.add_handler(CommandHandler("unset", unset))

    # Run the bot until the user presses Ctrl-C
    application.run_polling()
def main() -> None:
    """Start the bot."""
    # Create the Application and pass it your token and private key
    private_key = Path("private.key")
    application = (Application.builder().token("TOKEN").private_key(
        private_key.read_bytes()).build())

    # On messages that include passport data call msg
    application.add_handler(MessageHandler(filters.PASSPORT_DATA, msg))

    # 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.
    application = Application.builder().token("TOKEN").build()

    # Register the commands...
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("bad_command", bad_command))

    # ...and the error handler
    application.add_error_handler(error_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.
    application = Application.builder().token("TOKEN").build()

    # on different commands - answer in Telegram
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("help", help_command))

    # on non command i.e message - echo the message on Telegram
    application.add_handler(InlineQueryHandler(inline_query))

    # 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()
def main() -> None:
    """Start the bot."""
    # Create the Application and pass it your bot's token.
    application = Application.builder().token("TOKEN").build()

    # Keep track of which chats the bot is in
    application.add_handler(
        ChatMemberHandler(track_chats, ChatMemberHandler.MY_CHAT_MEMBER))
    application.add_handler(CommandHandler("show_chats", show_chats))

    # Handle members joining/leaving chats.
    application.add_handler(
        ChatMemberHandler(greet_chat_members, ChatMemberHandler.CHAT_MEMBER))

    # Run the bot until the user presses Ctrl-C
    # We pass 'allowed_updates' handle *all* updates including `chat_member` updates
    # To reset this, simply pass `allowed_updates=[]`
    application.run_polling(allowed_updates=Update.ALL_TYPES)
def main() -> None:
    """Run the bot."""
    # We use persistence to demonstrate how buttons can still work after the bot was restarted
    persistence = PicklePersistence(filepath="arbitrarycallbackdatabot")
    # Create the Application and pass it your bot's token.
    application = (
        Application.builder()
        .token("TOKEN")
        .persistence(persistence)
        .arbitrary_callback_data(True)
        .build()
    )

    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("help", help_command))
    application.add_handler(CommandHandler("clear", clear))
    application.add_handler(
        CallbackQueryHandler(handle_invalid_button, pattern=InvalidCallbackData)
    )
    application.add_handler(CallbackQueryHandler(list_button))

    # Run the bot until the user presses Ctrl-C
    application.run_polling()
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()
def main() -> None:
    """Run the bot."""
    # Create the Application and pass it your bot's token.
    application = Application.builder().token("TOKEN").build()

    # Set up third level ConversationHandler (collecting features)
    description_conv = ConversationHandler(
        entry_points=[
            CallbackQueryHandler(select_feature,
                                 pattern="^" + str(MALE) + "$|^" +
                                 str(FEMALE) + "$")
        ],
        states={
            SELECTING_FEATURE: [
                CallbackQueryHandler(ask_for_input,
                                     pattern="^(?!" + str(END) + ").*$")
            ],
            TYPING:
            [MessageHandler(filters.TEXT & ~filters.COMMAND, save_input)],
        },
        fallbacks=[
            CallbackQueryHandler(end_describing, pattern="^" + str(END) + "$"),
            CommandHandler("stop", stop_nested),
        ],
        map_to_parent={
            # Return to second level menu
            END: SELECTING_LEVEL,
            # End conversation altogether
            STOPPING: STOPPING,
        },
    )

    # Set up second level ConversationHandler (adding a person)
    add_member_conv = ConversationHandler(
        entry_points=[
            CallbackQueryHandler(select_level,
                                 pattern="^" + str(ADDING_MEMBER) + "$")
        ],
        states={
            SELECTING_LEVEL: [
                CallbackQueryHandler(select_gender,
                                     pattern=f"^{PARENTS}$|^{CHILDREN}$")
            ],
            SELECTING_GENDER: [description_conv],
        },
        fallbacks=[
            CallbackQueryHandler(show_data, pattern="^" + str(SHOWING) + "$"),
            CallbackQueryHandler(end_second_level,
                                 pattern="^" + str(END) + "$"),
            CommandHandler("stop", stop_nested),
        ],
        map_to_parent={
            # After showing data return to top level menu
            SHOWING: SHOWING,
            # Return to top level menu
            END: SELECTING_ACTION,
            # End conversation altogether
            STOPPING: END,
        },
    )

    # Set up top level ConversationHandler (selecting action)
    # Because the states of the third level conversation map to the ones of the second level
    # conversation, we need to make sure the top level conversation can also handle them
    selection_handlers = [
        add_member_conv,
        CallbackQueryHandler(show_data, pattern="^" + str(SHOWING) + "$"),
        CallbackQueryHandler(adding_self,
                             pattern="^" + str(ADDING_SELF) + "$"),
        CallbackQueryHandler(end, pattern="^" + str(END) + "$"),
    ]
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler("start", start)],
        states={
            SHOWING:
            [CallbackQueryHandler(start, pattern="^" + str(END) + "$")],
            SELECTING_ACTION: selection_handlers,
            SELECTING_LEVEL: selection_handlers,
            DESCRIBING_SELF: [description_conv],
            STOPPING: [CommandHandler("start", start)],
        },
        fallbacks=[CommandHandler("stop", stop)],
    )

    application.add_handler(conv_handler)

    # Run the bot until the user presses Ctrl-C
    application.run_polling()
Ejemplo n.º 16
0
def main():

    # print(allcups.task_leaderboard("1058"))

    parser = argparse.ArgumentParser(description='Calcifer telegram bot.')
    parser.add_argument('-c',
                        '--config-file',
                        type=str,
                        required=False,
                        default="etc/config.json",
                        help='Path to config.json file')
    args = parser.parse_args()

    config = configuration.from_json_file(args.config_file)
    os.makedirs(os.path.dirname(config.persistent_file), exist_ok=True)

    logger.info(f"Starting Calcifier bot... ")
    logger.info(f"Persistent file: {config.persistent_file}")

    # Using JSON can broke some sets
    persistent_storage = PicklePersistence(filepath=config.persistent_file)

    # loop = asyncio.new_event_loop()
    # asyncio.set_event_loop(loop)
    # loop.run_until_complete(persistent_storage.update_bot_data({'bot_admins': config.bot_admins}))

    application = Application.builder().token(config.tg_token)\
        .persistence(persistence=persistent_storage).build()
    #
    # logger.info(f"Bot admins: {', '.join(config.bot_admins)}")
    # application.admins = config.bot_admins

    job_queue = application.job_queue

    async def set_bot_admins(c):
        logger.info(f"Setting bot_data...")
        logger.info(f"Bot admins: {', '.join(config.bot_admins)}")
        c.bot_data['bot_admins'] = config.bot_admins

    job_queue.run_once(set_bot_admins, 5)
    job_queue.run_repeating(jobs.games_notifications, interval=3 * 60, first=5)

    application.add_error_handler(handlers.error_handler)
    application.add_handler(handlers.start)
    application.add_handler(handlers.get_info)
    application.add_handler(handlers.set_contest)
    application.add_handler(handlers.set_task)
    application.add_handler(handlers.choose_task)
    application.add_handler(handlers.top)
    application.add_handler(handlers.chat_add)
    application.add_handler(handlers.chat_remove)
    application.add_handler(handlers.chat_top)
    application.add_handler(handlers.pos)
    application.add_handler(handlers.sub)
    application.add_handler(handlers.unsub)
    application.add_handler(handlers.game)
    application.add_handler(handlers.games)
    application.add_handler(handlers.plot)
    application.add_handler(handlers.plotl)
    application.add_handler(handlers.plot_top)
    application.add_handler(handlers.plotl_top)
    application.add_handler(handlers.plot_chat)
    application.add_handler(handlers.plotl_chat)

    application.run_polling()
Ejemplo n.º 17
0
async def main() -> None:
    """Set up the application and a custom webserver."""
    url = "https://domain.tld"
    admin_chat_id = 123456
    port = 8000

    context_types = ContextTypes(context=CustomContext)
    # Here we set updater to None because we want our custom webhook server to handle the updates
    # and hence we don't need an Updater instance
    application = (Application.builder().token("TOKEN").updater(
        None).context_types(context_types).build())
    # save the values in `bot_data` such that we may easily access them in the callbacks
    application.bot_data["url"] = url
    application.bot_data["admin_chat_id"] = admin_chat_id

    # register handlers
    application.add_handler(CommandHandler("start", start))
    application.add_handler(
        TypeHandler(type=WebhookUpdate, callback=webhook_update))

    # Pass webhook settings to telegram
    await application.bot.set_webhook(url=f"{url}/telegram")

    # Set up webserver
    async def telegram(request: Request) -> Response:
        """Handle incoming Telegram updates by putting them into the `update_queue`"""
        await application.update_queue.put(
            Update.de_json(data=await request.json(), bot=application.bot))
        return Response()

    async def custom_updates(request: Request) -> PlainTextResponse:
        """
        Handle incoming webhook updates by also putting them into the `update_queue` if
        the required parameters were passed correctly.
        """
        try:
            user_id = int(request.query_params["user_id"])
            payload = request.query_params["payload"]
        except KeyError:
            return PlainTextResponse(
                status_code=HTTPStatus.BAD_REQUEST,
                content=
                "Please pass both `user_id` and `payload` as query parameters.",
            )
        except ValueError:
            return PlainTextResponse(
                status_code=HTTPStatus.BAD_REQUEST,
                content="The `user_id` must be a string!",
            )

        await application.update_queue.put(
            WebhookUpdate(user_id=user_id, payload=payload))
        return PlainTextResponse(
            "Thank you for the submission! It's being forwarded.")

    async def health(_: Request) -> PlainTextResponse:
        """For the health endpoint, reply with a simple plain text message."""
        return PlainTextResponse(content="The bot is still running fine :)")

    starlette_app = Starlette(routes=[
        Route("/telegram", telegram, methods=["POST"]),
        Route("/healthcheck", health, methods=["GET"]),
        Route("/submitpayload", custom_updates, methods=["POST", "GET"]),
    ])
    webserver = uvicorn.Server(config=uvicorn.Config(
        app=starlette_app,
        port=port,
        use_colors=False,
        host="127.0.0.1",
    ))

    # Run application and webserver together
    async with application:
        await application.start()
        await webserver.serve()
        await application.stop()
Ejemplo n.º 18
0
def keep_typing(last: float, chat: Chat, action: str,
                application: Application) -> float:
    now = time.time()
    if (now - last) > 1:
        application.create_task(chat.send_action(action))
    return now