aboutsummaryrefslogtreecommitdiff
path: root/discord/ui/item.py
blob: 7726407e93920aa1f982619c6a85463d26aebae2 (plain) (blame)
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
"""
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

from typing import Any, Callable, Coroutine, Dict, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Union
import inspect

from ..interactions import Interaction

__all__ = (
    'Item',
)

if TYPE_CHECKING:
    from ..enums import ComponentType
    from .view import View
    from ..components import Component

I = TypeVar('I', bound='Item')
ItemCallbackType = Callable[[Any, I, Interaction], Coroutine[Any, Any, Any]]


class Item:
    """Represents the base UI item that all UI components inherit from.

    The current UI items supported are:

    - :class:`discord.ui.Button`
    """

    __slots__: Tuple[str, ...] = (
        '_callback',
        '_pass_view_arg',
        'group_id',
    )

    __item_repr_attributes__: Tuple[str, ...] = ('group_id',)

    def __init__(self):
        self._callback: Optional[ItemCallbackType] = None
        self._pass_view_arg = True
        self.group_id: Optional[int] = None

    def to_component_dict(self) -> Dict[str, Any]:
        raise NotImplementedError

    def copy(self: I) -> I:
        raise NotImplementedError

    def refresh_state(self, component: Component) -> None:
        return None

    @classmethod
    def from_component(cls: Type[I], component: Component) -> I:
        return cls()

    @property
    def type(self) -> ComponentType:
        raise NotImplementedError

    def is_dispatchable(self) -> bool:
        return False

    def __repr__(self) -> str:
        attrs = ' '.join(f'{key}={getattr(self, key)!r}' for key in self.__item_repr_attributes__)
        return f'<{self.__class__.__name__} {attrs}>'

    @property
    def callback(self) -> Optional[ItemCallbackType]:
        """Returns the underlying callback associated with this interaction."""
        return self._callback

    @callback.setter
    def callback(self, value: Optional[ItemCallbackType]):
        if value is None:
            self._callback = None
            return

        # Check if it's a partial function
        try:
            partial = value.func
        except AttributeError:
            pass
        else:
            if not inspect.iscoroutinefunction(value.func):
                raise TypeError(f'inner partial function must be a coroutine')

            # Check if the partial is bound
            try:
                bound_partial = partial.__self__
            except AttributeError:
                pass
            else:
                self._pass_view_arg = not hasattr(bound_partial, '__discord_ui_view__')

            self._callback = value
            return

        try:
            func_self = value.__self__
        except AttributeError:
            pass
        else:
            if not isinstance(func_self, Item):
                raise TypeError(f'callback bound method must be from Item not {func_self!r}')
            else:
                value = value.__func__

        if not inspect.iscoroutinefunction(value):
            raise TypeError(f'callback must be a coroutine not {value!r}')

        self._callback = value

    async def _do_call(self, view: View, interaction: Interaction):
        if self._pass_view_arg:
            await self._callback(view, self, interaction)
        else:
            await self._callback(self, interaction)  # type: ignore