Skip to content

Commit

Permalink
Merge branch 'master' into patch-1
Browse files Browse the repository at this point in the history
  • Loading branch information
Lulalaby authored May 30, 2023
2 parents b59a6eb + e3ee572 commit 37a8bd2
Show file tree
Hide file tree
Showing 25 changed files with 299 additions and 121 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/todo.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ jobs:
steps:
- uses: actions/checkout@v3
- name: Run tdg-github-action
uses: ribtoks/[email protected].6-beta
uses: ribtoks/[email protected].7-beta
with:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }}
Expand Down
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ These changes are available on the `master` branch, but have not yet been releas
`BridgeCommandGroup.walk_commands`) to cycle through all bridge commands and their
children/subcommands.
([#1867](https://github.com/Pycord-Development/pycord/pull/1867))
- Added support for usernames and modified multiple methods accordingly.
([#2042](https://github.com/Pycord-Development/pycord/pull/2042))
- Added `icon` and `unicode_emoji` to `Guild.create_role`.
([#2086](https://github.com/Pycord-Development/pycord/pull/2086))

### Changed

Expand All @@ -74,6 +78,8 @@ These changes are available on the `master` branch, but have not yet been releas
- Embed attribues like author, footer, etc now return `None` when not set, and return
their respective classes when set.
([#2063](https://github.com/Pycord-Development/pycord/pull/2063))
- `default_avatar` behavior changes depending on the user's username migration status
([#2087](https://github.com/Pycord-Development/pycord/pull/2087))

### Removed

Expand Down Expand Up @@ -111,6 +117,14 @@ These changes are available on the `master` branch, but have not yet been releas
listeners. ([#2044](https://github.com/Pycord-Development/pycord/pull/2044))
- Fixed unloading of cogs having bridge commands.
([#2048](https://github.com/Pycord-Development/pycord/pull/2048))
- Fixed the Slash command syncronization method `indiviual`.
([#1925](https://github.com/Pycord-Development/pycord/pull/1925))
- Fixed an issue that occurred when `webhooks_update` event payload channel ID was
`None`. ([#2078](https://github.com/Pycord-Development/pycord/pull/2078))
- Fixed major TypeError when an AuditLogEntry has no user.
([#2079](https://github.com/Pycord-Development/pycord/pull/2079))
- Fixed `HTTPException` when trying to create a forum thread with files.
([#2075](https://github.com/Pycord-Development/pycord/pull/2075))

## [2.4.1] - 2023-03-20

Expand Down
9 changes: 9 additions & 0 deletions discord/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,14 @@ class User(Snowflake, Protocol):
The user's username.
discriminator: :class:`str`
The user's discriminator.
.. note::
If the user has migrated to the new username system, this will always be "0".
global_name: :class:`str`
The user's global name.
.. versionadded:: 2.5
avatar: :class:`~discord.Asset`
The avatar asset the user has.
bot: :class:`bool`
Expand All @@ -225,6 +233,7 @@ class User(Snowflake, Protocol):

name: str
discriminator: str
global_name: str | None
avatar: Asset
bot: bool

Expand Down
2 changes: 1 addition & 1 deletion discord/audit_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ class AuditLogEntry(Hashable):
-----------
action: :class:`AuditLogAction`
The action that was done.
user: :class:`abc.User`
user: Optional[:class:`abc.User`]
The user who initiated this action. Usually a :class:`Member`\, unless gone
then it's a :class:`User`.
id: :class:`int`
Expand Down
37 changes: 28 additions & 9 deletions discord/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -501,21 +501,24 @@ def _register(
)

def register(
method: Literal["bulk", "upsert", "delete", "edit"], *args, **kwargs
method: Literal["bulk", "upsert", "delete", "edit"],
*args,
cmd_name: str = None,
guild_id: int | None = None,
**kwargs,
):
if kwargs.pop("_log", True):
if method == "bulk":
_log.debug(
f"Bulk updating commands {[c['name'] for c in args[0]]} for"
f" guild {guild_id}"
)
# TODO: Find where "cmd" is defined
elif method == "upsert":
_log.debug(f"Creating command {cmd['name']} for guild {guild_id}") # type: ignore
_log.debug(f"Creating command {cmd_name} for guild {guild_id}") # type: ignore
elif method == "edit":
_log.debug(f"Editing command {cmd['name']} for guild {guild_id}") # type: ignore
_log.debug(f"Editing command {cmd_name} for guild {guild_id}") # type: ignore
elif method == "delete":
_log.debug(f"Deleting command {cmd['name']} for guild {guild_id}") # type: ignore
_log.debug(f"Deleting command {cmd_name} for guild {guild_id}") # type: ignore
return _register(method, *args, **kwargs)

pending_actions = []
Expand Down Expand Up @@ -602,15 +605,31 @@ def register(
registered = []
for cmd in filtered_no_action:
if cmd["action"] == "delete":
await register("delete", cmd["command"])
await register(
"delete",
cmd["id"],
cmd_name=cmd["command"].name,
guild_id=guild_id,
)
continue
if cmd["action"] == "edit":
registered.append(
await register("edit", cmd["id"], cmd["command"].to_dict())
await register(
"edit",
cmd["id"],
cmd["command"].to_dict(),
cmd_name=cmd["command"].name,
guild_id=guild_id,
)
)
elif cmd["action"] == "upsert":
registered.append(
await register("upsert", cmd["command"].to_dict())
await register(
"upsert",
cmd["command"].to_dict(),
cmd_name=cmd["command"].name,
guild_id=guild_id,
)
)
else:
raise ValueError(f"Unknown action: {cmd['action']}")
Expand All @@ -628,7 +647,7 @@ def register(
)
else:
data = [cmd.to_dict() for cmd in pending]
registered = await register("bulk", data)
registered = await register("bulk", data, guild_id=guild_id)

for i in registered:
cmd = get(
Expand Down
49 changes: 13 additions & 36 deletions discord/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -1274,53 +1274,25 @@ async def create_thread(
if file is not None and files is not None:
raise InvalidArgument("cannot pass both file and files parameter to send()")

if file is not None:
if not isinstance(file, File):
raise InvalidArgument("file parameter must be File")

try:
data = await state.http.send_files(
self.id,
files=[file],
allowed_mentions=allowed_mentions,
content=message_content,
embed=embed,
embeds=embeds,
nonce=nonce,
stickers=stickers,
components=components,
)
finally:
file.close()

elif files is not None:
if files is not None:
if len(files) > 10:
raise InvalidArgument(
"files parameter must be a list of up to 10 elements"
)
elif not all(isinstance(file, File) for file in files):
raise InvalidArgument("files parameter must be a list of File")

try:
data = await state.http.send_files(
self.id,
files=files,
content=message_content,
embed=embed,
embeds=embeds,
nonce=nonce,
allowed_mentions=allowed_mentions,
stickers=stickers,
components=components,
)
finally:
for f in files:
f.close()
else:
if file is not None:
if not isinstance(file, File):
raise InvalidArgument("file parameter must be File")
files = [file]

try:
data = await state.http.start_forum_thread(
self.id,
content=message_content,
name=name,
files=files,
embed=embed,
embeds=embeds,
nonce=nonce,
Expand All @@ -1333,6 +1305,11 @@ async def create_thread(
applied_tags=applied_tags,
reason=reason,
)
finally:
if files is not None:
for f in files:
f.close()

ret = Thread(guild=self.guild, state=self._state, data=data)
msg = ret.get_partial_message(data["last_message_id"])
if view:
Expand Down
4 changes: 3 additions & 1 deletion discord/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1051,7 +1051,9 @@ def get_all_members(self) -> Generator[Member, None, None]:
yield from guild.members

async def get_or_fetch_user(self, id: int, /) -> User | None:
"""Looks up a user in the user cache or fetches if not found.
"""|coro|
Looks up a user in the user cache or fetches if not found.
Parameters
----------
Expand Down
4 changes: 2 additions & 2 deletions discord/embeds.py
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ def __init__(
url: Any | None = None,
description: Any | None = None,
timestamp: datetime.datetime | None = None,
fields: list[EmbedField] = [],
fields: list[EmbedField] | None = None,
author: EmbedAuthor | None = None,
footer: EmbedFooter | None = None,
image: str | None = None,
Expand All @@ -374,7 +374,7 @@ def __init__(
if timestamp:
self.timestamp = timestamp

self._fields: list[EmbedField] = fields
self._fields: list[EmbedField] = fields if fields is not None else []

if author:
self.set_author(**author.to_dict())
Expand Down
15 changes: 0 additions & 15 deletions discord/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
"VerificationLevel",
"ContentFilter",
"Status",
"DefaultAvatar",
"AuditLogAction",
"AuditLogActionCategory",
"UserFlags",
Expand Down Expand Up @@ -354,20 +353,6 @@ def __str__(self):
return self.value


class DefaultAvatar(Enum):
"""Default avatar"""

blurple = 0
grey = 1
gray = 1
green = 2
orange = 3
red = 4

def __str__(self):
return self.name


class NotificationLevel(Enum, comparable=True):
"""Notification level"""

Expand Down
12 changes: 6 additions & 6 deletions discord/ext/commands/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,11 +199,11 @@ async def query_member_named(self, guild, argument):
return discord.utils.get(
members, name=username, discriminator=discriminator
)
else:
members = await guild.query_members(argument, limit=100, cache=cache)
return discord.utils.find(
lambda m: m.name == argument or m.nick == argument, members
)
members = await guild.query_members(argument, limit=100, cache=cache)
return discord.utils.find(
lambda m: argument in (m.nick, m.name, m.global_name),
members,
)

async def query_member_by_id(self, bot, guild, user_id):
ws = bot._get_websocket(shard_id=guild.shard_id)
Expand Down Expand Up @@ -320,7 +320,7 @@ async def convert(self, ctx: Context, argument: str) -> discord.User:
if result is not None:
return result

predicate = lambda u: u.name == arg
predicate = lambda u: arg in (u.name, u.global_name)
result = discord.utils.find(predicate, state._users.values())

if result is None:
Expand Down
29 changes: 25 additions & 4 deletions discord/guild.py
Original file line number Diff line number Diff line change
Expand Up @@ -1068,10 +1068,7 @@ def get_member_named(self, name: str, /) -> Member | None:
if result is not None:
return result

def pred(m: Member) -> bool:
return m.nick == name or m.name == name

return utils.find(pred, members)
return utils.find(lambda m: name in (m.nick, m.name, m.global_name), members)

def _create_channel(
self,
Expand Down Expand Up @@ -2806,6 +2803,8 @@ async def create_role(
colour: Colour | int = ...,
hoist: bool = ...,
mentionable: bool = ...,
icon: bytes | None = MISSING,
unicode_emoji: str | None = MISSING,
) -> Role:
...

Expand All @@ -2819,6 +2818,8 @@ async def create_role(
color: Colour | int = ...,
hoist: bool = ...,
mentionable: bool = ...,
icon: bytes | None = ...,
unicode_emoji: str | None = ...,
) -> Role:
...

Expand All @@ -2832,6 +2833,8 @@ async def create_role(
hoist: bool = MISSING,
mentionable: bool = MISSING,
reason: str | None = None,
icon: bytes | None = MISSING,
unicode_emoji: str | None = MISSING,
) -> Role:
"""|coro|
Expand Down Expand Up @@ -2862,6 +2865,13 @@ async def create_role(
Defaults to ``False``.
reason: Optional[:class:`str`]
The reason for creating this role. Shows up on the audit log.
icon: Optional[:class:`bytes`]
A :term:`py:bytes-like object` representing the icon. Only PNG/JPEG/WebP is supported.
If this argument is passed, ``unicode_emoji`` is set to None.
Only available to guilds that contain ``ROLE_ICONS`` in :attr:`Guild.features`.
unicode_emoji: Optional[:class:`str`]
The role's unicode emoji. If this argument is passed, ``icon`` is set to None.
Only available to guilds that contain ``ROLE_ICONS`` in :attr:`Guild.features`.
Returns
-------
Expand Down Expand Up @@ -2898,6 +2908,17 @@ async def create_role(
if name is not MISSING:
fields["name"] = name

if icon is not MISSING:
if icon is None:
fields["icon"] = None
else:
fields["icon"] = _bytes_to_base64_data(icon)
fields["unicode_emoji"] = None

if unicode_emoji is not MISSING:
fields["unicode_emoji"] = unicode_emoji
fields["icon"] = None

data = await self._state.http.create_role(self.id, reason=reason, **fields)
role = Role(guild=self, data=data, state=self._state)

Expand Down
Loading

0 comments on commit 37a8bd2

Please sign in to comment.