Exemple #1
0
    async def modify_webhook(self,
                             webhook_id,
                             webhook_token=None,
                             name=None,
                             avatar=None) -> Dict:
        if not webhook_token:
            r = Route("PATCH",
                      "/webhooks/{webhook_id}".format(webhook_id=webhook_id))
        else:
            r = Route(
                "PATCH", "/webhooks/{webhook_id}/{webhook_token}".format(
                    webhook_id=webhook_id, webhook_token=webhook_token))

        payload = {}

        if name:
            payload["name"] = name

        if avatar:
            payload["avatar"] = avatar

        if not payload:
            raise KeyError("Must include either `name`, `avatar`, or both")

        return await self.http.request(r, json=payload)
Exemple #2
0
    async def collect_discoverable_guilds(self):
        limit = 48
        offset = 0
        params = {"offset": offset, "limit": limit}

        request = await self.http.request(
            Route("GET", f"/discoverable-guilds"), params=params
        )

        guild_dict = {guild["id"]: guild for guild in request["guilds"]}

        while request["total"] > 0:

            await asyncio.sleep(0.5)

            offset += limit

            params = {"offset": offset, "limit": limit}

            request = await self.http.request(
                Route("GET", f"/discoverable-guilds"), params=params
            )

            temp_dict = {guild["id"]: guild for guild in request["guilds"]}
            guild_dict.update(temp_dict)

        return guild_dict
Exemple #3
0
    async def get_webhook(self, webhook_id, webhook_token) -> Dict:
        if not webhook_token:
            r = Route("GET",
                      "/webhooks/{webhook_id}".format(webhook_id=webhook_id))
        else:
            r = Route(
                "GET", "/webhooks/{webhook_id}/{webhook_token}".format(
                    webhook_id=webhook_id, webhook_token=webhook_token))

        return await self.http.request(r)
Exemple #4
0
    async def delete_webhook(self, webhook_id, webhook_token=None) -> None:
        if not webhook_token:
            r = Route("DELETE",
                      "/webhooks/{webhook_id}".format(webhook_id=webhook_id))
        else:
            r = Route(
                "DELETE", "/webhooks/{webhook_id}/{webhook_token}".format(
                    webhook_id=webhook_id, webhook_token=webhook_token))

        await self.http.request(r)
Exemple #5
0
async def get_banner(user_id):
    """Manualy request to discord api since discord.py haven't implement banner"""
    rr = Route('GET', 'None')
    rr.url = f'https://discord.com/api/v9/users/{user_id}'
    res = await bot.http.request(rr)
    if res['banner'] is None:
        return False
    fmt = "gif"
    url = f"https://cdn.discordapp.com/banners/{user_id}/{res['banner']}.{fmt}"
    http = urllib3.PoolManager()
    request = http.request("GET", url)
    if request.status != 200:
        fmt = "png"

    return f"https://cdn.discordapp.com/banners/{user_id}/{res['banner']}.{fmt}?size=512"
Exemple #6
0
    async def setup(self):
        # --- step 0.  set sane message notifications
        await self.bot.http.request(
            Route("PATCH", "/guilds/{guild_id}", guild_id=self.guild.id),
            json={"default_message_notifications": 1},
        )

        # --- step 1.  tweak base permissions
        perms = discord.Permissions()
        for sane_perm in PARTY_PERMISSIONS:
            setattr(perms, sane_perm, True)
        await self.guild.default_role.edit(permissions=perms)

        # --- step 2.  we need to be first
        await self.general.send("welcome to the party! \N{PARTY POPPER}")

        # --- step 3.  create party role for the creator
        self.creator_role = creator = await self.guild.create_role(
            name="party creator",
            color=discord.Color(0xFF6666),
            hoist=True,
            mentionable=True,
            permissions=Permissions.all(),
        )

        # --- step 4.  partygoers need a role
        self.partygoer_role = partygoer = await self.guild.create_role(
            name="partygoer", color=discord.Color(0x66CCFF), hoist=True)

        # --- step 5.  move roles
        await creator.edit(position=2)
        await partygoer.edit(position=1)

        # --- step 6.  add listeners
        self.bot.add_listener(self.handle_join, "on_member_join")
