daily pastebin goal
1%
SHARE
TWEET

Untitled

a guest Mar 20th, 2019 112 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import discord.message
  2. import re
  3.  
  4.  
  5. async def parse(message, commandIndex, trigger=None, script=None, cmdIndex=None,
  6.                 argsStart=None, argsEnd=None):
  7.     """
  8.     Reads user messages looking for valid command triggers (!COMMAND).
  9.     When found the associated command is called from 'commandIndex'.
  10.  
  11.     :param message: Message from which the command will be parsed.
  12.     :type message: discord.message.Message
  13.     :param commandIndex: Index of command/function pairs that
  14.         determine which command will be run for each !COMMAND keyword.
  15.         eg. {'!hello': func_hello}
  16.     :type commandIndex: dict
  17.     :return: Awaited result of the executed command.
  18.     """
  19.  
  20.     # Sterilizes user input
  21.     assert isinstance(message, discord.message.Message), (
  22.         'Invalid type for args \'message\':'
  23.         f' Expected <class \'discord.message.Message\'>'
  24.         f' got {type(message)}'
  25.     )
  26.     assert isinstance(commandIndex, dict), (
  27.         'Invalid type for args \'commandIndex\':'
  28.         f' Expected {type({})}'
  29.         f' got {type(commandIndex)}'
  30.     )
  31.    
  32.     # Updates non-required args
  33.     if trigger is None: trigger = lambda x: x.content.startswith('!')
  34.     if script is None: script = r'"(.*?)"|(\S+)'
  35.     if cmdIndex is None: cmdIndex = 0
  36.     if argsStart is None: argsStart = 1
  37.     if argsEnd is None: argsEnd = -1
  38.  
  39.     # Trigger condition
  40.     if trigger(message):
  41.  
  42.         # Using regex script given through 'script', the message is
  43.         # decomposed into a list of strings which will be given as
  44.         # args to desired command.
  45.         raw = [
  46.             ''.join(x)
  47.             for x in re.findall(script, message.content)
  48.         ]
  49.  
  50.         # 'raw' must contain data by this point to avoid index errors
  51.         # later on.
  52.         assert raw, 'Not enough items in \'raw\': Minimum 1'
  53.  
  54.         # Gathers the command, and all args from 'raw' using
  55.         # 'cmdIndex', 'argsStart', and 'argsEnd'.
  56.         command, args = raw[cmdIndex], raw[argsStart:argsEnd]
  57.  
  58.         # Begins the awaited execution of the associated command
  59.         # located in 'commandIndex'.
  60.         if command in commandIndex:
  61.             return await commandIndex[command](message, args)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top