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

Commit cfa862e

Browse files
authored
🔀 Merge pull request #315 from Endercheif/UserMessage-constructor
✨ Added UserMessage.from_id
2 parents 3428f1d + b52a058 commit cfa862e

File tree

3 files changed

+90
-27
lines changed

3 files changed

+90
-27
lines changed

pincer/client.py

Lines changed: 43 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,15 @@
99
from importlib import import_module
1010
from inspect import isasyncgenfunction
1111
from typing import (
12-
Any, Dict, Iterable, List, Optional, Tuple, Union, overload,
13-
AsyncIterator, TYPE_CHECKING
12+
Any,
13+
Dict,
14+
List,
15+
Optional,
16+
Tuple,
17+
Union,
18+
overload,
19+
AsyncIterator,
20+
TYPE_CHECKING
1421
)
1522
from . import __package__
1623
from .commands import ChatCommandHandler
@@ -33,8 +40,10 @@
3340
Guild,
3441
Intents,
3542
GuildTemplate,
43+
StickerPack,
44+
UserMessage,
3645
Connection,
37-
StickerPack, File
46+
File
3847
)
3948
from .objects.guild.channel import GroupDMChannel
4049
from .utils.conversion import construct_client_dict, remove_none
@@ -223,9 +232,10 @@ def chat_commands(self) -> List[str]:
223232
Get a list of chat command calls which have been registered in
224233
the :class:`~pincer.commands.ChatCommandHandler`\\.
225234
"""
226-
return list(
227-
map(lambda cmd: cmd.app.name, ChatCommandHandler.register.values())
228-
)
235+
return [
236+
cmd.app.name for cmd in ChatCommandHandler.register.values()
237+
]
238+
229239

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

325335
return (
326-
[]
327-
if not calls
328-
else list(
329-
filter(
330-
lambda call: iscoroutinefunction(call)
331-
or isasyncgenfunction(call),
332-
calls,
333-
)
334-
)
336+
[] if not calls
337+
else [
338+
call for call in calls
339+
if iscoroutinefunction(call)
340+
or isasyncgenfunction(call)
341+
]
335342
)
336343

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

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

870+
async def get_message(self, _id: Snowflake, channel_id: Snowflake) -> UserMessage:
871+
"""|coro|
872+
Creates a UserMessage object
873+
874+
Parameters
875+
----------
876+
_id: :class:`~pincer.utils.snowflake.Snowflake`
877+
ID of the message that is wanted.
878+
channel_id : int
879+
ID of the channel the message is in.
880+
881+
Returns
882+
-------
883+
:class:`~pincer.objects.message.user_message.UserMessage`
884+
The message object.
885+
"""
886+
887+
return await UserMessage.from_id(self, _id, channel_id)
888+
862889
async def get_webhook(
863890
self, id: Snowflake, token: Optional[str] = None
864891
) -> Webhook:

pincer/objects/message/user_message.py

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
if TYPE_CHECKING:
2929
from typing import Any, List, Optional, Union, Generator
3030

31+
from ... import Client
3132
from ..guild.channel import Channel, ChannelMention
3233
from ...utils.types import APINullable
3334
from ...utils.timestamp import Timestamp
@@ -45,6 +46,7 @@ class AllowedMentionTypes(str, Enum):
4546
EVERYONE:
4647
Controls @everyone and @here mentions
4748
"""
49+
4850
ROLES = "roles"
4951
USERS = "users"
5052
EVERYONE = "everyone"
@@ -66,6 +68,7 @@ class AllowedMentions(APIObject):
6668
If replies should mention the author.
6769
|default| :data:`True`
6870
"""
71+
6972
# noqa: E501
7073

7174
parse: List[AllowedMentionTypes]
@@ -84,7 +87,7 @@ def get_str_id(obj: Union[Snowflake, User, Role]) -> str:
8487
"parse": self.parse,
8588
"roles": list(map(get_str_id, self.roles)),
8689
"users": list(map(get_str_id, self.users)),
87-
"replied_user": self.reply
90+
"replied_user": self.reply,
8891
}
8992

9093

@@ -104,6 +107,7 @@ class MessageActivityType(IntEnum):
104107
JOIN_REQUEST:
105108
Request to join.
106109
"""
110+
107111
JOIN = 1
108112
SPECTATE = 2
109113
LISTEN = 3
@@ -138,6 +142,7 @@ class MessageFlags(IntEnum):
138142
This message is an Interaction
139143
Response and the bot is "thinking"
140144
"""
145+
141146
CROSSPOSTED = 1 << 0
142147
IS_CROSSPOST = 1 << 1
143148
SUPPRESS_EMBEDS = 1 << 2
@@ -198,6 +203,7 @@ class MessageType(IntEnum):
198203
GUILD_INVITE_REMINDER:
199204
??
200205
"""
206+
201207
DEFAULT = 0
202208
RECIPIENT_ADD = 1
203209
RECIPIENT_REMOVE = 2
@@ -241,6 +247,7 @@ class MessageActivity(APIObject):
241247
party_id: APINullable[:class:`str`]
242248
party_id from a Rich Presence event
243249
"""
250+
244251
type: MessageActivityType
245252
party_id: APINullable[str] = MISSING
246253

@@ -317,6 +324,7 @@ class UserMessage(APIObject, GuildProperty, ChannelProperty):
317324
sticker_items: APINullable[List[:class:`~pincer.objects.message.sticker.StickerItem`]]
318325
Sent if the message contains stickers
319326
"""
327+
320328
# noqa: E501
321329

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

