Skip to content
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

Sourcery refactored main branch #68

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
28 changes: 15 additions & 13 deletions discord/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,16 @@


def show_version():
entries = []
entries = [
'- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(
sys.version_info
)
]

entries.append('- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(sys.version_info))
version_info = discord.version_info
entries.append('- discord.py v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(version_info))
if version_info.releaselevel != 'final':
pkg = pkg_resources.get_distribution('discord.py')
if pkg:
if pkg := pkg_resources.get_distribution('discord.py'):
Comment on lines -38 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 pkg_resources: v{0}'.format(pkg.version))

entries.append('- aiohttp v{0.__version__}'.format(aiohttp))
Expand Down Expand Up @@ -176,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 -179 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 179-179 refactored with the following changes:


translation_table = str.maketrans(_base_table)

Expand Down Expand Up @@ -205,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 -208 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'

Expand All @@ -214,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)

Expand All @@ -244,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 -247 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')
Expand All @@ -263,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)

Expand Down
147 changes: 76 additions & 71 deletions discord/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,19 +124,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 -127 to +139
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):
"""An ABC that details the common operations on a private Discord channel.
Expand All @@ -162,10 +162,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

class _Overwrites:
Expand Down Expand Up @@ -298,14 +295,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 -301 to -307
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

Expand All @@ -330,7 +323,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 overridden_type:
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 -333 to +328
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))

Expand All @@ -345,9 +340,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
Expand All @@ -369,7 +362,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 -372 to +365
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 created_at(self):
Expand Down Expand Up @@ -654,15 +647,14 @@ async def set_permissions(self, target, *, overwrite=_undefined, reason=None, **
raise InvalidArgument('target parameter must be either Member or Role')

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

Expand Down Expand Up @@ -1049,14 +1041,13 @@ async def send(self, content=None, *, tts=False, embed=None, embeds=None, compon
_components.extend(ActionRow(*[obj for obj in component if isinstance(obj, (Button, SelectMenu))]).to_dict())
components = _components

if allowed_mentions is not None:
if state.allowed_mentions is not None:
allowed_mentions = state.allowed_mentions.merge(allowed_mentions).to_dict()
else:
allowed_mentions = allowed_mentions.to_dict()
else:
if allowed_mentions is None:
allowed_mentions = state.allowed_mentions and state.allowed_mentions.to_dict()

elif state.allowed_mentions is not None:
allowed_mentions = state.allowed_mentions.merge(allowed_mentions).to_dict()
else:
allowed_mentions = allowed_mentions.to_dict()
Comment on lines -1052 to +1050
Copy link
Author

Choose a reason for hiding this comment

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

Function Messageable.send refactored with the following changes:

if mention_author is not None:
allowed_mentions = allowed_mentions or AllowedMentions().to_dict()
allowed_mentions['replied_user'] = bool(mention_author)
Expand Down Expand Up @@ -1085,22 +1076,37 @@ async def send(self, content=None, *, tts=False, embed=None, embeds=None, compon
raise InvalidArgument('file parameter must be File')

try:
if hidden is not None:
data = await state.http.send_interaction_response(use_webhook=use_webhook,
interaction_id=interaction_id,
token=interaction_token,
application_id=application_id,
deferred=deferred,
files=[file], allowed_mentions=allowed_mentions,
content=content, tts=tts, embeds=embeds,
components=components,
nonce=nonce, message_reference=reference,
flags=64 if hidden is True else None,
followup=followup)
else:
data = await state.http.send_files(channel.id, files=[file], allowed_mentions=allowed_mentions,
content=content, tts=tts, embeds=embeds, components=components,
nonce=nonce, message_reference=reference)
data = (
await state.http.send_interaction_response(
use_webhook=use_webhook,
interaction_id=interaction_id,
token=interaction_token,
application_id=application_id,
deferred=deferred,
files=[file],
allowed_mentions=allowed_mentions,
content=content,
tts=tts,
embeds=embeds,
components=components,
nonce=nonce,
message_reference=reference,
flags=64 if hidden is True else None,
followup=followup,
)
if hidden is not None
else await state.http.send_files(
channel.id,
files=[file],
allowed_mentions=allowed_mentions,
content=content,
tts=tts,
embeds=embeds,
components=components,
nonce=nonce,
message_reference=reference,
)
)
finally:
file.close()

Expand Down Expand Up @@ -1130,28 +1136,27 @@ async def send(self, content=None, *, tts=False, embed=None, embeds=None, compon
finally:
for f in files:
f.close()
elif hidden is not None:
data = await state.http.send_interaction_response(use_webhook=use_webhook,
interaction_id=interaction_id,
token=interaction_token,
application_id=application_id,
deferred=deferred, allowed_mentions=allowed_mentions,
content=content, tts=tts, embeds=embeds,
components=components,
nonce=nonce, message_reference=reference,
flags=64 if hidden is True else None,
followup=followup)
else:
if hidden is not None:
data = await state.http.send_interaction_response(use_webhook=use_webhook,
interaction_id=interaction_id,
token=interaction_token,
application_id=application_id,
deferred=deferred, allowed_mentions=allowed_mentions,
content=content, tts=tts, embeds=embeds,
components=components,
nonce=nonce, message_reference=reference,
flags=64 if hidden is True else None,
followup=followup)
else:
data = await state.http.send_message(channel.id, content, tts=tts, embeds=embeds, components=components,
nonce=nonce, allowed_mentions=allowed_mentions,
message_reference=reference)
if not hidden is True:
if not isinstance(data, dict) and not hidden is None:
data = await state.http.send_message(channel.id, content, tts=tts, embeds=embeds, components=components,
nonce=nonce, allowed_mentions=allowed_mentions,
message_reference=reference)
if hidden is not True:
if not isinstance(data, dict) and hidden is not None:
"""Thanks Discord that they dont return the message when we send the interaction callback"""
data = await state.http.get_original_interaction_response(application_id=application_id, interaction_token=interaction_token)
ret = state.create_message(channel=channel, data=data)
if (delete_after is not None) and (not hidden is True):
if delete_after is not None and hidden is not True:
await ret.delete(delay=delete_after)
return ret

Expand Down
24 changes: 8 additions & 16 deletions discord/activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,10 +189,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 = (
Expand All @@ -205,7 +202,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 -208 to +205
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 = {}
Expand Down Expand Up @@ -332,9 +329,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 -335 to +334
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):
Expand Down Expand Up @@ -624,7 +621,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 -627 to +624
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):
Expand Down Expand Up @@ -737,12 +734,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 -740 to +739
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)
Expand All @@ -765,9 +759,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 -768 to +762
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