skip to Main Content

So user should enter 3 links one by one to bot

And bot should save each link to a new variable (exmp: link1,link2,link3)

Im tried using message handler with iterating,but for some reason it doesnt work

Any workaround?

link1 = ''
link2 = ''
link3 = ''
counter = 1

@dp.message_handler(Text(contains="https://" or "http://",))
async def url(message: types.Message):
    if link1 == '':
        counter+1
        link1 = message.text
    elif link2 == '':
        counter+1
        link2 = message.text
    elif link3 == '':
        counter+1
        link3 = message.text

2

Answers


  1. Chosen as BEST ANSWER

    Got it,

    Just need to use States in aiogram.

    class reg(StatesGroup):
        link1 = State()
        link2 = State()
        link3 = State()
        end = State()
    And just set a new state every new link
    

  2. There’s another good way of doing this if you just want to get multiple links without some specific order.

    You need only one state to do this.

    class Links(StatesGroup):
        get = State()
    

    Then register handlers which start a conversation

    @dp.message_handler(commands=["links"])
    async def collect_links_start(message: Message, state: FSMContext):
        await message.reply("Send me links.nTo finish, type or click /done")
        await Links.get.set()
        # You can use your own saving logic instead, this is just an example
        await state.update_data(links=[])
    

    …, append links

    # You can set more advanced filter for links, `text_startswith` is just an example
    @dp.message_handler(text_startswith=["http"], state=Links.get)
    async def collect_links(message: Message, state: FSMContext):
        # You can use your own saving logic instead, this is just an example
        data = await state.get_data()
        links = data["links"]
        links.append(message.text)
        await state.update_data(links=links)
    
        await message.reply("Got it!nTo finish, type or click /done")
    
    # This handler is a fallback in case user didn't provide valid link
    @dp.message_handler(state=Links.get)
    async def invalid_link(message: Message):
        await message.reply("This doesn't look like a valid link!nTo finish, type or click /done")
    

    … and end the conversation.

    @dp.message_handler(commands=["done"], state=Links.get)
    async def collect_links_finish(message: Message, state: FSMContext):
        # You can use your own loading logic instead, this is just an example
        data = await state.get_data()
        links = data["links"]
        await state.finish()
        link_list = "n".join(links)
    
        await message.reply(f"Links:n{link_list}")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search