Skip to content
This repository has been archived by the owner on Dec 26, 2022. It is now read-only.

Commit

Permalink
🔀 Merge pull request #315 from Endercheif/UserMessage-constructor
Browse files Browse the repository at this point in the history
✨ Added UserMessage.from_id
  • Loading branch information
Lunarmagpie authored Dec 21, 2021
2 parents 3428f1d + b52a058 commit cfa862e
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 27 deletions.
59 changes: 43 additions & 16 deletions pincer/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,15 @@
from importlib import import_module
from inspect import isasyncgenfunction
from typing import (
Any, Dict, Iterable, List, Optional, Tuple, Union, overload,
AsyncIterator, TYPE_CHECKING
Any,
Dict,
List,
Optional,
Tuple,
Union,
overload,
AsyncIterator,
TYPE_CHECKING
)
from . import __package__
from .commands import ChatCommandHandler
Expand All @@ -33,8 +40,10 @@
Guild,
Intents,
GuildTemplate,
StickerPack,
UserMessage,
Connection,
StickerPack, File
File
)
from .objects.guild.channel import GroupDMChannel
from .utils.conversion import construct_client_dict, remove_none
Expand Down Expand Up @@ -223,9 +232,10 @@ def chat_commands(self) -> List[str]:
Get a list of chat command calls which have been registered in
the :class:`~pincer.commands.ChatCommandHandler`\\.
"""
return list(
map(lambda cmd: cmd.app.name, ChatCommandHandler.register.values())
)
return [
cmd.app.name for cmd in ChatCommandHandler.register.values()
]


@property
def guild_ids(self) -> List[Snowflake]:
Expand Down Expand Up @@ -323,17 +333,15 @@ def get_event_coro(name: str) -> List[Optional[Coro]]:
calls = _events.get(name.strip().lower())

return (
[]
if not calls
else list(
filter(
lambda call: iscoroutinefunction(call)
or isasyncgenfunction(call),
calls,
)
)
[] if not calls
else [
call for call in calls
if iscoroutinefunction(call)
or isasyncgenfunction(call)
]
)


def load_cog(self, path: str, package: Optional[str] = None):
"""Load a cog from a string path, setup method in COG may
optionally have a first argument which will contain the client!
Expand Down Expand Up @@ -473,7 +481,7 @@ def execute_event(calls: List[Coro], *args, **kwargs):
if should_pass_cls(call):
call_args = (
ChatCommandHandler.managers[call.__module__],
*(arg for arg in args if arg is not None),
*remove_none(args),
)

ensure_future(call(*call_args, **kwargs))
Expand Down Expand Up @@ -859,6 +867,25 @@ async def get_channel(self, _id: int) -> Channel:
"""
return await Channel.from_id(self, _id)

async def get_message(self, _id: Snowflake, channel_id: Snowflake) -> UserMessage:
"""|coro|
Creates a UserMessage object
Parameters
----------
_id: :class:`~pincer.utils.snowflake.Snowflake`
ID of the message that is wanted.
channel_id : int
ID of the channel the message is in.
Returns
-------
:class:`~pincer.objects.message.user_message.UserMessage`
The message object.
"""

return await UserMessage.from_id(self, _id, channel_id)

async def get_webhook(
self, id: Snowflake, token: Optional[str] = None
) -> Webhook:
Expand Down
44 changes: 39 additions & 5 deletions pincer/objects/message/user_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
if TYPE_CHECKING:
from typing import Any, List, Optional, Union, Generator

from ... import Client
from ..guild.channel import Channel, ChannelMention
from ...utils.types import APINullable
from ...utils.timestamp import Timestamp
Expand All @@ -45,6 +46,7 @@ class AllowedMentionTypes(str, Enum):
EVERYONE:
Controls @everyone and @here mentions
"""

ROLES = "roles"
USERS = "users"
EVERYONE = "everyone"
Expand All @@ -66,6 +68,7 @@ class AllowedMentions(APIObject):
If replies should mention the author.
|default| :data:`True`
"""

# noqa: E501

parse: List[AllowedMentionTypes]
Expand All @@ -84,7 +87,7 @@ def get_str_id(obj: Union[Snowflake, User, Role]) -> str:
"parse": self.parse,
"roles": list(map(get_str_id, self.roles)),
"users": list(map(get_str_id, self.users)),
"replied_user": self.reply
"replied_user": self.reply,
}


Expand All @@ -104,6 +107,7 @@ class MessageActivityType(IntEnum):
JOIN_REQUEST:
Request to join.
"""

