pinhook
pinhook copied to clipboard
Use argparse to parse !command arguments?
When creating command-line scripts, the cool way to parse command-line arguments is to use the argparse
module. That could automatically generate help text (like for #19) with details about arguments. This should be easy to do with class-based plugins (#27) by using a way similar to how Django commands are designed:
import pinhook.plugin
class HelloPlugin(pinhook.plugin.BasePlugin):
help = 'Say hello to someone!'
def add_arguments(self, parser):
parser.add_argument(
'nick',
nargs='?',
default=None,
help='Nickname of the user to say hello to',
)
def handle(self, msg, **options):
message = 'Hello {}!'.format(options.get('nick', msg.nick))
return pinhook.plugin.message(message)
I love the functionality this will bring, but I worry it takes away the ability to make plugins really simple. I am going to think about ways to abstract this.
You could set add_arguments in BasePlugin to have the following default:
def add_arguments(self, parser):
parser.add_argument('args', nargs='*')
Then it becomes possible to have the following plugin:
import pinhook.plugin
class HelloPlugin(pinhook.plugin.BasePlugin):
help = 'Say hello to the world!'
def handle(self, msg, args=['world']):
return pinhook.plugin.message('Hello {} !'.format(', '.join(args)))
I literally just came up with a way to do this. Bad pseudocode to follow.
@pinhook.plugin.register('thing')
@pinhook.plugin.add_argument(args*, kwargs**)
def thing(msg):
return "pants"
basically this would run through and create an argument parser for the plugin object, and Message.args
would be an extended str
class that has the parsed string in it.
Of course, thinking about this more, I am not sure how those decorators stack 🤔