aboutsummaryrefslogtreecommitdiff
path: root/discord/ext/commands/converter.py
blob: eb1023b03f1230998fc31a8560bd507ac512dd82 (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
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
# -*- coding: utf-8 -*-

"""
The MIT License (MIT)

Copyright (c) 2015-2016 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.
"""

import discord
import asyncio
import re
import inspect

from .errors import BadArgument, NoPrivateMessage

__all__ = [ 'Converter', 'MemberConverter', 'UserConverter',
            'ChannelConverter', 'InviteConverter', 'RoleConverter',
            'GameConverter', 'ColourConverter' ]

def _get_from_guilds(bot, getter, argument):
    result = None
    for guild in bot.guilds:
        result = getattr(guild, getter)(argument)
        if result:
            return result
    return result

class Converter:
    """The base class of custom converters that require the :class:`Context`
    to be passed to be useful.

    This allows you to implement converters that function similar to the
    special cased ``discord`` classes.

    Classes that derive from this should override the :meth:`convert` method
    to do its conversion logic. This method could be a coroutine or a regular
    function.

    Attributes
    -----------
    ctx: :class:`Context`
        The invocation context that the argument is being used in.
    argument: str
        The argument that is being converted.
    """
    def __init__(self, ctx, argument):
        self.ctx = ctx
        self.argument = argument

    def convert(self):
        raise NotImplementedError('Derived classes need to implement this.')

class IDConverter(Converter):
    def __init__(self, ctx, argument):
        super().__init__(ctx, argument)
        self._id_regex = re.compile(r'([0-9]{15,21})$')

    def _get_id_match(self):
        return self._id_regex.match(self.argument)

class MemberConverter(IDConverter):
    def convert(self):
        message = self.ctx.message
        bot = self.ctx.bot
        match = self._get_id_match() or re.match(r'<@!?([0-9]+)>$', self.argument)
        guild = message.guild
        result = None
        if match is None:
            # not a mention...
            if guild:
                result = guild.get_member_named(self.argument)
            else:
                result = _get_from_guilds(bot, 'get_member_named', self.argument)
        else:
            user_id = int(match.group(1))
            if guild:
                result = guild.get_member(user_id)
            else:
                result = _get_from_guilds(bot, 'get_member', user_id)

        if result is None:
            raise BadArgument('Member "{}" not found'.format(self.argument))

        return result

UserConverter = MemberConverter

class ChannelConverter(IDConverter):
    def convert(self):
        message = self.ctx.message
        bot = self.ctx.bot

        match = self._get_id_match() or re.match(r'<#([0-9]+)>$', self.argument)
        result = None
        guild = message.guild
        if match is None:
            # not a mention
            if guild:
                result = discord.utils.get(guild.channels, name=self.argument)
            else:
                result = discord.utils.get(bot.get_all_channels(), name=self.argument)
        else:
            channel_id = int(match.group(1))
            if guild:
                result = guild.get_channel(channel_id)
            else:
                result = _get_from_guilds(bot, 'get_channel', channel_id)

        if result is None:
            raise BadArgument('Channel "{}" not found.'.format(self.argument))

        return result

class ColourConverter(Converter):
    def convert(self):
        arg = self.argument.replace('0x', '').lower()

        if arg[0] == '#':
            arg = arg[1:]
        try:
            value = int(arg, base=16)
            return discord.Colour(value=value)
        except ValueError:
            method = getattr(discord.Colour, arg, None)
            if method is None or not inspect.ismethod(method):
                raise BadArgument('Colour "{}" is invalid.'.format(arg))
            return method()

class RoleConverter(IDConverter):
    def convert(self):
        guild = self.ctx.message.guild
        if not guild:
            raise NoPrivateMessage()

        match = self._get_id_match() or re.match(r'<@&([0-9]+)>$', self.argument)
        params = dict(id=int(match.group(1))) if match else dict(name=self.argument)
        result = discord.utils.get(guild.roles, **params)
        if result is None:
            raise BadArgument('Role "{}" not found.'.format(self.argument))
        return result

class GameConverter(Converter):
    def convert(self):
        return discord.Game(name=self.argument)

class InviteConverter(Converter):
    @asyncio.coroutine
    def convert(self):
        try:
            invite = yield from self.ctx.bot.get_invite(self.argument)
            return invite
        except Exception as e:
            raise BadArgument('Invite is invalid or expired') from e

class EmojiConverter(IDConverter):
    @asyncio.coroutine
    def convert(self):
        message = self.ctx.message
        bot = self.ctx.bot

        match = self._get_id_match() or re.match(r'<:[a-zA-Z0-9]+:([0-9]+)>$', self.argument)
        result = None
        guild = message.guild
        if match is None:
            # Try to get the emoji by name. Try local guild first.
            if guild:
                result = discord.utils.get(guild.emojis, name=self.argument)

            if result is None:
                result = discord.utils.get(bot.get_all_emojis(), name=self.argument)
        else:
            emoji_id = int(match.group(1))

            # Try to look up emoji by id.
            if guild:
                result = discord.utils.get(guild.emojis, id=emoji_id)

            if result is None:
                result = discord.utils.get(bot.get_all_emojis(), id=emoji_id)

        if result is None:
            raise BadArgument('Emoji "{}" not found.'.format(self.argument))

        return result