Skip to content

Sourcery refactored developer branch #69

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: developer
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions discord/__main__.py
Original file line number Diff line number Diff line change
@@ -42,8 +42,9 @@ def show_version():
version_info = discord.version_info
entries.append('- discord.py-message-components v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(version_info))
if version_info.releaselevel != 'final':
version = importlib_metadata.version('discord.py-message-components')
if version:
if version := importlib_metadata.version(
'discord.py-message-components'
):
Comment on lines -45 to +47
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function show_version refactored with the following changes:

entries.append(' - discord.py.message-components metadata: v{0}'.format(version))

entries.append('- aiohttp v{0.__version__}'.format(aiohttp))
@@ -177,7 +178,7 @@ async def cog_after_invoke(self, ctx):
}

# NUL (0) and 1-31 are disallowed
_base_table.update((chr(i), None) for i in range(32))
_base_table |= ((chr(i), None) for i in range(32))
Comment on lines -180 to +181
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 180-180 refactored with the following changes:


translation_table = str.maketrans(_base_table)

@@ -206,7 +207,7 @@ def newbot(parser, args):
try:
new_directory.mkdir(exist_ok=True, parents=True)
except OSError as exc:
parser.error('could not create our bot directory ({})'.format(exc))
parser.error(f'could not create our bot directory ({exc})')
Comment on lines -209 to +210
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function newbot refactored with the following changes:


cogs = new_directory / 'cogs'

@@ -215,27 +216,27 @@ def newbot(parser, args):
init = cogs / '__init__.py'
init.touch()
except OSError as exc:
print('warning: could not create cogs directory ({})'.format(exc))
print(f'warning: could not create cogs directory ({exc})')

try:
with open(str(new_directory / 'config.py'), 'w', encoding='utf-8') as fp:
fp.write('token = "place your token here"\ncogs = []\n')
except OSError as exc:
parser.error('could not create config file ({})'.format(exc))
parser.error(f'could not create config file ({exc})')

try:
with open(str(new_directory / 'bot.py'), 'w', encoding='utf-8') as fp:
base = 'Bot' if not args.sharded else 'AutoShardedBot'
fp.write(bot_template.format(base=base, prefix=args.prefix))
except OSError as exc:
parser.error('could not create bot file ({})'.format(exc))
parser.error(f'could not create bot file ({exc})')

if not args.no_git:
try:
with open(str(new_directory / '.gitignore'), 'w', encoding='utf-8') as fp:
fp.write(gitignore_template)
except OSError as exc:
print('warning: could not create .gitignore file ({})'.format(exc))
print(f'warning: could not create .gitignore file ({exc})')

print('successfully made bot at', new_directory)

@@ -245,7 +246,7 @@ def newcog(parser, args):
try:
cog_dir.mkdir(exist_ok=True)
except OSError as exc:
print('warning: could not create cogs directory ({})'.format(exc))
print(f'warning: could not create cogs directory ({exc})')
Comment on lines -248 to +249
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function newcog refactored with the following changes:


directory = cog_dir / to_path(parser, args.name)
directory = directory.with_suffix('.py')
@@ -264,12 +265,12 @@ def newcog(parser, args):
name = name.title()

if args.display_name:
attrs += ', name="{}"'.format(args.display_name)
attrs += f', name="{args.display_name}"'
if args.hide_commands:
attrs += ', command_attrs=dict(hidden=True)'
fp.write(cog_template.format(name=name, extra=extra, attrs=attrs))
except OSError as exc:
parser.error('could not create cog file ({})'.format(exc))
parser.error(f'could not create cog file ({exc})')
else:
print('successfully made cog at', directory)

54 changes: 23 additions & 31 deletions discord/abc.py
Original file line number Diff line number Diff line change
@@ -147,19 +147,19 @@ def mention(self):

@classmethod
def __subclasshook__(cls, C):
if cls is User:
if Snowflake.__subclasshook__(C) is NotImplemented:
return NotImplemented
if cls is not User:
return NotImplemented
if Snowflake.__subclasshook__(C) is NotImplemented:
return NotImplemented

mro = C.__mro__
for attr in ('display_name', 'mention', 'name', 'avatar', 'discriminator', 'bot'):
for base in mro:
if attr in base.__dict__:
break
else:
return NotImplemented
return True
return NotImplemented
mro = C.__mro__
for attr in ('display_name', 'mention', 'name', 'avatar', 'discriminator', 'bot'):
for base in mro:
if attr in base.__dict__:
break
else:
return NotImplemented
return True
Comment on lines -150 to +162
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function User.__subclasshook__ refactored with the following changes:



class PrivateChannel(metaclass=abc.ABCMeta):
@@ -186,10 +186,7 @@ def __subclasshook__(cls, C):
return NotImplemented

mro = C.__mro__
for base in mro:
if 'me' in base.__dict__:
return True
return NotImplemented
return next((True for base in mro if 'me' in base.__dict__), NotImplemented)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function PrivateChannel.__subclasshook__ refactored with the following changes:

  • Use the built-in function next instead of a for-loop (use-next)

return NotImplemented


@@ -324,14 +321,10 @@ async def _edit(self, options, reason):
payload = {
'allow': allow.value,
'deny': deny.value,
'id': target.id
'id': target.id,
'type': 'role' if isinstance(target, Role) else 'member',
}