Exemple #7
0
async def on_interaction(i: Interaction):
    log.info('interaction channel=%s', i.channel)
    # log.info('interaction data is %s', i.data)
    iid = i.data['id']
    itoken = i.data['token']

    msg = 'What?'
    embeds = []

    greet_command = '%s-greet' % client.user.name.lower()
    todays_matches = '%s-foci-ma' % client.user.name.lower()

    command_data = i.data['data']

    if command_data['name'] == greet_command:
        greetee = get_command_option(command_data, 'name')
        age = get_command_option(command_data, 'age')

        if age is not None:
            greetee += ' (%s)' % age

        msg = 'Hello, %s!' % greetee
    elif command_data['name'] == todays_matches:
        embed = await get_todays_matches()
        embeds.append(embed)

    payload = {'type': 4, 'data': {'content': msg, 'embeds': embeds}}

    http_client: HTTPClient = i.state.http
    route = Route('POST', '/interactions/%s/%s/callback' % (iid, itoken))
    await http_client.request(route, json=payload)
Exemple #8
0
    async def get_channel_webhooks(self, channel) -> List[Dict]:
        if isinstance(channel, Channel):
            channel = channel.id

        r = Route("GET",
                  "/channels/{channel_id}/webhooks".format(channel_id=channel))
        return await self.http.request(r)
Exemple #9
0
    async def delete(self):
        if self.id:
            route = Route(
                "DELETE",
                "/webhooks/{application_id}/{interaction_token}/messages/{message_id}",
                application_id=Bloxlink.user.id,
                interaction_token=self.interaction_token,
                message_id=self.id)
        else:
            route = Route(
                "DELETE",
                "/webhooks/{application_id}/{interaction_token}/messages/@original",
                application_id=Bloxlink.user.id,
                interaction_token=self.interaction_token)

        await self._state.http.request(route)
Exemple #10
0
    async def edit_button_msg(
        self,
        message: Message,
        content: str = "",
        *,
        tts: bool = False,
        embed: Embed = None,
        allowed_mentions: AllowedMentions = None,
        buttons: List[Button] = None,
        **options,
    ):
        state = self.bot._get_state()
        if embed:
            embed = embed.to_dict()

        if allowed_mentions:
            if state.allowed_mentions:
                allowed_mentions = state.allowed_mentions.merge(allowed_mentions).to_dict()
            else:
                allowed_mentions = allowed_mentions.to_dict()
        else:
            allowed_mentions = state.allowed_mentions and state.allowed_mentions.to_dict()

        data = {
            "content": content,
            **self._get_buttons_json(buttons),
            **options,
            "embed": embed,
            "allowed_mentions": allowed_mentions,
            "tts": tts,
        }
        await self.bot.http.request(
            Route("PATCH", f"/channels/{message.channel.id}/messages/{message.id}"), json=data
        )
def send_message_components(
    *,
    content: Optional[str] = None,
    state: ConnectionState,
    channel_id: int,
    embed: Optional[Embed] = None,
    components: Optional[Sequence[Union[ActionRow, Button, Select]]] = None,
) -> Any:

    allowed_mentions = state.allowed_mentions and state.allowed_mentions.to_dict(
    )  # type: ignore
    components = [c.to_dict()
                  for c in components] if components is not None else None

    r = Route("POST", "/channels/{channel_id}/messages", channel_id=channel_id)
    payload: Dict[str, Any] = {}

    if content:
        payload["content"] = content

    if embed:
        payload["embeds"] = [embed.to_dict()]

    if allowed_mentions:
        payload["allowed_mentions"] = allowed_mentions

    if components:
        payload["components"] = components

    return state.http.request(r, json=payload)  # type: ignore
