File: parameters.py

package info (click to toggle)
python-discord 2.5.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,180 kB
  • sloc: python: 46,013; javascript: 363; makefile: 154
file content (322 lines) | stat: -rw-r--r-- 9,510 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
"""
The MIT License (MIT)

Copyright (c) 2015-present Rapptz

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""

from __future__ import annotations

import inspect
from operator import attrgetter
from typing import TYPE_CHECKING, Any, Literal, Optional, OrderedDict, Union, Protocol

from discord.utils import MISSING, maybe_coroutine

from .errors import NoPrivateMessage
from .converter import GuildConverter

from discord import (
    Member,
    User,
    TextChannel,
    VoiceChannel,
    DMChannel,
    Thread,
)

if TYPE_CHECKING:
    from typing_extensions import Self

    from discord import Guild

    from .context import Context

__all__ = (
    'Parameter',
    'parameter',
    'param',
    'Author',
    'CurrentChannel',
    'CurrentGuild',
)


ParamKinds = Union[
    Literal[inspect.Parameter.POSITIONAL_ONLY],
    Literal[inspect.Parameter.POSITIONAL_OR_KEYWORD],
    Literal[inspect.Parameter.VAR_POSITIONAL],
    Literal[inspect.Parameter.KEYWORD_ONLY],
    Literal[inspect.Parameter.VAR_KEYWORD],
]

empty: Any = inspect.Parameter.empty


def _gen_property(name: str) -> property:
    attr = f'_{name}'
    return property(
        attrgetter(attr),
        lambda self, value: setattr(self, attr, value),
        doc=f"The parameter's {name}.",
    )


class Parameter(inspect.Parameter):
    r"""A class that stores information on a :class:`Command`\'s parameter.

    This is a subclass of :class:`inspect.Parameter`.

    .. versionadded:: 2.0
    """

    __slots__ = ('_displayed_default', '_description', '_fallback', '_displayed_name')

    def __init__(
        self,
        name: str,
        kind: ParamKinds,
        default: Any = empty,
        annotation: Any = empty,
        description: str = empty,
        displayed_default: str = empty,
        displayed_name: str = empty,
    ) -> None:
        super().__init__(name=name, kind=kind, default=default, annotation=annotation)
        self._name = name
        self._kind = kind
        self._description = description
        self._default = default
        self._annotation = annotation
        self._displayed_default = displayed_default
        self._fallback = False
        self._displayed_name = displayed_name

    def replace(
        self,
        *,
        name: str = MISSING,  # MISSING here cause empty is valid
        kind: ParamKinds = MISSING,
        default: Any = MISSING,
        annotation: Any = MISSING,
        description: str = MISSING,
        displayed_default: Any = MISSING,
        displayed_name: Any = MISSING,
    ) -> Self:
        if name is MISSING:
            name = self._name
        if kind is MISSING:
            kind = self._kind  # type: ignore  # this assignment is actually safe
        if default is MISSING:
            default = self._default
        if annotation is MISSING:
            annotation = self._annotation
        if description is MISSING:
            description = self._description
        if displayed_default is MISSING:
            displayed_default = self._displayed_default
        if displayed_name is MISSING:
            displayed_name = self._displayed_name

        ret = self.__class__(
            name=name,
            kind=kind,
            default=default,
            annotation=annotation,
            description=description,
            displayed_default=displayed_default,
            displayed_name=displayed_name,
        )
        ret._fallback = self._fallback
        return ret

    if not TYPE_CHECKING:  # this is to prevent anything breaking if inspect internals change
        name = _gen_property('name')
        kind = _gen_property('kind')
        default = _gen_property('default')
        annotation = _gen_property('annotation')

    @property
    def required(self) -> bool:
        """:class:`bool`: Whether this parameter is required."""
        return self.default is empty

    @property
    def converter(self) -> Any:
        """The converter that should be used for this parameter."""
        if self.annotation is empty:
            return type(self.default) if self.default not in (empty, None) else str

        return self.annotation

    @property
    def description(self) -> Optional[str]:
        """Optional[:class:`str`]: The description of this parameter."""
        return self._description if self._description is not empty else None

    @property
    def displayed_default(self) -> Optional[str]:
        """Optional[:class:`str`]: The displayed default in :class:`Command.signature`."""
        if self._displayed_default is not empty:
            return self._displayed_default

        if self.required:
            return None

        if callable(self.default) or self.default is None:
            return None

        return str(self.default)

    @property
    def displayed_name(self) -> Optional[str]:
        """Optional[:class:`str`]: The name that is displayed to the user.

        .. versionadded:: 2.3
        """
        return self._displayed_name if self._displayed_name is not empty else None

    async def get_default(self, ctx: Context[Any]) -> Any:
        """|coro|

        Gets this parameter's default value.

        Parameters
        ----------
        ctx: :class:`Context`
            The invocation context that is used to get the default argument.
        """
        # pre-condition: required is False
        if callable(self.default):
            return await maybe_coroutine(self.default, ctx)
        return self.default


def parameter(
    *,
    converter: Any = empty,
    default: Any = empty,
    description: str = empty,
    displayed_default: str = empty,
    displayed_name: str = empty,
) -> Any:
    r"""parameter(\*, converter=..., default=..., description=..., displayed_default=..., displayed_name=...)

    A way to assign custom metadata for a :class:`Command`\'s parameter.

    .. versionadded:: 2.0

    Examples
    --------
    A custom default can be used to have late binding behaviour.

    .. code-block:: python3

        @bot.command()
        async def wave(ctx, to: discord.User = commands.parameter(default=lambda ctx: ctx.author)):
            await ctx.send(f'Hello {to.mention} :wave:')

    Parameters
    ----------
    converter: Any
        The converter to use for this parameter, this replaces the annotation at runtime which is transparent to type checkers.
    default: Any
        The default value for the parameter, if this is a :term:`callable` or a |coroutine_link|_ it is called with a
        positional :class:`Context` argument.
    description: :class:`str`
        The description of this parameter.
    displayed_default: :class:`str`
        The displayed default in :attr:`Command.signature`.
    displayed_name: :class:`str`
        The name that is displayed to the user.

        .. versionadded:: 2.3
    """
    if isinstance(default, Parameter):
        if displayed_default is empty:
            displayed_default = default._displayed_default

        default = default._default

    return Parameter(
        name='empty',
        kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,
        annotation=converter,
        default=default,
        description=description,
        displayed_default=displayed_default,
        displayed_name=displayed_name,
    )


class ParameterAlias(Protocol):
    def __call__(
        self,
        *,
        converter: Any = empty,
        default: Any = empty,
        description: str = empty,
        displayed_default: str = empty,
        displayed_name: str = empty,
    ) -> Any:
        ...


param: ParameterAlias = parameter
r"""param(\*, converter=..., default=..., description=..., displayed_default=..., displayed_name=...)

An alias for :func:`parameter`.

.. versionadded:: 2.0
"""

# some handy defaults
Author = parameter(
    default=attrgetter('author'),
    displayed_default='<you>',
    converter=Union[Member, User],
)
Author._fallback = True

CurrentChannel = parameter(
    default=attrgetter('channel'),
    displayed_default='<this channel>',
    converter=Union[TextChannel, DMChannel, Thread, VoiceChannel],
)
CurrentChannel._fallback = True


def default_guild(ctx: Context[Any]) -> Guild:
    if ctx.guild is not None:
        return ctx.guild
    raise NoPrivateMessage()


CurrentGuild = parameter(
    default=default_guild,
    displayed_default='<this server>',
    converter=GuildConverter,
)
CurrentGuild._fallback = True


class Signature(inspect.Signature):
    _parameter_cls = Parameter
    parameters: OrderedDict[str, Parameter]