D
D
Denis Petrenko2021-05-16 13:32:02
Python
Denis Petrenko, 2021-05-16 13:32:02

How to recognize din. bot commands?

There is a bot. And it accepts commands of the form "/command1" which are already registered. But what if I need to recognize commands like:
"/search_XXX", where xxx is a dynamic number not written in advance, in order to send a query to the database. Prescribing all the known ones is not an option, because there are too many of them ..
I use aiogram.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
soremix, 2021-05-16
@Termoslik

Just make a decorator using regex
@dp.message_handler(regexp=r'^/search_\w+$')
Next, import the re library and get the desired part of the text

@dp.message_handler(regexp=r'^/search_\w+$')
async def text(message: types.Message):
    query = re.search(r'^/search_(\w+)$', message.text).group(1)

O
o5a, 2021-05-16
@o5a

If xxx is just a search parameter, then it can be passed through a space. Then the command will be universal, and the argument can be pulled out of the string.

@bot.message_handler(commands=['search'])
def search(message):
  if ' ' in message.text:
    param = message.text.split(maxsplit=1)[1]
    ...
  else:
    bot.send_message(message.chat.id, 'no params')

Will understand commands like
/search XXX

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question