Skip to content

Instantly share code, notes, and snippets.

@tshipenchko
Last active February 19, 2021 06:13
Show Gist options
  • Save tshipenchko/42b81fb53bd52ca7034eb6f2b1b99799 to your computer and use it in GitHub Desktop.
Save tshipenchko/42b81fb53bd52ca7034eb6f2b1b99799 to your computer and use it in GitHub Desktop.
Telegram bots commands regex handler (python)
##Regex
`regex_patern = r'^\/(command)+(\@username_of_bot\w*(_\w+)*)?([ \f\n\r\t\v\u00A0\u2028\u2029].*)?$'`
Commands like that will handle
/command
/command arg1 arg2 ...
/command@username_of_bot
/command@username_of_bot arg1 arg2 ...
but
/command@other_bot
/command@other_bot arg1 arg2 ...
won't handle
###Function with regex
```
def commands(*args, bot_username='username_of_bot'):
"""Returns regex based commands' parser for telegram"""
return '|'.join([i for i in [
rf'^\/({i})+(\@{bot_username}\w*(_\w+)*)?([ \f\n\r\t\v\u00A0\u2028\u2029].*)?$' for i in args
]])
```
###Telethon example
```
@client.on(events.NewMessage(pattern=commands("start", "help"))
async def start(event):
print(evet)
```
###Pyrogram example
```
@app.on_message(filters.regex(commands("start", "help")))
async def start(client, message):
print(message)
```
@tshipenchko
Copy link
Author

tshipenchko commented Feb 19, 2021

A shit i forgot that

sthg

won't work((

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment