Package: telegram-click-aio
telegram-click-aioClickinspired command-line interface creation toolkit foraiogram, optimized for asyncio.Note that this library canonlybe used with asyncio. If you are looking for a non-asyncio andpython-telegram-botcompatible variant have a look attelegram-click!FeaturesPOSIX style argument parsingQuoted arguments (/command "Hello World")Named arguments (/command --text "Hello World")Value Separator (/command --text=myvalue)Flags (/command --yes)Multiple combined Flags (/command -Syu)Optional argumentsType conversion including support for custom typesArgument input validationAutomatic help messagesShow help messages when a command was used with invalid argumentsList all available commands with a single methodPermission handlingSet up permissions for each command separatelyLimit command execution to private chats or group adminsCombine permissions using logical operatorsCreate custom permission handlersError handlingAutomatically send error and help messages if something goes wrongWrite custom error handlersHow to useInstall this library as a dependency to use it in your project.pipinstalltelegram-click-aioThen annotate your command handler functions with the@commanddecorator
of this library:fromaiogramimportBotfromaiogram.typesimportMessagefromtelegram_click_aio.decoratorimportcommandfromtelegram_click_aio.argumentimportArgumentclassMyBot:[...]@command(name='start',description='Start bot interaction')asyncdef_start_command_callback(self,message:Message):# do somethingpass@command(name='age',description='Set age',arguments=[Argument(name='age',description='The new age',type=int,validator=lambdax:x>0,example='25')])asyncdef_age_command_callback(self,bot:Bot,message:Message,age:int):awaitbot.send_message(message.chat.id,"New age:{}".format(age))Argumentstelegram-click-aioparses arguments using a custom tokenizer:space acts as an argument delimiter, except when quoted (supporting both"and')argument keys are prefixed with--,—(long dash) or-(for single character keys)quoted arguments are never considered as argument keys, even when prefixed with--or—flags can be combined in a single argument (f.ex.-AxZ)The behaviour should be pretty intuitive. If it's not, let's discuss and improve it!NamingArguments can have multiple names to allow for abbreviated names. The
first name you specify for an argument will be used for the
callback parameter name (normalized to snake-case). Because of this
it is advisable to specify a full word argument name as the first one.TypesSince all user input initially is of typestrthere needs to be a type
conversion if the expected type is not astr. For basic types likebool,int,floatandstrconverters are built in to this library.
If you want to use other types you have to specify how to convert thestrinput to your type using theconverterattribute of theArgumentconstructor:fromtelegram_click_aio.argumentimportArgumentArgument(name='age',description='The new age',type=MyType,converter=lambdax:MyType(x),validator=lambdax:x>0,example='25')FlagsTechnically you can use theArgumentclass to specify a flag, but since
many of its parameters are implicit for a flag theFlagclass can be used
instead:fromtelegram_click_aio.argumentimportFlagFlag(name='flag',description='My boolean flag')Permission handlingIf a command should only be executable when a specific criteria is met
you can specify those criteria using thepermissionsparameter:fromaiogram.typesimportMessagefromtelegram_click_aio.decoratorimportcommandfromtelegram_click_aio.permissionimportGROUP_ADMIN@command(name='permission',description='Needs permission',permissions=GROUP_ADMIN)asyncdef_permission_command_callback(self,message:Message):Multiple permissions can be combined using&,|and~(not) operators.If a user does not have permission to use a command it will not be displayed
when this user generate a list of commands.Integrated permission handlersNameDescriptionPRIVATE_CHATThe command can only be executed in a private chatNORMAL_GROUP_CHATThe command can only be executed in a normal groupSUPER_GROUP_CHATThe command can only be executed in a supergroupGROUP_CHATThe command can only be executed in either a normal or a supergroupUSER_IDOnly users whose user id is specified have permissionUSER_NAMEOnly users whose username is specified have permissionGROUP_CREATOROnly the group creator has permissionGROUP_ADMINOnly the group admin has permissionNOBODYNobody has permission (useful for callbacks triggered via code instead of user interaction f.ex. "unknown command" handler)ANYBODYAnybody has permission (this is the default)Custom permissionsIf none of the integrated permissions suit your needs you can simply write
your own permission handler by extending thePermissionbase class
and pass an instance of theMyPermissionclass to the list ofpermissions:fromaiogram.typesimportMessagefromtelegram_click_aio.decoratorimportcommandfromtelegram_click_aio.permission.baseimportPermissionfromtelegram_click_aio.permissionimportGROUP_ADMINclassMyPermission(Permission):asyncdefevaluate(self,message:Message)->bool:from_user=message.from_userreturnfrom_user.idin[12345,32435]@command(name='permission',description='Needs permission',permissions=MyPermission()&GROUP_ADMIN)asyncdef_permission_command_callback(self,message:Message):Show "Permission denied" messageThis behaviour is defined by the error handler. TheDefaultErrorHandlersilently ignores
command messages from users without permission. To change this simply define your own,
customizedErrorHandlerclass as shown in theexample.py.Targeted commandsTelegram supports the@notation to target commands at specific bot
usernames:/start               # unspecified
/start@myAwesomeBot  # targeted at self
/start@someOtherBot  # targeted at other botWhen using aMessageHandlerinstead of aCommandHandlerit is possible to catch even commands that are targeted at other bots.
By default only messages without a target, and messages that are targeted
directly at your bot are processed.To control this behaviour specify thecommand_targetparameter:fromaiogram.typesimportMessagefromtelegram_click_aio.decoratorimportcommandfromtelegram_click_aioimportCommandTargetfromtelegram_click_aio.permissionimportNOBODY@command(name="commands",description="List commands supported by this bot.",permissions=NOBODY,command_target=CommandTarget.UNSPECIFIED|CommandTarget.SELF)asyncdef_unknown_command_callback(self,message:Message):You can combineCommandTarget's using logical operators like in the
example above.Hidden commandsIn rare cases it can be useful to hide a command from the help output.
To do this you can use thehiddenparameter on the@commanddecorator
by either passingTrueorFalse, or a callable like f.ex. this one:asyncdefhide_whois_if_admin(message:Message):user_id=message.from_user.idreturnuser_idnotin[123456]This function is evaluated on each message and therefore provides
themessageobject fromaiogram, which
allows you to make decisions based on chat and user properties
among other things.Error handlingtelegram-click-aioautomatically handles errors in most situations.Errors are divided into three categories:Permission errorsInput validation errorsCommand execution errorsTheDefaultErrorHandlerwill handle these categories in the following way:Permission errors will be silently ignored.Input validation errors likean argument can not be parsed correctlyan invalid value is passed for an argumentwill send the exception message, as well as a help message of the command the user was trying to use.On command execution errors the user will be notified that his
command has crashed, without any specific error message.To modify the behaviour for each of those categories, define anErrorHandlerand
pass an instance of it to theerror_handlerparameter of the@commanddecorator,
like shown in theexample.py.ContributingGitHub is for social coding: if you want to write code, I encourage contributions through pull requests from forks
of this repository. Create GitHub tickets for bugs and new features and comment on the ones that you are interested in.Licensetelegram-click-aio
Copyright (c) 2020 Markus Ressel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.