Exemple #1
0
class DiscordAPI:

    def __init__(self):
        self.api = APIClient(settings.DISCORD_BOT_TOKEN)
        self.guild = self.api.http(Routes.USERS_ME_GUILDS_LIST).json()[0]


    def is_user_in_guild(self, user_id):
        members = self.api.guilds_members_list(self.guild['id']).keys()
        return int(user_id) in members


    def kick_member(self, user_id):
        try:
            reason = "User no longer had the correct access level for discord"
            self.api.guilds_members_kick(self.guild['id'], user_id, reason)
            return True
        except:
            return False


    def set_name(self, user_id, name):
        try:
            self.api.guilds_members_modify(self.guild['id'], user_id, nick=name)
            return True
        except:
            return False


    # Roles is a list of role name strings
    def update_roles(self, user_id, roles):
        # Find roles we need to create
        guild_roles = self.api.guilds_roles_list(self.guild['id'])
        guild_roles_map = map(lambda x: x.name, guild_roles)
        for role_name in Set(roles).difference(guild_roles_map):
            role = self.api.guilds_roles_create(self.guild['id'])
            self.api.guilds_roles_modify(self.guild['id'], role.id, name=role_name)
            guild_roles.append(role)

        # Build snowflake list
        snowflakes = []
        for role in roles:
            snowflakes.append(filter(lambda x: x.name == role, guild_roles)[0].id)

        self.api.guilds_members_modify(self.guild['id'], user_id, roles=snowflakes)
Exemple #2
0
class DiscordInterface:
    TOKEN = None  # FIXME a long token from Discord

    # the next two should be big decimal numbers; in Discord, you can right
    # click and Copy ID to get them
    GUILD = 'FIXME'
    HINT_CHANNEL = 'FIXME'

    # You also need to enable the "Server Members Intent" under the "Privileged
    # Gateway Intents" section of the "Bot" page of your application from the
    # Discord Developer Portal. Or you can comment out the code that
    # initializes `self.avatars` below.

    def __init__(self):
        self.client = None
        self.avatars = None
        if self.TOKEN and not settings.IS_TEST:
            self.client = APIClient(self.TOKEN)

    def get_avatars(self):
        if self.avatars is None:
            self.avatars = {}
            if self.client is not None:
                members = self.client.guilds_members_list(self.GUILD).values()
                for member in members:
                    self.avatars[member.user.username] = member.user.avatar_url
                for member in members:
                    self.avatars[member.name] = member.user.avatar_url
        return self.avatars

    # If you get an error code 50001 when trying to create a message, even
    # though you're sure your bot has all the permissions, it might be because
    # you need to "connect to and identify with a gateway at least once"??
    # https://discord.com/developers/docs/resources/channel#create-message

    # I spent like four hours trying to find weird asynchronous ways to do this
    # right before each time I send a message, but it seems maybe you actually
    # just need to do this once and your bot can create messages forever?
    # disco.py's Client (not APIClient) wraps an APIClient and a GatewayClient,
    # the latter of which does this. So I believe you can fix this by running a
    # script like the following *once* on your local machine (it will, as
    # advertised, run forever; just kill it after a few seconds)?

    # from gevent import monkey
    # monkey.patch_all()
    # from disco.client import Client, ClientConfig
    # Client(ClientConfig({'token': TOKEN})).run_forever()

    def update_hint(self, hint):
        HintsConsumer.send_to_all(
            json.dumps({
                'id':
                hint.id,
                'content':
                render_to_string('hint_list_entry.html', {
                    'hint': hint,
                    'now': timezone.localtime()
                })
            }))
        embed = MessageEmbed()
        embed.author.url = hint.full_url()
        if hint.claimed_datetime:
            embed.color = 0xdddddd
            embed.timestamp = hint.claimed_datetime.isoformat()
            embed.author.name = 'Claimed by {}'.format(hint.claimer)
            if hint.claimer in self.get_avatars():
                embed.author.icon_url = self.get_avatars()[hint.claimer]
            debug = 'claimed by {}'.format(hint.claimer)
        else:
            embed.color = 0xff00ff
            embed.author.name = 'U N C L A I M E D'
            claim_url = hint.full_url(claim=True)
            embed.title = 'Claim: ' + claim_url
            embed.url = claim_url
            debug = 'unclaimed'

        if self.client is None:
            message = hint.long_discord_message()
            logger.info('Hint, {}: {}\n{}'.format(debug, hint, message))
            logger.info('Embed: {}'.format(embed.to_dict()))
        elif hint.discord_id:
            try:
                self.client.channels_messages_modify(self.HINT_CHANNEL,
                                                     hint.discord_id,
                                                     embed=embed)
            except Exception:
                dispatch_general_alert(
                    'Discord API failure: modify\n{}'.format(
                        traceback.format_exc()))
        else:
            message = hint.long_discord_message()
            try:
                discord_id = self.client.channels_messages_create(
                    self.HINT_CHANNEL, message, embed=embed).id
            except Exception:
                dispatch_general_alert(
                    'Discord API failure: create\n{}'.format(
                        traceback.format_exc()))
                return
            hint.discord_id = discord_id
            hint.save(update_fields=('discord_id', ))

    def clear_hint(self, hint):
        HintsConsumer.send_to_all(json.dumps({'id': hint.id}))
        if self.client is None:
            logger.info('Hint done: {}'.format(hint))
        elif hint.discord_id:
            # try:
            #     self.client.channels_messages_delete(
            #         self.HINT_CHANNEL, hint.discord_id)
            # except Exception:
            #     dispatch_general_alert('Discord API failure: delete\n{}'.format(
            #         traceback.format_exc()))
            # hint.discord_id = ''
            # hint.save(update_fields=('discord_id',))

            # what DPPH did instead of deleting messages:
            # (nb. I tried to make these colors color-blind friendly)

            embed = MessageEmbed()
            if hint.status == 'ANS':
                embed.color = 0xaaffaa
            elif hint.status == 'REF':
                embed.color = 0xcc6600
            # nothing for obsolete

            embed.author.name = '{} by {}'.format(hint.status, hint.claimer)
            embed.author.url = hint.full_url()
            embed.description = hint.response[:250]
            if hint.claimer in self.get_avatars():
                embed.author.icon_url = self.get_avatars()[hint.claimer]
            debug = 'claimed by {}'.format(hint.claimer)
            try:
                self.client.channels_messages_modify(
                    self.HINT_CHANNEL,
                    hint.discord_id,
                    content=hint.short_discord_message(),
                    embed=embed)
            except Exception:
                dispatch_general_alert(
                    'Discord API failure: modify\n{}'.format(
                        traceback.format_exc()))