Last active
February 19, 2021 06:13
-
-
Save tshipenchko/42b81fb53bd52ca7034eb6f2b1b99799 to your computer and use it in GitHub Desktop.
Telegram bots commands regex handler (python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##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) | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A shit i forgot that
won't work((