Exemple #12
0
    async def send_button_msg(
        self,
        channel: TextChannel,
        content: str = "",
        *,
        tts: bool = False,
        embed: Embed = None,
        allowed_mentions: AllowedMentions = None,
        buttons: List[Button] = None,
        **options,
    ) -> Message:
        state = self.bot._get_state()
        if embed:
            embed = embed.to_dict()

        if allowed_mentions:
            if state.allowed_mentions:
                allowed_mentions = state.allowed_mentions.merge(allowed_mentions).to_dict()
            else:
                allowed_mentions = allowed_mentions.to_dict()
        else:
            allowed_mentions = state.allowed_mentions and state.allowed_mentions.to_dict()

        data = {
            "content": content,
            **self._get_buttons_json(buttons),
            **options,
            "embed": embed,
            "allowed_mentions": allowed_mentions,
            "tts": tts,
        }
        data = await self.bot.http.request(
            Route("POST", f"/channels/{channel.id}/messages"), json=data
        )
        return Message(state=state, channel=channel, data=data)
def send_message_components(self, channel_id, content, *, tts=False, embed=None, nonce=None, allowed_mentions=None,
                 message_reference=None, components=None):
    r = Route('POST', '/channels/{channel_id}/messages', channel_id=channel_id)
    payload = {}

    if content:
        payload['content'] = content

    if tts:
        payload['tts'] = True

    if embed:
        payload['embed'] = embed

    if nonce:
        payload['nonce'] = nonce

    if allowed_mentions:
        payload['allowed_mentions'] = allowed_mentions

    if message_reference:
        payload['message_reference'] = message_reference

    if components:
        payload['components'] = components

    return self.request(r, json=payload)
Exemple #14
0
 async def respond(self,
                   type: int,
                   content: str,
                   embed: Optional[discord.Embed] = None,
                   embeds: Optional[List[discord.Embed]] = None,
                   tts: Optional[bool] = None,
                   flags: Optional[int] = None):
     Route('POST', '')
Exemple #15
0
    async def send_to(self,
                      dest,
                      content=None,
                      files=None,
                      embed=None,
                      allowed_mentions=AllowedMentions(everyone=False,
                                                       roles=False),
                      send_as_slash_command=True,
                      hidden=False,
                      reference=None,
                      mention_author=None,
                      fail_on_dm=None):
        msg = None

        if fail_on_dm and isinstance(dest, (DMChannel, User, Member)):
            return None

        if isinstance(dest, Webhook):
            msg = await dest.send(content,
                                  username=self.bot_name,
                                  avatar_url=self.bot_avatar,
                                  embed=embed,
                                  files=files,
                                  wait=True,
                                  allowed_mentions=allowed_mentions)

        elif self.slash_command and send_as_slash_command:
            payload = {
                "content": content,
                "embeds": [embed.to_dict()] if embed else None,
                "flags": 1 << 6 if hidden else None
            }

            route = Route("POST",
                          "/webhooks/{application_id}/{interaction_token}",
                          application_id=Bloxlink.user.id,
                          interaction_token=self.slash_command["token"])

            response = await self.channel._state.http.request(route,
                                                              json=payload)

            msg = InteractionWebhook(
                interaction_token=self.slash_command["token"],
                data=response,
                state=self.channel._state,
                channel=self.channel)

        else:
            msg = await dest.send(content,
                                  embed=embed,
                                  files=files,
                                  allowed_mentions=allowed_mentions,
                                  reference=reference,
                                  mention_author=mention_author)

        self.bot_responses.append(msg.id)

        return msg
Exemple #16
0
 async def move_channels(self, server: discord.Server,
                         channels: List[discord.Channel]):
     payload = [{
         'id': c.id,
         'position': index
     } for index, c in enumerate(channels)]
     r = Route('PATCH', '/guilds/{guild_id}/channels', guild_id=server.id)
     logger.debug('using payload: {0!r}'.format(payload))
     await self.bot.http.request(r, json=payload)
Exemple #17
0
 def request_guild_members(self, guild_id, query, limit=1):
     return self.request(
         Route(
             "GET",
             "/guilds/{guild_id}/members/search?query={query}&limit={limit}",
             guild_id=guild_id,
             query=query,
             limit=limit,
         ))
Exemple #18
0
 async def get_connections(self, access, refresh):
     async with self.oauth.get_oauth2_http(access, refresh) as http:
         all_connections = await http.request(
             Route('GET', '/users/@me/connections'))
     verified = []
     for connection in all_connections:
         if connection["verified"]:
             verified.append(connection)
     return verified
 def put_slash_commands(self, commands, guild_id=None):
     r = Route(
         "PUT",
         "/applications/{application_id}/commands" if not guild_id else
         "/applications/{application_id}/guilds/{guild_id}/commands",
         application_id=self.bot.user.id,
         guild_id=guild_id,
     )
     return self.bot.http.request(
         r, json=[command.to_dict(with_id=False) for command in commands])