362+
@classmethod
363+
async def from_id(
364+
cls, client: Client, _id: Snowflake, channel_id: Snowflake
365+
) -> UserMessage:
366+
"""|coro|
367+
368+
Creates a UserMessage object
369+
It is recommended to use the ``get_message`` function from
370+
:class:`~pincer.client.Client` most of the time.
371+
372+
Parameters
373+
----------
374+
client : :class:`~pincer.client.Client`
375+
Client object to use the HTTP class of.
376+
_id: :class:`~pincer.utils.snowflake.Snowflake`
377+
ID of the message that is wanted.
378+
channel_id : int
379+
ID of the channel the message is in.
380+
381+
Returns
382+
-------
383+
:class:`~pincer.objects.message.user_message.UserMessage`
384+
The message object.
385+
"""
386+
msg = await client.http.get(f"channels/{channel_id}/messages/{_id}")
387+
return cls.from_dict(construct_client_dict(client, msg))
388+
354389
def __str__(self):
355390
return self.content
356391

@@ -367,7 +402,7 @@ async def get_most_recent(self):
367402
self._client,
368403
await self._http.get(
369404
f"/channels/{self.channel_id}/messages/{self.id}"
370-
)
405+
),
371406
)
372407
)
373408

@@ -483,7 +518,7 @@ async def edit(
483518
flags: int = None,
484519
allowed_mentions: AllowedMentions = None,
485520
attachments: List[Attachment] = None,
486-
components: List[MessageComponent] = None
521+
components: List[MessageComponent] = None,
487522
):
488523
"""|coro|
489524
@@ -533,8 +568,7 @@ def set_if_not_none(value: Any, name: str):
533568
set_if_not_none(components, "components")
534569

535570
await self._http.patch(
536-
f"/channels/{self.channel_id}/messages/{self.id}",
537-
data=data
571+
f"/channels/{self.channel_id}/messages/{self.id}", data=data
538572
)
539573

540574
async def delete(self):

pincer/utils/conversion.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
if TYPE_CHECKING:
1212
from ..client import Client
13-
from typing import Any, Callable, Dict, List, Optional, Set, Union
13+
from typing import Any, Callable, Dict, List, Optional, Set, Union, Tuple
1414

1515

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

3131

32-
def remove_none(obj: Union[List, Dict, Set]) -> Union[List, Dict, Set]:
32+
def remove_none(obj: Union[List, Dict, Set, Tuple]) -> Union[List, Dict, Set, Tuple]:
3333
"""
3434
Removes all ``None`` values from a list, dict or set.
3535
3636
Parameters
3737
----------
38-
obj : Union[List, Dict, Set]
39-
The list, dict or set to remove ``None`` values from.
38+
obj : Union[List, Dict, Set, Tuple]
39+
The list, dict, set or tuple to remove ``None`` values from.
4040
4141
Returns
4242
-------
43-
Union[List, Dict, Set]
44-
The list, dict or set without ``None`` values.
43+
Union[List, Dict, Set, Tuple]
44+
The list, dict, set or tuple, without ``None`` values.
4545
"""
4646
if isinstance(obj, list):
4747
return [i for i in obj if i is not None]
48+
elif isinstance(obj, tuple):
49+
return tuple(i for i in obj if i is not None)
4850
elif isinstance(obj, set):
4951
return obj - {None}
5052
elif isinstance(obj, dict):

0 commit comments

Comments
 (0)