if isinstance(target, Role):
payload['type'] = 'role'
else:
payload['type'] = 'member'
Comment on lines -327 to -333
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function GuildChannel._edit refactored with the following changes:


perms.append(payload)
options['permission_overwrites'] = perms

@@ -356,7 +349,9 @@ def _fill_overwrites(self, data):
for index, overridden in enumerate(data.get('permission_overwrites', [])):
overridden_type = try_enum(PermissionType, overridden.pop('type'))
if not isinstance(overridden_type, PermissionType):
raise AttributeError('Type type should be 0 - member, or 1 - role not %s' % overridden_type)
raise AttributeError(
f'Type type should be 0 - member, or 1 - role not {overridden_type}'
)
Comment on lines -359 to +354
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function GuildChannel._fill_overwrites refactored with the following changes:

This removes the following comments ( why? ):

# do the swap

overridden_id = int(overridden.pop('id'))
self._overwrites.append(_Overwrites(id=overridden_id, type=overridden_type.name, **overridden))

@@ -371,9 +366,7 @@ def _fill_overwrites(self, data):
# swap it to be the first one.
everyone_index = index

# do the swap
tmp = self._overwrites
if tmp:
if tmp := self._overwrites:
tmp[everyone_index], tmp[0] = tmp[0], tmp[everyone_index]

@property
@@ -395,7 +388,7 @@ def changed_roles(self):
@property
def mention(self):
""":class:`str`: The string that allows you to mention the channel."""
return '<#%s>' % self.id
return f'<#{self.id}>'
Comment on lines -398 to +391
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function GuildChannel.mention refactored with the following changes:


@property
def jump_url(self):
@@ -694,15 +687,14 @@ async def set_permissions(
raise InvalidArgument(f'target parameter must be either Member or Role, not {target.__class__.__name__}')

if isinstance(overwrite, _Undefined):
if len(permissions) == 0:
if not permissions:
raise InvalidArgument('No overwrite provided.')
try:
overwrite = PermissionOverwrite(**permissions)
except (ValueError, TypeError):
raise InvalidArgument('Invalid permissions given to keyword arguments.')
else:
if len(permissions) > 0:
raise InvalidArgument('Cannot mix overwrite and keyword arguments.')
elif permissions:
raise InvalidArgument('Cannot mix overwrite and keyword arguments.')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function GuildChannel.set_permissions refactored with the following changes:


# TODO: wait for event

24 changes: 8 additions & 16 deletions discord/activity.py
Original file line number Diff line number Diff line change
@@ -194,10 +194,7 @@ def __init__(self, **kwargs):
self.session_id = kwargs.pop('session_id', None)
self.type = try_enum(ActivityType, kwargs.pop('type', -1))
emoji = kwargs.pop('emoji', None)
if emoji is not None:
self.emoji = PartialEmoji.from_dict(emoji)
else:
self.emoji = None
self.emoji = PartialEmoji.from_dict(emoji) if emoji is not None else None
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Activity.__init__ refactored with the following changes:


def __repr__(self):
attrs = (
@@ -210,7 +207,7 @@ def __repr__(self):
'emoji',
)
mapped = ' '.join('%s=%r' % (attr, getattr(self, attr)) for attr in attrs)
return '<Activity %s>' % mapped
return f'<Activity {mapped}>'
Comment on lines -213 to +210
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Activity.__repr__ refactored with the following changes:


def to_dict(self):
ret = {}
@@ -338,9 +335,9 @@ def _extract_timestamp(self, data, key):
try:
dt = data[key]
except KeyError:
setattr(self, '_' + key, 0)
setattr(self, f'_{key}', 0)
else:
setattr(self, '_' + key, dt.timestamp() * 1000.0)
setattr(self, f'_{key}', dt.timestamp() * 1000.0)
Comment on lines -341 to +340
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Game._extract_timestamp refactored with the following changes:


@property
def type(self):
@@ -632,7 +629,7 @@ def album_cover_url(self):
if large_image[:8] != 'spotify:':
return ''
album_image_id = large_image[8:]
return 'https://i.scdn.co/image/' + album_image_id
return f'https://i.scdn.co/image/{album_image_id}'
Comment on lines -635 to +632
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Spotify.album_cover_url refactored with the following changes:


@property
def track_id(self):
@@ -751,12 +748,9 @@ def __hash__(self):
return hash((self.name, str(self.emoji)))

def __str__(self):
if self.emoji:
if self.name:
return '%s %s' % (self.emoji, self.name)
return str(self.emoji)
else:
if not self.emoji:
return str(self.name)
return f'{self.emoji} {self.name}' if self.name else str(self.emoji)
Comment on lines -754 to +753
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function CustomActivity.__str__ refactored with the following changes:


def __repr__(self):
return '<CustomActivity name={0.name!r} emoji={0.emoji!r}>'.format(self)
@@ -779,9 +773,7 @@ def create_activity(data):
else:
return CustomActivity(name=name, **data)
elif game_type is ActivityType.streaming:
if 'url' in data:
return Streaming(**data)
return Activity(**data)
return Streaming(**data) if 'url' in data else Activity(**data)
Comment on lines -782 to +776
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function create_activity refactored with the following changes:

elif game_type is ActivityType.listening and 'sync_id' in data and 'session_id' in data:
return Spotify(**data)
return Activity(**data)
Loading