Exemple #20
0
    async def _raw_send_no_mention(self, ctx, text: str):
        """Send chat as a raw payload to never mention included roles and @s."""
        r = Route("POST",
                  "/channels/{channel_id}/messages",
                  channel_id=ctx.channel.id)
        payload = {}
        payload["content"] = text
        payload["allowed_mentions"] = {"parse": []}

        await self.bot.http.request(r, json=payload)
Exemple #21
0
    async def slash_ack(self):
        if self.slash_command:
            route = Route(
                "POST",
                "/interactions/{interaction_id}/{interaction_token}/callback",
                interaction_id=self.slash_command["id"],
                interaction_token=self.slash_command["token"])

            payload = {"type": 5}

            await self.channel._state.http.request(route, json=payload)
Exemple #22
0
async def send_message(
    bot: Red,
    channel_id: int,
    *,
    content: Optional[str] = None,
    embed: Optional[discord.Embed] = None,
    file: Optional[discord.File] = None,
    url_button: Optional[URLButton] = None,
):
    """Send a message with a URL button, with pure dpy 1.7."""
    payload = {}

    if content:
        payload["content"] = content

    if embed:
        payload["embed"] = embed.to_dict()

    if url_button:
        payload["components"] = [{"type": 1, "components": [url_button.to_dict()]}]  # type:ignore

    if file:
        form = [
            {
                "name": "file",
                "value": file.fp,
                "filename": file.filename,
                "content_type": "application/octet-stream",
            },
            {"name": "payload_json", "value": discord.utils.to_json(payload)},
        ]

        r = Route("POST", "/channels/{channel_id}/messages", channel_id=channel_id)
        await bot._connection.http.request(r, form=form, files=[file])

    else:
        r = Route("POST", "/channels/{channel_id}/messages", channel_id=channel_id)
        await bot._connection.http.request(r, json=payload)
Exemple #23
0
 def tmp_post_request():
     payload = {
         'name': name,
         'type': str(discord.ChannelType.voice),
         'permission_overwrites': permissions_payload,
         'parent_id': target_category
     }
     return self.http.request(
         Route('POST',
               '/guilds/{guild_id}/channels',
               guild_id=message.server.id),
         json=payload,
         # reason=None
     )
Exemple #24
0
    async def edit(self, content=None, embed=None, *args, **kwargs):
        payload = {
            "content": content,
            "embeds": [embed.to_dict()] if embed else None
        }

        route = Route(
            "PATCH",
            "/webhooks/{application_id}/{interaction_token}/messages/{message_id}",
            application_id=Bloxlink.user.id,
            interaction_token=self.interaction_token,
            message_id=self.id)

        await self._state.http.request(route, json=payload)
 def raw_delete_slash_command(self, command_id, guild_id=None):
     url = (
         "applications/{application_id}/commands/{command_id}"
         if not guild_id else
         "applications/{my_application_id}/guilds/{guild_id}/commands/{command_id}"
     )
     r = Route(
         "DELETE",
         url,
         application_id=self.bot.user.id,
         command_id=command_id,
         guild_id=guild_id,
     )
     return self.bot.http.request(r)
Exemple #26
0
async def edit_role_icon(
    bot,
    role: Role,
    *,
    reason=None,
    icon: bytes = None,
    unicode_emoji: str = None,
    reset: bool = False,
):
    """|coro|

    Changes specified role's icon

    Parameters
    -----------
    role: :class:`discord.Role`
        A role to edit
    icon: :class:`bytes`
        A :term:`py:bytes-like object` representing the image to upload.
    unicode_emoji: :class:`str`
        A unicode emoji to set
    reason: Optional[:class:`str`]
        The reason for editing this role. Shows up on the audit log.

    Raises
    -------
    Forbidden
        You do not have permissions to change the role.
    HTTPException
        Editing the role failed.
    InvalidArgument
        Wrong image format passed for ``icon``.
        :param bot:
    """
    if not icon and not unicode_emoji and not reset:
        raise discord.InvalidArgument("You must specify icon or unicode_emoji")
    if reset:
        fields = {"unicode_emoji": None, "icon": None}
    else:
        fields = {
            "unicode_emoji": unicode_emoji,
            "icon": _bytes_to_base64_data(icon) if icon else None,
        }

    r = Route("PATCH",
              "/guilds/{guild_id}/roles/{role_id}",
              guild_id=role.guild.id,
              role_id=role.id)
    await bot.http.request(r, json=fields, reason=reason)
