From e91675291e5b5a4697f869a7a01c96aa5fa3ffea Mon Sep 17 00:00:00 2001 From: Rapptz Date: Sun, 12 Jan 2020 03:27:48 -0500 Subject: [PATCH] Fix bug preventing movement of channels when there are gaps in position The original code was too aggressive in ensuring that the channel positions are correct and within bounds. Unfortunately, for Discord this number is merely a guess and there can be gaps that cause the position number to be greater than the number of channels currently in that sorting bucket. One such example of this is when a channel is deleted and created. When this happens, the positions are not updated (presumably because Discord considers this to be too expensive). Sadly this means that if a user were to create a channel, delete a channel, and then create another one then there will be gaps in the position sequence. More concretely, consider the following example: Channels with position [0, 1, 2, 3, 4]. A new channel is created so it inherits the maximum position giving us [0, 1, 2, 3, 4, 5]. We delete a channel that's smaller than the maximum so our list now looks like [0, 1, 2, 4, 5]. Next time we create a channel we will further increment the gap, giving us [0, 1, 2, 4, 5, 6]. If a user would want to move the channel with position 4 to be after position 6 (so in this case that value would 7) then the library would erroneously raise an error because it assumed too much about the data integrity. Luckily, the library upon actually doing the request fixes the channel positions so everything goes back to normal like it was intended. That is to say, [0, 1, 2, 3, 4, 5]. --- discord/abc.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/discord/abc.py b/discord/abc.py index dc69ff27b..983c323f2 100644 --- a/discord/abc.py +++ b/discord/abc.py @@ -202,9 +202,6 @@ class GuildChannel: bucket = self._sorting_bucket channels = [c for c in self.guild.channels if c._sorting_bucket == bucket] - if position >= len(channels): - raise InvalidArgument('Channel position cannot be greater than {}'.format(len(channels) - 1)) - channels.sort(key=lambda c: c.position) try: @@ -214,8 +211,9 @@ class GuildChannel: # not there somehow lol return else: + index = next((i for i, c in enumerate(channels) if c.position >= position), -1) # add ourselves at our designated position - channels.insert(position, self) + channels.insert(index, self) payload = [] for index, c in enumerate(channels): @@ -259,7 +257,7 @@ class GuildChannel: options['permission_overwrites'] = [c._asdict() for c in category._overwrites] else: await self._move(position, parent_id=parent_id, lock_permissions=lock_permissions, reason=reason) - + overwrites = options.get('overwrites', None) if overwrites: perms = []