JOIN = 1
SPECTATE = 2
LISTEN = 3
Expand Down Expand Up @@ -138,6 +142,7 @@ class MessageFlags(IntEnum):
This message is an Interaction
Response and the bot is "thinking"
"""

CROSSPOSTED = 1 << 0
IS_CROSSPOST = 1 << 1
SUPPRESS_EMBEDS = 1 << 2
Expand Down Expand Up @@ -198,6 +203,7 @@ class MessageType(IntEnum):
GUILD_INVITE_REMINDER:
??
"""

DEFAULT = 0
RECIPIENT_ADD = 1
RECIPIENT_REMOVE = 2
Expand Down Expand Up @@ -241,6 +247,7 @@ class MessageActivity(APIObject):
party_id: APINullable[:class:`str`]
party_id from a Rich Presence event
"""

type: MessageActivityType
party_id: APINullable[str] = MISSING

Expand Down Expand Up @@ -317,6 +324,7 @@ class UserMessage(APIObject, GuildProperty, ChannelProperty):
sticker_items: APINullable[List[:class:`~pincer.objects.message.sticker.StickerItem`]]
Sent if the message contains stickers
"""

# noqa: E501

id: Snowflake
Expand Down Expand Up @@ -351,6 +359,33 @@ class UserMessage(APIObject, GuildProperty, ChannelProperty):
components: APINullable[List[MessageComponent]] = MISSING
sticker_items: APINullable[List[StickerItem]] = MISSING

@classmethod
async def from_id(
cls, client: Client, _id: Snowflake, channel_id: Snowflake
) -> UserMessage:
"""|coro|
Creates a UserMessage object
It is recommended to use the ``get_message`` function from
:class:`~pincer.client.Client` most of the time.
Parameters
----------
client : :class:`~pincer.client.Client`
Client object to use the HTTP class of.
_id: :class:`~pincer.utils.snowflake.Snowflake`
ID of the message that is wanted.
channel_id : int
ID of the channel the message is in.
Returns
-------
:class:`~pincer.objects.message.user_message.UserMessage`
The message object.
"""
msg = await client.http.get(f"channels/{channel_id}/messages/{_id}")
return cls.from_dict(construct_client_dict(client, msg))

def __str__(self):
return self.content

Expand All @@ -367,7 +402,7 @@ async def get_most_recent(self):
self._client,
await self._http.get(
f"/channels/{self.channel_id}/messages/{self.id}"
)
),
)
)

Expand Down Expand Up @@ -483,7 +518,7 @@ async def edit(
flags: int = None,
allowed_mentions: AllowedMentions = None,
attachments: List[Attachment] = None,
components: List[MessageComponent] = None
components: List[MessageComponent] = None,
):
"""|coro|
Expand Down Expand Up @@ -533,8 +568,7 @@ def set_if_not_none(value: Any, name: str):
set_if_not_none(components, "components")

await self._http.patch(
f"/channels/{self.channel_id}/messages/{self.id}",
data=data
f"/channels/{self.channel_id}/messages/{self.id}", data=data
)

async def delete(self):
Expand Down
14 changes: 8 additions & 6 deletions pincer/utils/conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

if TYPE_CHECKING:
from ..client import Client
from typing import Any, Callable, Dict, List, Optional, Set, Union
from typing import Any, Callable, Dict, List, Optional, Set, Union, Tuple


def construct_client_dict(client: Client, data: Dict) -> Dict:
Expand All @@ -29,22 +29,24 @@ def construct_client_dict(client: Client, data: Dict) -> Dict:
return {**data, "_client": client}


def remove_none(obj: Union[List, Dict, Set]) -> Union[List, Dict, Set]:
def remove_none(obj: Union[List, Dict, Set, Tuple]) -> Union[List, Dict, Set, Tuple]:
"""
Removes all ``None`` values from a list, dict or set.
Parameters
----------
obj : Union[List, Dict, Set]
The list, dict or set to remove ``None`` values from.
obj : Union[List, Dict, Set, Tuple]
The list, dict, set or tuple to remove ``None`` values from.
Returns
-------
Union[List, Dict, Set]
The list, dict or set without ``None`` values.
Union[List, Dict, Set, Tuple]
The list, dict, set or tuple, without ``None`` values.
"""
if isinstance(obj, list):
return [i for i in obj if i is not None]
elif isinstance(obj, tuple):
return tuple(i for i in obj if i is not None)
elif isinstance(obj, set):
return obj - {None}
elif isinstance(obj, dict):
Expand Down

0 comments on commit cfa862e

Please sign in to comment.