Exemple #27
0
 async def join_guild(self, guild_id: int, user_id: int,
                      access_token: str, **kwargs) -> Optional[str]:
     r = Route('PUT',
               '/guilds/{guild_id}/members/{user_id}',
               guild_id=guild_id,
               user_id=user_id)
     try:
         await bot.http.request(r,
                                json={
                                    "access_token": access_token,
                                    **kwargs
                                })
         return None
     except HTTPException as e:
         return e.text
Exemple #28
0
 async def slowmode(self,
                    ctx,
                    timeout: int = 10,
                    channel: discord.Channel = None):
     """Slows a channel."""
     if channel is None:
         channel = ctx.message.channel
     try:
         await self.bot.http.request(Route('PATCH',
                                           '/channels/{channel_id}',
                                           channel_id=channel.id),
                                     json={"rate_limit_per_user": timeout})
         await self.bot.say(
             f"Ratelimit set to {timeout} seconds in {channel}.")
     except:
         await self.bot.say("Failed to set ratelimit.")
Exemple #29
0
def send_files(self,
               channel_id,
               *,
               files,
               content=None,
               tts=False,
               embed=None,
               nonce=None,
               allowed_mentions=None,
               message_reference=None,
               components=None):
    r = Route('POST', '/channels/{channel_id}/messages', channel_id=channel_id)
    form = []

    payload = {'tts': tts}
    if content:
        payload['content'] = content
    if embed:
        payload['embed'] = embed
    if nonce:
        payload['nonce'] = nonce
    if allowed_mentions:
        payload['allowed_mentions'] = allowed_mentions
    if message_reference:
        payload['message_reference'] = message_reference
    if components:
        payload['components'] = components

    form.append({'name': 'payload_json', 'value': utils.to_json(payload)})
    if len(files) == 1:
        file = files[0]
        form.append({
            'name': 'file',
            'value': file.fp,
            'filename': file.filename,
            'content_type': 'application/octet-stream'
        })
    else:
        for index, file in enumerate(files):
            form.append({
                'name': 'file%s' % index,
                'value': file.fp,
                'filename': file.filename,
                'content_type': 'application/octet-stream'
            })

    return self.request(r, form=form, files=files)
Exemple #30
0
    async def respond(self,
                      response_type: InteractionResponseType,
                      content: Optional[str] = None,
                      embed: Optional[Embed] = None,
                      embeds: Optional[List[Embed]] = None,
                      allowed_mentions: Optional[AllowedMentions] = None,
                      tts: Optional[bool] = None,
                      flags: Optional[int] = None):
        state = self.client._get_state()
        data: JSON = {}

        if content:
            data['content'] = content

        if embed and embeds:
            embeds.append(embed)
        elif embed:
            embeds = [embed]

        if embeds and len(embeds) <= 10:
            data['embeds'] = list(map(embed.to_dict() for embed in embeds))

        if allowed_mentions:
            if state.allowed_mentions:
                data['allowed_mentions'] = state.allowed_mentions.merge(
                    allowed_mentions).to_dict()
            else:
                data['allowed_mentions'] = allowed_mentions.to_dict()
        else:
            data[
                'allowed_mentions'] = state.allowed_mentions and state.allowed_mentions.to_dict(
                )

        if tts:
            data['tts'] = tts

        await self.client.http.request(
            Route(
                "POST",
                f"/interactions/{self.interaction_id}/{self.interaction_token}/callback"
            ),
            json={
                "type": response_type.value,
                "data": data
            },
        )