archangelic / pinhook

the pluggable python framework for IRC bots and Twitch bots
https://archangelic.github.io/pinhook/
MIT License
31 stars 4 forks source link

Use argparse to parse !command arguments? #30

Open Lucidiot opened 5 years ago

Lucidiot commented 5 years ago

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)
archangelic commented 5 years ago

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.

Lucidiot commented 5 years ago

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)))
archangelic commented 5 years ago

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 commented 5 years ago

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