pinhook icon indicating copy to clipboard operation
pinhook copied to clipboard

Use argparse to parse !command arguments?

Open Lucidiot opened this issue 6 years ago • 4 comments

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)

Lucidiot avatar Oct 07 '18 01:10 Lucidiot

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.

archangelic avatar Oct 07 '18 05:10 archangelic

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)))

Lucidiot avatar Oct 07 '18 07:10 Lucidiot

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.

archangelic avatar Apr 30 '19 19:04 archangelic

Of course, thinking about this more, I am not sure how those decorators stack 🤔

archangelic avatar Apr 30 '19 23:04 archangelic