Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import discord.message
- import re
- async def parse(message, commandIndex, trigger=None, script=None, cmdIndex=None,
- argsStart=None, argsEnd=None):
- """
- Reads user messages looking for valid command triggers (!COMMAND).
- When found the associated command is called from 'commandIndex'.
- :param message: Message from which the command will be parsed.
- :type message: discord.message.Message
- :param commandIndex: Index of command/function pairs that
- determine which command will be run for each !COMMAND keyword.
- eg. {'!hello': func_hello}
- :type commandIndex: dict
- :return: Awaited result of the executed command.
- """
- # Sterilizes user input
- assert isinstance(message, discord.message.Message), (
- 'Invalid type for args \'message\':'
- f' Expected <class \'discord.message.Message\'>'
- f' got {type(message)}'
- )
- assert isinstance(commandIndex, dict), (
- 'Invalid type for args \'commandIndex\':'
- f' Expected {type({})}'
- f' got {type(commandIndex)}'
- )
- # Updates non-required args
- if trigger is None: trigger = lambda x: x.content.startswith('!')
- if script is None: script = r'"(.*?)"|(\S+)'
- if cmdIndex is None: cmdIndex = 0
- if argsStart is None: argsStart = 1
- if argsEnd is None: argsEnd = -1
- # Trigger condition
- if trigger(message):
- # Using regex script given through 'script', the message is
- # decomposed into a list of strings which will be given as
- # args to desired command.
- raw = [
- ''.join(x)
- for x in re.findall(script, message.content)
- ]
- # 'raw' must contain data by this point to avoid index errors
- # later on.
- assert raw, 'Not enough items in \'raw\': Minimum 1'
- # Gathers the command, and all args from 'raw' using
- # 'cmdIndex', 'argsStart', and 'argsEnd'.
- command, args = raw[cmdIndex], raw[argsStart:argsEnd]
- # Begins the awaited execution of the associated command
- # located in 'commandIndex'.
- if command in commandIndex:
- return await commandIndex[command](message, args)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement