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

[V3] Code standards (black code format pass) #1650

Merged
merged 2 commits into from
May 14, 2018
Merged
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
5 changes: 5 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
:target: https://www.patreon.com/Red_Devs
:alt: Patreon

.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/ambv/black
:alt: Code style: black


********************
Red - Discord Bot v3
********************
Expand Down
8 changes: 5 additions & 3 deletions redbot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
# Let's do all the dumb version checking in one place.

if discord.version_info.major < 1:
print("You are not running the rewritten version of discord.py.\n\n"
"In order to use Red v3 you MUST be running d.py version"
" >= 1.0.0.")
print(
"You are not running the rewritten version of discord.py.\n\n"
"In order to use Red v3 you MUST be running d.py version"
" >= 1.0.0."
)
sys.exit(1)
51 changes: 27 additions & 24 deletions redbot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,24 +40,25 @@ def init_loggers(cli_flags):
logger = logging.getLogger("red")

red_format = logging.Formatter(
'%(asctime)s %(levelname)s %(module)s %(funcName)s %(lineno)d: '
'%(message)s',
datefmt="[%d/%m/%Y %H:%M]")
"%(asctime)s %(levelname)s %(module)s %(funcName)s %(lineno)d: " "%(message)s",
datefmt="[%d/%m/%Y %H:%M]",
)

stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(red_format)

if cli_flags.debug:
os.environ['PYTHONASYNCIODEBUG'] = '1'
os.environ["PYTHONASYNCIODEBUG"] = "1"
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.WARNING)

from redbot.core.data_manager import core_data_path
logfile_path = core_data_path() / 'red.log'

logfile_path = core_data_path() / "red.log"
fhandler = logging.handlers.RotatingFileHandler(
filename=str(logfile_path), encoding='utf-8', mode='a',
maxBytes=10**7, backupCount=5)
filename=str(logfile_path), encoding="utf-8", mode="a", maxBytes=10 ** 7, backupCount=5
)
fhandler.setFormatter(red_format)

logger.addHandler(fhandler)
Expand All @@ -76,15 +77,17 @@ async def _get_prefix_and_token(red, indict):
:param indict:
:return:
"""
indict['token'] = await red.db.token()
indict['prefix'] = await red.db.prefix()
indict['enable_sentry'] = await red.db.enable_sentry()
indict["token"] = await red.db.token()
indict["prefix"] = await red.db.prefix()
indict["enable_sentry"] = await red.db.enable_sentry()


def list_instances():
if not config_file.exists():
print("No instances have been configured! Configure one "
"using `redbot-setup` before trying to run the bot!")
print(
"No instances have been configured! Configure one "
"using `redbot-setup` before trying to run the bot!"
)
sys.exit(1)
else:
data = JsonIO(config_file)._load_json()
Expand Down Expand Up @@ -118,29 +121,30 @@ def main():
loop = asyncio.get_event_loop()
tmp_data = {}
loop.run_until_complete(_get_prefix_and_token(red, tmp_data))
token = os.environ.get("RED_TOKEN", tmp_data['token'])
prefix = cli_flags.prefix or tmp_data['prefix']
token = os.environ.get("RED_TOKEN", tmp_data["token"])
prefix = cli_flags.prefix or tmp_data["prefix"]
if token is None or not prefix:
if cli_flags.no_prompt is False:
new_token = interactive_config(red, token_set=bool(token),
prefix_set=bool(prefix))
new_token = interactive_config(red, token_set=bool(token), prefix_set=bool(prefix))
if new_token:
token = new_token
else:
log.critical("Token and prefix must be set in order to login.")
sys.exit(1)
loop.run_until_complete(_get_prefix_and_token(red, tmp_data))
if tmp_data['enable_sentry']:
if tmp_data["enable_sentry"]:
red.enable_sentry()
cleanup_tasks = True
try:
loop.run_until_complete(red.start(token, bot=not cli_flags.not_bot))
except discord.LoginFailure:
cleanup_tasks = False # No login happened, no need for this
log.critical("This token doesn't seem to be valid. If it belongs to "
"a user account, remember that the --not-bot flag "
"must be used. For self-bot functionalities instead, "
"--self-bot")
log.critical(
"This token doesn't seem to be valid. If it belongs to "
"a user account, remember that the --not-bot flag "
"must be used. For self-bot functionalities instead, "
"--self-bot"
)
db_token = red.db.token()
if db_token and not cli_flags.no_prompt:
print("\nDo you want to reset the token? (y/n)")
Expand All @@ -159,12 +163,11 @@ def main():
rpc.clean_up()
if cleanup_tasks:
pending = asyncio.Task.all_tasks(loop=red.loop)
gathered = asyncio.gather(
*pending, loop=red.loop, return_exceptions=True)
gathered = asyncio.gather(*pending, loop=red.loop, return_exceptions=True)
gathered.cancel()

sys.exit(red._shutdown_mode.value)


if __name__ == '__main__':
if __name__ == "__main__":
main()
89 changes: 40 additions & 49 deletions redbot/cogs/admin/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,16 @@


class Admin:

def __init__(self, config=Config):
self.conf = config.get_conf(self, 8237492837454039,
force_registration=True)
self.conf = config.get_conf(self, 8237492837454039, force_registration=True)

self.conf.register_global(
serverlocked=False
)
self.conf.register_global(serverlocked=False)

self.conf.register_guild(
announce_ignore=False,
announce_channel=None, # Integer ID
selfroles=[] # List of integer ID's
selfroles=[], # List of integer ID's
Copy link
Member

Choose a reason for hiding this comment

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

Where did this even come from. Is that compliant?

Copy link
Member

Choose a reason for hiding this comment

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

Yes, it's compliant and a style choice.

)

self.__current_announcer = None
Expand All @@ -63,8 +61,7 @@ def __unload(self):
pass

@staticmethod
async def complain(ctx: commands.Context, message: str,
**kwargs):
async def complain(ctx: commands.Context, message: str, **kwargs):
await ctx.send(message.format(**kwargs))

def is_announcing(self) -> bool:
Expand All @@ -78,8 +75,7 @@ def is_announcing(self) -> bool:
return self.__current_announcer.active or False

@staticmethod
def pass_heirarchy_check(ctx: commands.Context,
role: discord.Role) -> bool:
def pass_heirarchy_check(ctx: commands.Context, role: discord.Role) -> bool:
"""
Determines if the bot has a higher role than the given one.
:param ctx:
Expand All @@ -89,8 +85,7 @@ def pass_heirarchy_check(ctx: commands.Context,
return ctx.guild.me.top_role > role

@staticmethod
def pass_user_heirarchy_check(ctx: commands.Context,
role: discord.Role) -> bool:
def pass_user_heirarchy_check(ctx: commands.Context, role: discord.Role) -> bool:
"""
Determines if a user is allowed to add/remove/edit the given role.
:param ctx:
Expand All @@ -99,43 +94,40 @@ def pass_user_heirarchy_check(ctx: commands.Context,
"""
return ctx.author.top_role > role

async def _addrole(self, ctx: commands.Context, member: discord.Member,
role: discord.Role):
async def _addrole(self, ctx: commands.Context, member: discord.Member, role: discord.Role):
try:
await member.add_roles(role)
except discord.Forbidden:
if not self.pass_heirarchy_check(ctx, role):
await self.complain(ctx, HIERARCHY_ISSUE, role=role,
member=member)
await self.complain(ctx, HIERARCHY_ISSUE, role=role, member=member)
else:
await self.complain(ctx, GENERIC_FORBIDDEN)
else:
await ctx.send("I successfully added {role.name} to"
" {member.display_name}".format(
role=role, member=member
))
await ctx.send(
"I successfully added {role.name} to"
" {member.display_name}".format(role=role, member=member)
)

async def _removerole(self, ctx: commands.Context, member: discord.Member,
role: discord.Role):
async def _removerole(self, ctx: commands.Context, member: discord.Member, role: discord.Role):
try:
await member.remove_roles(role)
except discord.Forbidden:
if not self.pass_heirarchy_check(ctx, role):
await self.complain(ctx, HIERARCHY_ISSUE, role=role,
member=member)
await self.complain(ctx, HIERARCHY_ISSUE, role=role, member=member)
else:
await self.complain(ctx, GENERIC_FORBIDDEN)
else:
await ctx.send("I successfully removed {role.name} from"
" {member.display_name}".format(
role=role, member=member
))
await ctx.send(
"I successfully removed {role.name} from"
" {member.display_name}".format(role=role, member=member)
)

@commands.command()
@commands.guild_only()
@checks.admin_or_permissions(manage_roles=True)
async def addrole(self, ctx: commands.Context, rolename: discord.Role, *,
user: MemberDefaultAuthor=None):
async def addrole(
self, ctx: commands.Context, rolename: discord.Role, *, user: MemberDefaultAuthor = None
):
"""
Adds a role to a user. If user is left blank it defaults to the
author of the command.
Expand All @@ -151,8 +143,9 @@ async def addrole(self, ctx: commands.Context, rolename: discord.Role, *,
@commands.command()
@commands.guild_only()
@checks.admin_or_permissions(manage_roles=True)
async def removerole(self, ctx: commands.Context, rolename: discord.Role, *,
user: MemberDefaultAuthor=None):
async def removerole(
self, ctx: commands.Context, rolename: discord.Role, *, user: MemberDefaultAuthor = None
):
"""
Removes a role from a user. If user is left blank it defaults to the
author of the command.
Expand All @@ -173,9 +166,10 @@ async def editrole(self, ctx: commands.Context):
if ctx.invoked_subcommand is None:
await ctx.send_help()

@editrole.command(name="colour", aliases=["color", ])
async def editrole_colour(self, ctx: commands.Context, role: discord.Role,
value: discord.Colour):
@editrole.command(name="colour", aliases=["color"])
async def editrole_colour(
self, ctx: commands.Context, role: discord.Role, value: discord.Colour
):
"""Edits a role's colour

Use double quotes if the role contains spaces.
Expand All @@ -185,8 +179,7 @@ async def editrole_colour(self, ctx: commands.Context, role: discord.Role,
!editrole colour \"The Transistor\" #ff0000
!editrole colour Test #ff9900"""
author = ctx.author
reason = "{}({}) changed the colour of role '{}'".format(
author.name, author.id, role.name)
reason = "{}({}) changed the colour of role '{}'".format(author.name, author.id, role.name)

if not self.pass_user_heirarchy_check(ctx, role):
await self.complain(ctx, USER_HIERARCHY_ISSUE)
Expand All @@ -211,7 +204,8 @@ async def edit_role_name(self, ctx: commands.Context, role: discord.Role, *, nam
author = ctx.message.author
old_name = role.name
reason = "{}({}) changed the name of role '{}' to '{}'".format(
author.name, author.id, old_name, name)
author.name, author.id, old_name, name
)

if not self.pass_user_heirarchy_check(ctx, role):
await self.complain(ctx, USER_HIERARCHY_ISSUE)
Expand Down Expand Up @@ -240,8 +234,7 @@ async def announce(self, ctx: commands.Context, *, message: str):
await ctx.send("The announcement has begun.")
else:
prefix = ctx.prefix
await self.complain(ctx, RUNNING_ANNOUNCEMENT,
prefix=prefix)
await self.complain(ctx, RUNNING_ANNOUNCEMENT, prefix=prefix)

@announce.command(name="cancel")
@checks.is_owner()
Expand All @@ -259,22 +252,20 @@ async def announce_cancel(self, ctx):
@announce.command(name="channel")
@commands.guild_only()
@checks.guildowner_or_permissions(administrator=True)
async def announce_channel(self, ctx, *, channel: discord.TextChannel=None):
async def announce_channel(self, ctx, *, channel: discord.TextChannel = None):
"""
Changes the channel on which the bot makes announcements.
"""
if channel is None:
channel = ctx.channel
await self.conf.guild(ctx.guild).announce_channel.set(channel.id)

await ctx.send("The announcement channel has been set to {}".format(
channel.mention
))
await ctx.send("The announcement channel has been set to {}".format(channel.mention))

@announce.command(name="ignore")
@commands.guild_only()
@checks.guildowner_or_permissions(administrator=True)
async def announce_ignore(self, ctx, *, guild: discord.Guild=None):
async def announce_ignore(self, ctx, *, guild: discord.Guild = None):
Copy link
Contributor

Choose a reason for hiding this comment

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

Why does it add spaces around the = operator here and not below?

"""
Toggles whether the announcements will ignore the given server.
Defaults to the current server if none is provided.
Expand All @@ -287,9 +278,7 @@ async def announce_ignore(self, ctx, *, guild: discord.Guild=None):

verb = "will" if ignored else "will not"

await ctx.send("The server {} {} receive announcements.".format(
guild.name, verb
))
await ctx.send("The server {} {} receive announcements.".format(guild.name, verb))

async def _valid_selfroles(self, guild: discord.Guild) -> Tuple[discord.Role]:
"""
Expand Down Expand Up @@ -384,8 +373,10 @@ async def serverlock(self, ctx: commands.Context):

await ctx.send("The bot {} serverlocked.".format(verb))

# region Event Handlers
# region Event Handlers
async def on_guild_join(self, guild: discord.Guild):
if await self._serverlock_check(guild):
return


# endregion
10 changes: 3 additions & 7 deletions redbot/cogs/admin/announcer.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@


class Announcer:
def __init__(self, ctx: commands.Context,
message: str,
config=None):

def __init__(self, ctx: commands.Context, message: str, config=None):
Copy link
Contributor

Choose a reason for hiding this comment

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

Here it does not add spaces around the = operator, despite doing it above frequently

Copy link
Member

Choose a reason for hiding this comment

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

One of them has a type annotation and the other does not. It's consistent and compliant.

"""
:param ctx:
:param message:
Expand Down Expand Up @@ -65,10 +64,7 @@ async def announcer(self):
try:
await channel.send(self.message)
except discord.Forbidden:
await bot_owner.send("I could not announce to server: {}".format(
g.id
))
await bot_owner.send("I could not announce to server: {}".format(g.id))
await asyncio.sleep(0.5)

self.active = False

Loading