Debian Codegraph @

docs/user_guide/plugin_development/botcommands.rst

raw
1 Advanced bot commands
2 =====================
3
4
5 Automatic argument splitting
6 ----------------------------
7
8 With the `split_args_with` argument to :func:`~errbot.decorators.botcmd`,
9 you can specify a delimiter of the arguments and it will give you an
10 array of strings instead of a string:
11
12 .. code-block:: python
13
14 @botcmd(split_args_with=None)
15 def action(self, mess, args):
16 # if you send it !action one two three
17 # args will be ['one', 'two', 'three']
18
19 .. note::
20 `split_args_with` behaves exactly like :func:`str.split`, therefore
21 the value `None` can be used to split on any type of whitespace, such
22 as multiple spaces, tabs, etc. This is recommended over `' '` for
23 general use cases but you're free to use whatever argument you see
24 fit.
25
26
27 Subcommands
28 -----------
29
30 If you put an _ in the name of the function, Errbot will create what
31 looks like a subcommand for you. This is useful to group commands
32 that belong to each other together.
33
34 .. code-block:: python
35
36 @botcmd
37 def basket_add(self, mess, args):
38 # Will respond to !basket add
39 pass
40
41 @botcmd
42 def basket_remove(self, mess, args):
43 # Will respond to !basket remove
44 pass
45
46 .. note::
47 It will still respond to !basket_add and !basket_remove as well.
48
49
50 Argparse argument splitting
51 ----------------------------
52
53 With the :func:`~errbot.decorators.arg_botcmd` decorator you can specify
54 a command's arguments in `argparse format`_. The decorator can be used multiple times, and each use adds a new argument to the command. The decorator can be passed any valid `add_arguments()`_ parameters.
55
56 .. _`argparse format`: https://docs.python.org/3/library/argparse.html
57 .. _`add_arguments()`: https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument
58
59 .. code-block:: python
60
61 @arg_botcmd('first_name', type=str)
62 @arg_botcmd('--last-name', dest='last_name', type=str)
63 @arg_botcmd('--favorite', dest='favorite_number', type=int, default=42)
64 def hello(self, mess, first_name=None, last_name=None, favorite_number=None):
65 # if you send it !hello Err --last-name Bot
66 # first_name will be 'Err'
67 # last_name will be 'Bot'
68 # favorite_number will be 42
69
70 .. note::
71 * An argument's `dest` parameter is used as its kwargs key when your command is called.
72 * `favorite_number` would be `None` if we removed `default=42` from the :func:`~errbot.decorators.arg_botcmd` call.
73
74
75
76 Commands using regular expressions
77 ----------------------------------
78
79 In addition to the fixed commands created with the :func:`~errbot.decorators.botcmd`
80 decorator, Errbot supports an alternative type of bot function which can be triggered
81 based on a regular expression. These are created using the
82 :func:`~errbot.decorators.re_botcmd` decorator. There are two forms these can be
83 used, with and without the usual bot prefix.
84
85 In both cases, your method will receive the message object same as with a regular
86 :func:`~errbot.decorators.botcmd`, but instead of an `args` parameter, it takes
87 a `match` parameter which will receive an :class:`re.MatchObject`.
88
89 .. note::
90 By default, only the first occurrence of a match is returned, even if it can
91 match multiple parts of the message. If you specify `matchall=True`, you will
92 instead get a list of :class:`re.MatchObject` items, containing all the
93 non-overlapping matches that were found in the message.
94
95
96 With a bot prefix
97 ~~~~~~~~~~~~~~~~~
98
99 You can define commands that trigger based on a regular expression, but still
100 require a bot prefix at the beginning of the line, in order to create more
101 flexible bot commands. Here's an example of a bot command that lets people
102 ask for cookies:
103
104 .. code-block:: python
105
106 from errbot import BotPlugin, re_botcmd
107
108 class CookieBot(BotPlugin):
109 """A cookiemonster bot"""
110
111 @re_botcmd(pattern=r"^(([Cc]an|[Mm]ay) I have a )?cookie please\?$")
112 def hand_out_cookies(self, msg, match):
113 """
114 Gives cookies to people who ask me nicely.
115
116 This command works especially nice if you have the following in
117 your `config.py`:
118
119 BOT_ALT_PREFIXES = ('Err',)
120 BOT_ALT_PREFIX_SEPARATORS = (':', ',', ';')
121
122 People are then able to say one of the following:
123
124 Err, can I have a cookie please?
125 Err: May I have a cookie please?
126 Err; cookie please?
127 """
128 yield "Here's a cookie for you, {}".format(msg.frm)
129 yield "/me hands out a cookie."
130
131
132 Without a bot prefix
133 ~~~~~~~~~~~~~~~~~~~~
134
135 It's also possible to trigger commands even when no bot prefix is specified,
136 by passing `prefixed=False` to the :func:`~errbot.decorators.re_botcmd`
137 decorator. This is especially useful if you want to trigger on specific
138 keywords that could show up anywhere in a conversation:
139
140 .. code-block:: python
141
142 import re
143 from errbot import BotPlugin, re_botcmd
144
145 class CookieBot(BotPlugin):
146 """A cookiemonster bot"""
147
148 @re_botcmd(pattern=r"(^| )cookies?( |$)", prefixed=False, flags=re.IGNORECASE)
149 def listen_for_talk_of_cookies(self, msg, match):
150 """Talk of cookies gives Errbot a craving..."""
151 return "Somebody mentioned cookies? Om nom nom!"