[i18n] Start work on named format arguments (#1795)

This commit is contained in:
Michael H 2018-08-16 10:00:57 +10:00 committed by Toby Harradine
parent 139329233a
commit aa8c9c350e
9 changed files with 263 additions and 183 deletions

View File

@ -12,32 +12,35 @@ from .converters import MemberDefaultAuthor, SelfRole
log = logging.getLogger("red.admin") log = logging.getLogger("red.admin")
GENERIC_FORBIDDEN = ( _ = Translator("Admin", __file__)
GENERIC_FORBIDDEN = _(
"I attempted to do something that Discord denied me permissions for." "I attempted to do something that Discord denied me permissions for."
" Your command failed to successfully complete." " Your command failed to successfully complete."
) )
HIERARCHY_ISSUE = ( HIERARCHY_ISSUE = _(
"I tried to add {role.name} to {member.display_name} but that role" "I tried to add {role.name} to {member.display_name} but that role"
" is higher than my highest role in the Discord hierarchy so I was" " is higher than my highest role in the Discord hierarchy so I was"
" unable to successfully add it. Please give me a higher role and " " unable to successfully add it. Please give me a higher role and "
"try again." "try again."
) )
USER_HIERARCHY_ISSUE = ( USER_HIERARCHY_ISSUE = _(
"I tried to add {role.name} to {member.display_name} but that role" "I tried to add {role.name} to {member.display_name} but that role"
" is higher than your highest role in the Discord hierarchy so I was" " is higher than your highest role in the Discord hierarchy so I was"
" unable to successfully add it. Please get a higher role and " " unable to successfully add it. Please get a higher role and "
"try again." "try again."
) )
RUNNING_ANNOUNCEMENT = ( RUNNING_ANNOUNCEMENT = _(
"I am already announcing something. If you would like to make a" "I am already announcing something. If you would like to make a"
" different announcement please use `{prefix}announce cancel`" " different announcement please use `{prefix}announce cancel`"
" first." " first."
) )
@cog_i18n(_)
class Admin(commands.Cog): class Admin(commands.Cog):
def __init__(self, config=Config): def __init__(self, config=Config):
super().__init__() super().__init__()
@ -103,8 +106,9 @@ class Admin(commands.Cog):
await self.complain(ctx, GENERIC_FORBIDDEN) await self.complain(ctx, GENERIC_FORBIDDEN)
else: else:
await ctx.send( await ctx.send(
"I successfully added {role.name} to" _("I successfully added {role.name} to {member.display_name}").format(
" {member.display_name}".format(role=role, member=member) 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):
@ -117,8 +121,9 @@ class Admin(commands.Cog):
await self.complain(ctx, GENERIC_FORBIDDEN) await self.complain(ctx, GENERIC_FORBIDDEN)
else: else:
await ctx.send( await ctx.send(
"I successfully removed {role.name} from" _("I successfully removed {role.name} from {member.display_name}").format(
" {member.display_name}".format(role=role, member=member) role=role, member=member
)
) )
@commands.command() @commands.command()
@ -189,7 +194,7 @@ class Admin(commands.Cog):
await self.complain(ctx, GENERIC_FORBIDDEN) await self.complain(ctx, GENERIC_FORBIDDEN)
else: else:
log.info(reason) log.info(reason)
await ctx.send("Done.") await ctx.send(_("Done."))
@editrole.command(name="name") @editrole.command(name="name")
@checks.admin_or_permissions(administrator=True) @checks.admin_or_permissions(administrator=True)
@ -215,7 +220,7 @@ class Admin(commands.Cog):
await self.complain(ctx, GENERIC_FORBIDDEN) await self.complain(ctx, GENERIC_FORBIDDEN)
else: else:
log.info(reason) log.info(reason)
await ctx.send("Done.") await ctx.send(_("Done."))
@commands.group(invoke_without_command=True) @commands.group(invoke_without_command=True)
@checks.is_owner() @checks.is_owner()
@ -229,7 +234,7 @@ class Admin(commands.Cog):
self.__current_announcer = announcer self.__current_announcer = announcer
await ctx.send("The announcement has begun.") await ctx.send(_("The announcement has begun."))
else: else:
prefix = ctx.prefix prefix = ctx.prefix
await self.complain(ctx, RUNNING_ANNOUNCEMENT, prefix=prefix) await self.complain(ctx, RUNNING_ANNOUNCEMENT, prefix=prefix)
@ -245,7 +250,7 @@ class Admin(commands.Cog):
except AttributeError: except AttributeError:
pass pass
await ctx.send("The current announcement has been cancelled.") await ctx.send(_("The current announcement has been cancelled."))
@announce.command(name="channel") @announce.command(name="channel")
@commands.guild_only() @commands.guild_only()
@ -258,7 +263,9 @@ class Admin(commands.Cog):
channel = ctx.channel channel = ctx.channel
await self.conf.guild(ctx.guild).announce_channel.set(channel.id) 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 {channel.mention}").format(channel=channel)
)
@announce.command(name="ignore") @announce.command(name="ignore")
@commands.guild_only() @commands.guild_only()
@ -270,9 +277,16 @@ class Admin(commands.Cog):
ignored = await self.conf.guild(ctx.guild).announce_ignore() ignored = await self.conf.guild(ctx.guild).announce_ignore()
await self.conf.guild(ctx.guild).announce_ignore.set(not ignored) await self.conf.guild(ctx.guild).announce_ignore.set(not ignored)
verb = "will" if ignored else "will not" if ignored: # Keeping original logic....
await ctx.send(
await ctx.send(f"The server {ctx.guild.name} {verb} receive announcements.") _("The server {guild.name} will receive announcements.").format(guild=ctx.guild)
)
else:
await ctx.send(
_("The server {guild.name} will not receive announcements.").format(
guild=ctx.guild
)
)
async def _valid_selfroles(self, guild: discord.Guild) -> Tuple[discord.Role]: async def _valid_selfroles(self, guild: discord.Guild) -> Tuple[discord.Role]:
""" """
@ -325,7 +339,7 @@ class Admin(commands.Cog):
if role.id not in curr_selfroles: if role.id not in curr_selfroles:
curr_selfroles.append(role.id) curr_selfroles.append(role.id)
await ctx.send("The selfroles list has been successfully modified.") await ctx.send(_("The selfroles list has been successfully modified."))
@selfrole.command(name="delete") @selfrole.command(name="delete")
@checks.admin_or_permissions(manage_roles=True) @checks.admin_or_permissions(manage_roles=True)
@ -338,7 +352,7 @@ class Admin(commands.Cog):
async with self.conf.guild(ctx.guild).selfroles() as curr_selfroles: async with self.conf.guild(ctx.guild).selfroles() as curr_selfroles:
curr_selfroles.remove(role.id) curr_selfroles.remove(role.id)
await ctx.send("The selfroles list has been successfully modified.") await ctx.send(_("The selfroles list has been successfully modified."))
@selfrole.command(name="list") @selfrole.command(name="list")
async def selfrole_list(self, ctx: commands.Context): async def selfrole_list(self, ctx: commands.Context):
@ -348,7 +362,7 @@ class Admin(commands.Cog):
selfroles = await self._valid_selfroles(ctx.guild) selfroles = await self._valid_selfroles(ctx.guild)
fmt_selfroles = "\n".join(["+ " + r.name for r in selfroles]) fmt_selfroles = "\n".join(["+ " + r.name for r in selfroles])
msg = "Available Selfroles:\n{}".format(fmt_selfroles) msg = _("Available Selfroles:\n{selfroles}").format(selfroles=fmt_selfroles)
await ctx.send(box(msg, "diff")) await ctx.send(box(msg, "diff"))
async def _serverlock_check(self, guild: discord.Guild) -> bool: async def _serverlock_check(self, guild: discord.Guild) -> bool:
@ -371,9 +385,10 @@ class Admin(commands.Cog):
serverlocked = await self.conf.serverlocked() serverlocked = await self.conf.serverlocked()
await self.conf.serverlocked.set(not serverlocked) await self.conf.serverlocked.set(not serverlocked)
verb = "is now" if not serverlocked else "is no longer" if serverlocked: # again with original logic I'm not sure of
await ctx.send(_("The bot is no longer serverlocked."))
await ctx.send("The bot {} serverlocked.".format(verb)) else:
await ctx.send(_("The bot is now serverlocked."))
# region Event Handlers # region Event Handlers
async def on_guild_join(self, guild: discord.Guild): async def on_guild_join(self, guild: discord.Guild):

View File

@ -200,9 +200,9 @@ class Alias(commands.Cog):
await ctx.send( await ctx.send(
_( _(
"You attempted to create a new alias" "You attempted to create a new alias"
" with the name {} but that" " with the name {name} but that"
" name is already a command on this bot." " name is already a command on this bot."
).format(alias_name) ).format(name=alias_name)
) )
return return
@ -211,9 +211,9 @@ class Alias(commands.Cog):
await ctx.send( await ctx.send(
_( _(
"You attempted to create a new alias" "You attempted to create a new alias"
" with the name {} but that" " with the name {name} but that"
" alias already exists on this server." " alias already exists on this server."
).format(alias_name) ).format(name=alias_name)
) )
return return
@ -222,10 +222,10 @@ class Alias(commands.Cog):
await ctx.send( await ctx.send(
_( _(
"You attempted to create a new alias" "You attempted to create a new alias"
" with the name {} but that" " with the name {name} but that"
" name is an invalid alias name. Alias" " name is an invalid alias name. Alias"
" names may not contain spaces." " names may not contain spaces."
).format(alias_name) ).format(name=alias_name)
) )
return return
# endregion # endregion
@ -235,7 +235,9 @@ class Alias(commands.Cog):
await self.add_alias(ctx, alias_name, command) await self.add_alias(ctx, alias_name, command)
await ctx.send(_("A new alias with the trigger `{}` has been created.").format(alias_name)) await ctx.send(
_("A new alias with the trigger `{name}` has been created.").format(name=alias_name)
)
@checks.is_owner() @checks.is_owner()
@global_.command(name="add") @global_.command(name="add")
@ -249,9 +251,9 @@ class Alias(commands.Cog):
await ctx.send( await ctx.send(
_( _(
"You attempted to create a new global alias" "You attempted to create a new global alias"
" with the name {} but that" " with the name {name} but that"
" name is already a command on this bot." " name is already a command on this bot."
).format(alias_name) ).format(name=alias_name)
) )
return return
@ -260,9 +262,9 @@ class Alias(commands.Cog):
await ctx.send( await ctx.send(
_( _(
"You attempted to create a new global alias" "You attempted to create a new global alias"
" with the name {} but that" " with the name {name} but that"
" alias already exists on this server." " alias already exists on this server."
).format(alias_name) ).format(name=alias_name)
) )
return return
@ -271,10 +273,10 @@ class Alias(commands.Cog):
await ctx.send( await ctx.send(
_( _(
"You attempted to create a new global alias" "You attempted to create a new global alias"
" with the name {} but that" " with the name {name} but that"
" name is an invalid alias name. Alias" " name is an invalid alias name. Alias"
" names may not contain spaces." " names may not contain spaces."
).format(alias_name) ).format(name=alias_name)
) )
return return
# endregion # endregion
@ -282,7 +284,9 @@ class Alias(commands.Cog):
await self.add_alias(ctx, alias_name, command, global_=True) await self.add_alias(ctx, alias_name, command, global_=True)
await ctx.send( await ctx.send(
_("A new global alias with the trigger `{}` has been created.").format(alias_name) _("A new global alias with the trigger `{name}` has been created.").format(
name=alias_name
)
) )
@alias.command(name="help") @alias.command(name="help")
@ -294,10 +298,12 @@ class Alias(commands.Cog):
base_cmd = alias.command[0] base_cmd = alias.command[0]
new_msg = copy(ctx.message) new_msg = copy(ctx.message)
new_msg.content = "{}help {}".format(ctx.prefix, base_cmd) new_msg.content = _("{prefix}help {command}").format(
prefix=ctx.prefix, command=base_cmd
)
await self.bot.process_commands(new_msg) await self.bot.process_commands(new_msg)
else: else:
ctx.send(_("No such alias exists.")) await ctx.send(_("No such alias exists."))
@alias.command(name="show") @alias.command(name="show")
@commands.guild_only() @commands.guild_only()
@ -307,10 +313,12 @@ class Alias(commands.Cog):
if is_alias: if is_alias:
await ctx.send( await ctx.send(
_("The `{}` alias will execute the command `{}`").format(alias_name, alias.command) _("The `{alias_name}` alias will execute the command `{command}`").format(
alias_name=alias_name, command=alias.command
)
) )
else: else:
await ctx.send(_("There is no alias with the name `{}`").format(alias_name)) await ctx.send(_("There is no alias with the name `{name}`").format(name=alias_name))
@checks.mod_or_permissions(manage_guild=True) @checks.mod_or_permissions(manage_guild=True)
@alias.command(name="del") @alias.command(name="del")
@ -328,10 +336,10 @@ class Alias(commands.Cog):
if await self.delete_alias(ctx, alias_name): if await self.delete_alias(ctx, alias_name):
await ctx.send( await ctx.send(
_("Alias with the name `{}` was successfully deleted.").format(alias_name) _("Alias with the name `{name}` was successfully deleted.").format(name=alias_name)
) )
else: else:
await ctx.send(_("Alias with name `{}` was not found.").format(alias_name)) await ctx.send(_("Alias with name `{name}` was not found.").format(name=alias_name))
@checks.is_owner() @checks.is_owner()
@global_.command(name="del") @global_.command(name="del")
@ -348,10 +356,10 @@ class Alias(commands.Cog):
if await self.delete_alias(ctx, alias_name, global_=True): if await self.delete_alias(ctx, alias_name, global_=True):
await ctx.send( await ctx.send(
_("Alias with the name `{}` was successfully deleted.").format(alias_name) _("Alias with the name `{name}` was successfully deleted.").format(name=alias_name)
) )
else: else:
await ctx.send(_("Alias with name `{}` was not found.").format(alias_name)) await ctx.send(_("Alias with name `{name}` was not found.").format(name=alias_name))
@alias.command(name="list") @alias.command(name="list")
@commands.guild_only() @commands.guild_only()

View File

@ -81,8 +81,11 @@ class Bank(commands.Cog):
default_balance = await bank._conf.guild(ctx.guild).default_balance() default_balance = await bank._conf.guild(ctx.guild).default_balance()
settings = _( settings = _(
"Bank settings:\n\nBank name: {}\nCurrency: {}\nDefault balance: {}" "Bank settings:\n\nBank name: {bank_name}\nCurrency: {currency_name}\n"
).format(bank_name, currency_name, default_balance) "Default balance: {default_balance}"
).format(
bank_name=bank_name, currency_name=currency_name, default_balance=default_balance
)
await ctx.send(box(settings)) await ctx.send(box(settings))
@bankset.command(name="toggleglobal") @bankset.command(name="toggleglobal")
@ -97,26 +100,26 @@ class Bank(commands.Cog):
if confirm is False: if confirm is False:
await ctx.send( await ctx.send(
_( _(
"This will toggle the bank to be {}, deleting all accounts " "This will toggle the bank to be {banktype}, deleting all accounts "
"in the process! If you're sure, type `{}`" "in the process! If you're sure, type `{command}`"
).format(word, "{}bankset toggleglobal yes".format(ctx.prefix)) ).format(banktype=word, command="{}bankset toggleglobal yes".format(ctx.prefix))
) )
else: else:
await bank.set_global(not cur_setting) await bank.set_global(not cur_setting)
await ctx.send(_("The bank is now {}.").format(word)) await ctx.send(_("The bank is now {banktype}.").format(banktype=word))
@bankset.command(name="bankname") @bankset.command(name="bankname")
@check_global_setting_guildowner() @check_global_setting_guildowner()
async def bankset_bankname(self, ctx: commands.Context, *, name: str): async def bankset_bankname(self, ctx: commands.Context, *, name: str):
"""Set the bank's name""" """Set the bank's name"""
await bank.set_bank_name(name, ctx.guild) await bank.set_bank_name(name, ctx.guild)
await ctx.send(_("Bank's name has been set to {}").format(name)) await ctx.send(_("Bank name has been set to: {name}").format(name=name))
@bankset.command(name="creditsname") @bankset.command(name="creditsname")
@check_global_setting_guildowner() @check_global_setting_guildowner()
async def bankset_creditsname(self, ctx: commands.Context, *, name: str): async def bankset_creditsname(self, ctx: commands.Context, *, name: str):
"""Set the name for the bank's currency""" """Set the name for the bank's currency"""
await bank.set_currency_name(name, ctx.guild) await bank.set_currency_name(name, ctx.guild)
await ctx.send(_("Currency name has been set to {}").format(name)) await ctx.send(_("Currency name has been set to: {name}").format(name=name))
# ENDSECTION # ENDSECTION

View File

@ -33,7 +33,7 @@ class Cleanup(commands.Cog):
""" """
prompt = await ctx.send( prompt = await ctx.send(
_("Are you sure you want to delete {} messages? (y/n)").format(number) _("Are you sure you want to delete {number} messages? (y/n)").format(number=number)
) )
response = await ctx.bot.wait_for("message", check=MessagePredicate.same_context(ctx)) response = await ctx.bot.wait_for("message", check=MessagePredicate.same_context(ctx))

View File

@ -52,11 +52,11 @@ class CommandObj:
async def get_responses(self, ctx): async def get_responses(self, ctx):
intro = _( intro = _(
"Welcome to the interactive random {} maker!\n" "Welcome to the interactive random {cc} maker!\n"
"Every message you send will be added as one of the random " "Every message you send will be added as one of the random "
"responses to choose from once this {} is " "responses to choose from once this {} is "
"triggered. To exit this interactive menu, type `{}`" "triggered. To exit this interactive menu, type `{quit}`"
).format("customcommand", "customcommand", "exit()") ).format(cc="customcommand", quit="exit()")
await ctx.send(intro) await ctx.send(intro)
responses = [] responses = []
@ -226,8 +226,8 @@ class CustomCommands(commands.Cog):
await ctx.send(_("Custom command successfully added.")) await ctx.send(_("Custom command successfully added."))
except AlreadyExists: except AlreadyExists:
await ctx.send( await ctx.send(
_("This command already exists. Use `{}` to edit it.").format( _("This command already exists. Use `{command}` to edit it.").format(
"{}customcom edit".format(ctx.prefix) command="{}customcom edit".format(ctx.prefix)
) )
) )
@ -249,8 +249,8 @@ class CustomCommands(commands.Cog):
await ctx.send(_("Custom command successfully added.")) await ctx.send(_("Custom command successfully added."))
except AlreadyExists: except AlreadyExists:
await ctx.send( await ctx.send(
_("This command already exists. Use `{}` to edit it.").format( _("This command already exists. Use `{command}` to edit it.").format(
"{}customcom edit".format(ctx.prefix) command="{}customcom edit".format(ctx.prefix)
) )
) )
except ArgParseError as e: except ArgParseError as e:
@ -293,8 +293,8 @@ class CustomCommands(commands.Cog):
await ctx.send(_("Custom command cooldown successfully edited.")) await ctx.send(_("Custom command cooldown successfully edited."))
except NotFound: except NotFound:
await ctx.send( await ctx.send(
_("That command doesn't exist. Use `{}` to add it.").format( _("That command doesn't exist. Use `{command}` to add it.").format(
"{}customcom add".format(ctx.prefix) command="{}customcom add".format(ctx.prefix)
) )
) )
@ -341,8 +341,8 @@ class CustomCommands(commands.Cog):
await ctx.send( await ctx.send(
_( _(
"There are no custom commands in this server." "There are no custom commands in this server."
" Use `{}` to start adding some." " Use `{command}` to start adding some."
).format("{}customcom add".format(ctx.prefix)) ).format(command="{}customcom add".format(ctx.prefix))
) )
return return

View File

@ -242,7 +242,7 @@ class Downloader(commands.Cog):
exc_info=err, exc_info=err,
) )
else: else:
await ctx.send(_("Repo `{}` successfully added.").format(name)) await ctx.send(_("Repo `{name}` successfully added.").format(name=name))
if repo.install_msg is not None: if repo.install_msg is not None:
await ctx.send(repo.install_msg.replace("[p]", ctx.prefix)) await ctx.send(repo.install_msg.replace("[p]", ctx.prefix))
@ -253,7 +253,9 @@ class Downloader(commands.Cog):
""" """
await self._repo_manager.delete_repo(repo_name.name) await self._repo_manager.delete_repo(repo_name.name)
await ctx.send(_("The repo `{}` has been deleted successfully.").format(repo_name.name)) await ctx.send(
_("The repo `{name}` has been deleted successfully.").format(name=repo_name.name)
)
@repo.command(name="list") @repo.command(name="list")
async def _repo_list(self, ctx): async def _repo_list(self, ctx):
@ -276,10 +278,12 @@ class Downloader(commands.Cog):
Lists information about a single repo Lists information about a single repo
""" """
if repo_name is None: if repo_name is None:
await ctx.send(_("There is no repo `{}`").format(repo_name.name)) await ctx.send(_("There is no repo `{repo_name}`").format(repo_name=repo_name.name))
return return
msg = _("Information on {}:\n{}").format(repo_name.name, repo_name.description or "") msg = _("Information on {repo_name}:\n{description}").format(
repo_name=repo_name.name, description=repo_name.description or ""
)
await ctx.send(box(msg)) await ctx.send(box(msg))
@commands.group() @commands.group()
@ -298,9 +302,9 @@ class Downloader(commands.Cog):
cog = discord.utils.get(repo_name.available_cogs, name=cog_name) # type: Installable cog = discord.utils.get(repo_name.available_cogs, name=cog_name) # type: Installable
if cog is None: if cog is None:
await ctx.send( await ctx.send(
_("Error, there is no cog by the name of `{}` in the `{}` repo.").format( _(
cog_name, repo_name.name "Error, there is no cog by the name of `{cog_name}` in the `{repo_name}` repo."
) ).format(cog_name=cog_name, repo_name=repo_name.name)
) )
return return
elif cog.min_python_version > sys.version_info: elif cog.min_python_version > sys.version_info:
@ -313,9 +317,9 @@ class Downloader(commands.Cog):
if not await repo_name.install_requirements(cog, self.LIB_PATH): if not await repo_name.install_requirements(cog, self.LIB_PATH):
await ctx.send( await ctx.send(
_("Failed to install the required libraries for `{}`: `{}`").format( _(
cog.name, cog.requirements "Failed to install the required libraries for `{cog_name}`: `{libraries}`"
) ).format(cog_name=cog.name, libraries=cog.requirements)
) )
return return
@ -325,7 +329,7 @@ class Downloader(commands.Cog):
await repo_name.install_libraries(self.SHAREDLIB_PATH) await repo_name.install_libraries(self.SHAREDLIB_PATH)
await ctx.send(_("`{}` cog successfully installed.").format(cog_name)) await ctx.send(_("`{cog_name}` cog successfully installed.").format(cog_name=cog_name))
if cog.install_msg is not None: if cog.install_msg is not None:
await ctx.send(cog.install_msg.replace("[p]", ctx.prefix)) await ctx.send(cog.install_msg.replace("[p]", ctx.prefix))
@ -343,7 +347,9 @@ class Downloader(commands.Cog):
await self._delete_cog(poss_installed_path) await self._delete_cog(poss_installed_path)
# noinspection PyTypeChecker # noinspection PyTypeChecker
await self._remove_from_installed(cog_name) await self._remove_from_installed(cog_name)
await ctx.send(_("`{}` was successfully removed.").format(real_name)) await ctx.send(
_("`{real_name}` was successfully removed.").format(real_name=real_name)
)
else: else:
await ctx.send( await ctx.send(
_( _(
@ -453,12 +459,18 @@ class Downloader(commands.Cog):
cog = discord.utils.get(repo_name.available_cogs, name=cog_name) cog = discord.utils.get(repo_name.available_cogs, name=cog_name)
if cog is None: if cog is None:
await ctx.send( await ctx.send(
_("There is no cog `{}` in the repo `{}`").format(cog_name, repo_name.name) _("There is no cog `{cog_name}` in the repo `{repo_name}`").format(
cog_name=cog_name, repo_name=repo_name.name
)
) )
return return
msg = _("Information on {}:\n{}\n\nRequirements: {}").format( msg = _(
cog.name, cog.description or "", ", ".join(cog.requirements) or "None" "Information on {cog_name}:\n{description}\n\nRequirements: {requirements}"
).format(
cog_name=cog.name,
description=cog.description or "",
requirements=", ".join(cog.requirements) or "None",
) )
await ctx.send(box(msg)) await ctx.send(box(msg))
@ -512,9 +524,9 @@ class Downloader(commands.Cog):
repo_url = "https://github.com/Cog-Creators/Red-DiscordBot" repo_url = "https://github.com/Cog-Creators/Red-DiscordBot"
cog_name = cog_installable.__class__.__name__ cog_name = cog_installable.__class__.__name__
msg = _("Command: {}\nMade by: {}\nRepo: {}\nCog name: {}") msg = _("Command: {command}\nMade by: {author}\nRepo: {repo}\nCog name: {cog}")
return msg.format(command_name, made_by, repo_url, cog_name) return msg.format(command=command_name, author=made_by, repo=repo_url, cog=cog_name)
def cog_name_from_instance(self, instance: object) -> str: def cog_name_from_instance(self, instance: object) -> str:
"""Determines the cog name that Downloader knows from the cog instance. """Determines the cog name that Downloader knows from the cog instance.

View File

@ -447,32 +447,30 @@ class Economy(commands.Cog):
"""Changes economy module settings""" """Changes economy module settings"""
guild = ctx.guild guild = ctx.guild
if ctx.invoked_subcommand is None: if ctx.invoked_subcommand is None:
fmt = {}
if await bank.is_global(): if await bank.is_global():
slot_min = await self.config.SLOT_MIN() fmt["slot_min"] = await self.config.SLOT_MIN()
slot_max = await self.config.SLOT_MAX() fmt["slot_max"] = await self.config.SLOT_MAX()
slot_time = await self.config.SLOT_TIME() fmt["slot_time"] = await self.config.SLOT_TIME()
payday_time = await self.config.PAYDAY_TIME() fmt["payday_time"] = await self.config.PAYDAY_TIME()
payday_amount = await self.config.PAYDAY_CREDITS() fmt["payday_amount"] = await self.config.PAYDAY_CREDITS()
else: else:
slot_min = await self.config.guild(guild).SLOT_MIN() fmt["slot_min"] = await self.config.guild(guild).SLOT_MIN()
slot_max = await self.config.guild(guild).SLOT_MAX() fmt["slot_max"] = await self.config.guild(guild).SLOT_MAX()
slot_time = await self.config.guild(guild).SLOT_TIME() fmt["slot_time"] = await self.config.guild(guild).SLOT_TIME()
payday_time = await self.config.guild(guild).PAYDAY_TIME() fmt["payday_time"] = await self.config.guild(guild).PAYDAY_TIME()
payday_amount = await self.config.guild(guild).PAYDAY_CREDITS() fmt["payday_amount"] = await self.config.guild(guild).PAYDAY_CREDITS()
register_amount = await bank.get_default_balance(guild) fmt["register_amount"] = await bank.get_default_balance(guild)
msg = box( msg = box(
_( _(
"Minimum slot bid: {}\n" "Current Economy settings:"
"Maximum slot bid: {}\n" "Minimum slot bid: {slot_min}\n"
"Slot cooldown: {}\n" "Maximum slot bid: {slot_max}\n"
"Payday amount: {}\n" "Slot cooldown: {slot_time}\n"
"Payday cooldown: {}\n" "Payday amount: {payday_amount}\n"
"Amount given at account registration: {}" "Payday cooldown: {payday_time}\n"
"" "Amount given at account registration: {register_amount}"
).format( ).format(**fmt)
slot_min, slot_max, slot_time, payday_amount, payday_time, register_amount
),
_("Current Economy settings:"),
) )
await ctx.send(msg) await ctx.send(msg)
@ -488,7 +486,9 @@ class Economy(commands.Cog):
else: else:
await self.config.guild(guild).SLOT_MIN.set(bid) await self.config.guild(guild).SLOT_MIN.set(bid)
credits_name = await bank.get_currency_name(guild) credits_name = await bank.get_currency_name(guild)
await ctx.send(_("Minimum bid is now {} {}.").format(bid, credits_name)) await ctx.send(
_("Minimum bid is now {bid} {currency}.").format(bid=bid, currency=credits_name)
)
@economyset.command() @economyset.command()
async def slotmax(self, ctx: commands.Context, bid: int): async def slotmax(self, ctx: commands.Context, bid: int):
@ -503,7 +503,9 @@ class Economy(commands.Cog):
await self.config.SLOT_MAX.set(bid) await self.config.SLOT_MAX.set(bid)
else: else:
await self.config.guild(guild).SLOT_MAX.set(bid) await self.config.guild(guild).SLOT_MAX.set(bid)
await ctx.send(_("Maximum bid is now {} {}.").format(bid, credits_name)) await ctx.send(
_("Maximum bid is now {bid} {currency}.").format(bid=bid, currency=credits_name)
)
@economyset.command() @economyset.command()
async def slottime(self, ctx: commands.Context, seconds: int): async def slottime(self, ctx: commands.Context, seconds: int):
@ -513,7 +515,7 @@ class Economy(commands.Cog):
await self.config.SLOT_TIME.set(seconds) await self.config.SLOT_TIME.set(seconds)
else: else:
await self.config.guild(guild).SLOT_TIME.set(seconds) await self.config.guild(guild).SLOT_TIME.set(seconds)
await ctx.send(_("Cooldown is now {} seconds.").format(seconds)) await ctx.send(_("Cooldown is now {num} seconds.").format(num=seconds))
@economyset.command() @economyset.command()
async def paydaytime(self, ctx: commands.Context, seconds: int): async def paydaytime(self, ctx: commands.Context, seconds: int):
@ -524,7 +526,9 @@ class Economy(commands.Cog):
else: else:
await self.config.guild(guild).PAYDAY_TIME.set(seconds) await self.config.guild(guild).PAYDAY_TIME.set(seconds)
await ctx.send( await ctx.send(
_("Value modified. At least {} seconds must pass between each payday.").format(seconds) _("Value modified. At least {num} seconds must pass between each payday.").format(
num=seconds
)
) )
@economyset.command() @economyset.command()
@ -539,7 +543,11 @@ class Economy(commands.Cog):
await self.config.PAYDAY_CREDITS.set(creds) await self.config.PAYDAY_CREDITS.set(creds)
else: else:
await self.config.guild(guild).PAYDAY_CREDITS.set(creds) await self.config.guild(guild).PAYDAY_CREDITS.set(creds)
await ctx.send(_("Every payday will now give {} {}.").format(creds, credits_name)) await ctx.send(
_("Every payday will now give {num} {currency}.").format(
num=creds, currency=credits_name
)
)
@economyset.command() @economyset.command()
async def rolepaydayamount(self, ctx: commands.Context, role: discord.Role, creds: int): async def rolepaydayamount(self, ctx: commands.Context, role: discord.Role, creds: int):
@ -551,9 +559,10 @@ class Economy(commands.Cog):
else: else:
await self.config.role(role).PAYDAY_CREDITS.set(creds) await self.config.role(role).PAYDAY_CREDITS.set(creds)
await ctx.send( await ctx.send(
_("Every payday will now give {} {} to people with the role {}.").format( _(
creds, credits_name, role.name "Every payday will now give {num} {currency} "
) "to people with the role {role_name}."
).format(num=creds, currency=credits_name, role_name=role.name)
) )
@economyset.command() @economyset.command()
@ -565,7 +574,9 @@ class Economy(commands.Cog):
credits_name = await bank.get_currency_name(guild) credits_name = await bank.get_currency_name(guild)
await bank.set_default_balance(creds, guild) await bank.set_default_balance(creds, guild)
await ctx.send( await ctx.send(
_("Registering an account will now give {} {}.").format(creds, credits_name) _("Registering an account will now give {num} {currency}.").format(
num=creds, currency=credits_name
)
) )
# What would I ever do without stackoverflow? # What would I ever do without stackoverflow?

View File

@ -131,11 +131,23 @@ class General(commands.Cog):
outcome = cond[(player_choice, red_choice)] outcome = cond[(player_choice, red_choice)]
if outcome is True: if outcome is True:
await ctx.send(_("{} You win {}!").format(red_choice.value, author.mention)) await ctx.send(
_("{choice} You win {author.mention}!").format(
choice=red_choice.value, author=author
)
)
elif outcome is False: elif outcome is False:
await ctx.send(_("{} You lose {}!").format(red_choice.value, author.mention)) await ctx.send(
_("{choice} You lose {author.mention}!").format(
choice=red_choice.value, author=author
)
)
else: else:
await ctx.send(_("{} We're square {}!").format(red_choice.value, author.mention)) await ctx.send(
_("{choice} We're square {author.mention}!").format(
choice=red_choice.value, author=author
)
)
@commands.command(name="8", aliases=["8ball"]) @commands.command(name="8", aliases=["8ball"])
async def _8ball(self, ctx, *, question: str): async def _8ball(self, ctx, *, question: str):
@ -198,12 +210,12 @@ class General(commands.Cog):
text_channels = len(guild.text_channels) text_channels = len(guild.text_channels)
voice_channels = len(guild.voice_channels) voice_channels = len(guild.voice_channels)
passed = (ctx.message.created_at - guild.created_at).days passed = (ctx.message.created_at - guild.created_at).days
created_at = _("Since {}. That's over {} days ago!").format( created_at = _("Since {date}. That's over {num} days ago!").format(
guild.created_at.strftime("%d %b %Y %H:%M"), passed date=guild.created_at.strftime("%d %b %Y %H:%M"), num=passed
) )
data = discord.Embed(description=created_at, colour=(await ctx.embed_colour())) data = discord.Embed(description=created_at, colour=(await ctx.embed_colour()))
data.add_field(name=_("Region"), value=str(guild.region)) data.add_field(name=_("Region"), value=str(guild.region))
data.add_field(name=_("Users"), value="{}/{}".format(online, total_users)) data.add_field(name=_("Users"), value=f"{online}/{total_users}")
data.add_field(name=_("Text Channels"), value=str(text_channels)) data.add_field(name=_("Text Channels"), value=str(text_channels))
data.add_field(name=_("Voice Channels"), value=str(voice_channels)) data.add_field(name=_("Voice Channels"), value=str(voice_channels))
data.add_field(name=_("Roles"), value=str(len(guild.roles))) data.add_field(name=_("Roles"), value=str(len(guild.roles)))
@ -223,7 +235,7 @@ class General(commands.Cog):
@commands.command() @commands.command()
async def urban(self, ctx, *, word): async def urban(self, ctx, *, word):
"""Searches urban dictionary entries using the unofficial api""" """Searches urban dictionary entries using the unofficial API."""
try: try:
url = "https://api.urbandictionary.com/v0/define?term=" + str(word).lower() url = "https://api.urbandictionary.com/v0/define?term=" + str(word).lower()
@ -236,8 +248,9 @@ class General(commands.Cog):
except: except:
await ctx.send( await ctx.send(
_("No Urban dictionary entries were found or there was an error in the process") _("No Urban dictionary entries were found, or there was an error in the process")
) )
return
if data.get("error") != 404: if data.get("error") != 404:
@ -246,20 +259,20 @@ class General(commands.Cog):
embeds = [] embeds = []
for ud in data["list"]: for ud in data["list"]:
embed = discord.Embed() embed = discord.Embed()
embed.title = _("{} by {}").format(ud["word"].capitalize(), ud["author"]) embed.title = _("{word} by {author}").format(
word=ud["word"].capitalize(), author=ud["author"]
)
embed.url = ud["permalink"] embed.url = ud["permalink"]
description = "{} \n \n **Example : ** {}".format( description = _("{definition}\n\n**Example:** {example}").format(**ud)
ud["definition"], ud.get("example", "N/A")
)
if len(description) > 2048: if len(description) > 2048:
description = "{}...".format(description[:2045]) description = "{}...".format(description[:2045])
embed.description = description embed.description = description
embed.set_footer( embed.set_footer(
text=_("{} Down / {} Up , Powered by urban dictionary").format( text=_(
ud["thumbs_down"], ud["thumbs_up"] "{thumbs_down} Down / {thumbs_up} Up, Powered by Urban Dictionary."
) ).format(**ud)
) )
embeds.append(embed) embeds.append(embed)
@ -274,25 +287,17 @@ class General(commands.Cog):
) )
else: else:
messages = [] messages = []
ud.set_default("example", "N/A")
for ud in data["list"]: for ud in data["list"]:
description = _("{} \n \n **Example : ** {}").format( description = _("{definition}\n\n**Example:** {example}").format(**ud)
ud["definition"], ud.get("example", "N/A")
)
if len(description) > 2048: if len(description) > 2048:
description = "{}...".format(description[:2045]) description = "{}...".format(description[:2045])
description = description description = description
message = _( message = _(
"<{}> \n {} by {} \n \n {} \n \n {} Down / {} Up, Powered by urban " "<{permalink}>\n {word} by {author}\n\n{description}\n\n"
"dictionary" "{thumbs_down} Down / {thumbs_up} Up, Powered by urban dictionary"
).format( ).format(word=ud.pop("word").capitalize(), **ud)
ud["permalink"],
ud["word"].capitalize(),
ud["author"],
description,
ud["thumbs_down"],
ud["thumbs_up"],
)
messages.append(message) messages.append(message)
if messages is not None and len(messages) > 0: if messages is not None and len(messages) > 0:
@ -306,6 +311,6 @@ class General(commands.Cog):
) )
else: else:
await ctx.send( await ctx.send(
_("No Urban dictionary entries were found or there was an error in the process") _("No Urban dictionary entries were found, or there was an error in the process.")
) )
return return

View File

@ -178,17 +178,25 @@ class Mod(commands.Cog):
delete_delay = await self.settings.guild(guild).delete_delay() delete_delay = await self.settings.guild(guild).delete_delay()
reinvite_on_unban = await self.settings.guild(guild).reinvite_on_unban() reinvite_on_unban = await self.settings.guild(guild).reinvite_on_unban()
msg = "" msg = ""
msg += "Delete repeats: {}\n".format("Yes" if delete_repeats else "No") msg += _("Delete repeats: {yes_or_no}\n").format(
msg += "Ban mention spam: {}\n".format( yes_or_no=_("Yes") if delete_repeats else _("No")
"{} mentions".format(ban_mention_spam) )
msg += _("Ban mention spam: {num_mentions}\n").format(
num_mentions=_("{num} mentions").format(num=ban_mention_spam)
if isinstance(ban_mention_spam, int) if isinstance(ban_mention_spam, int)
else "No" else _("No")
) )
msg += "Respects hierarchy: {}\n".format("Yes" if respect_hierarchy else "No") msg += _("Respects hierarchy: {yes_or_no}\n").format(
msg += "Delete delay: {}\n".format( yes_or_no=_("Yes") if respect_hierarchy else _("No")
"{} seconds".format(delete_delay) if delete_delay != -1 else "None" )
msg += _("Delete delay: {num_seconds}\n").format(
num_seconds=_("{num} seconds").format(delete_delay)
if delete_delay != -1
else _("None")
)
msg += _("Reinvite on unban: {yes_or_no}\n").format(
yes_or_no=_("Yes") if respect_hierarchy else _("No")
) )
msg += "Reinvite on unban: {}".format("Yes" if reinvite_on_unban else "No")
await ctx.send(box(msg)) await ctx.send(box(msg))
@modset.command() @modset.command()
@ -222,9 +230,9 @@ class Mod(commands.Cog):
await ctx.send( await ctx.send(
_( _(
"Autoban for mention spam enabled. " "Autoban for mention spam enabled. "
"Anyone mentioning {} or more different people " "Anyone mentioning {max_mentions} or more different people "
"in a single message will be autobanned." "in a single message will be autobanned."
).format(max_mentions) ).format(max_mentions=max_mentions)
) )
else: else:
cur_setting = await self.settings.guild(guild).ban_mention_spam() cur_setting = await self.settings.guild(guild).ban_mention_spam()
@ -262,16 +270,16 @@ class Mod(commands.Cog):
if time == -1: if time == -1:
await ctx.send(_("Command deleting disabled.")) await ctx.send(_("Command deleting disabled."))
else: else:
await ctx.send(_("Delete delay set to {} seconds.").format(time)) await ctx.send(_("Delete delay set to {num} seconds.").format(num=time))
else: else:
delay = await self.settings.guild(guild).delete_delay() delay = await self.settings.guild(guild).delete_delay()
if delay != -1: if delay != -1:
await ctx.send( await ctx.send(
_( _(
"Bot will delete command messages after" "Bot will delete command messages after"
" {} seconds. Set this value to -1 to" " {num} seconds. Set this value to -1 to"
" stop deleting messages" " stop deleting messages"
).format(delay) ).format(num=delay)
) )
else: else:
await ctx.send(_("I will not delete command messages.")) await ctx.send(_("I will not delete command messages."))
@ -287,10 +295,16 @@ class Mod(commands.Cog):
cur_setting = await self.settings.guild(guild).reinvite_on_unban() cur_setting = await self.settings.guild(guild).reinvite_on_unban()
if not cur_setting: if not cur_setting:
await self.settings.guild(guild).reinvite_on_unban.set(True) await self.settings.guild(guild).reinvite_on_unban.set(True)
await ctx.send(_("Users unbanned with {} will be reinvited.").format("[p]unban")) await ctx.send(
_("Users unbanned with {command} will be reinvited.").format(f"{ctx.prefix}unban")
)
else: else:
await self.settings.guild(guild).reinvite_on_unban.set(False) await self.settings.guild(guild).reinvite_on_unban.set(False)
await ctx.send(_("Users unbanned with {} will not be reinvited.").format("[p]unban")) await ctx.send(
_("Users unbanned with {command} will not be reinvited.").format(
f"{ctx.prefix}unban"
)
)
@commands.command() @commands.command()
@commands.guild_only() @commands.guild_only()
@ -305,7 +319,9 @@ class Mod(commands.Cog):
if author == user: if author == user:
await ctx.send( await ctx.send(
_("I cannot let you do that. Self-harm is bad {}").format("\N{PENSIVE FACE}") _("I cannot let you do that. Self-harm is bad {emoji}").format(
emoji="\N{PENSIVE FACE}"
)
) )
return return
elif not await is_allowed_by_hierarchy(self.bot, self.settings, guild, author, user): elif not await is_allowed_by_hierarchy(self.bot, self.settings, guild, author, user):
@ -515,9 +531,13 @@ class Mod(commands.Cog):
try: # We don't want blocked DMs preventing us from banning try: # We don't want blocked DMs preventing us from banning
msg = await user.send( msg = await user.send(
_( _(
"You have been temporarily banned from {} until {}. " "You have been temporarily banned from {server_name} until {date}. "
"Here is an invite for when your ban expires: {}" "Here is an invite for when your ban expires: {invite_link}"
).format(guild.name, unban_time.strftime("%m-%d-%Y %H:%M:%S"), invite) ).format(
server_name=guild.name,
date=unban_time.strftime("%m-%d-%Y %H:%M:%S"),
invite_link=invite,
)
) )
except discord.HTTPException: except discord.HTTPException:
msg = None msg = None
@ -557,7 +577,9 @@ class Mod(commands.Cog):
if author == user: if author == user:
await ctx.send( await ctx.send(
_("I cannot let you do that. Self-harm is bad {}").format("\N{PENSIVE FACE}") _("I cannot let you do that. Self-harm is bad {emoji}").format(
emoji="\N{PENSIVE FACE}"
)
) )
return return
elif not await is_allowed_by_hierarchy(self.bot, self.settings, guild, author, user): elif not await is_allowed_by_hierarchy(self.bot, self.settings, guild, author, user):
@ -583,8 +605,8 @@ class Mod(commands.Cog):
_( _(
"You have been banned and " "You have been banned and "
"then unbanned as a quick way to delete your messages.\n" "then unbanned as a quick way to delete your messages.\n"
"You can now join the server again. {}" "You can now join the server again. {invite_link}"
).format(invite) ).format(invite_link=invite)
) )
except discord.HTTPException: except discord.HTTPException:
msg = None msg = None
@ -687,26 +709,26 @@ class Mod(commands.Cog):
invite = await self.get_invite_for_reinvite(ctx) invite = await self.get_invite_for_reinvite(ctx)
if invite: if invite:
try: try:
user.send( await user.send(
_( _(
"You've been unbanned from {}.\n" "You've been unbanned from {server}.\n"
"Here is an invite for that server: {}" "Here is an invite for that server: {invite_link}"
).format(guild.name, invite.url) ).format(server=guild.name, invite_link=invite.url)
) )
except discord.Forbidden: except discord.Forbidden:
await ctx.send( await ctx.send(
_( _(
"I failed to send an invite to that user. " "I failed to send an invite to that user. "
"Perhaps you may be able to send it for me?\n" "Perhaps you may be able to send it for me?\n"
"Here's the invite link: {}" "Here's the invite link: {invite_link}"
).format(invite.url) ).format(invite_link=invite.url)
) )
except discord.HTTPException: except discord.HTTPException:
await ctx.send( await ctx.send(
_( _(
"Something went wrong when attempting to send that user" "Something went wrong when attempting to send that user"
"an invite. Here's the link so you can try: {}" "an invite. Here's the link so you can try: {invite_link}"
).format(invite.url) ).format(invite_link=invite.url)
) )
@staticmethod @staticmethod
@ -841,7 +863,9 @@ class Mod(commands.Cog):
await ctx.send("Done.") await ctx.send("Done.")
except discord.Forbidden: except discord.Forbidden:
await ctx.send( await ctx.send(
_("I cannot do that, I lack the '{}' permission.").format("Manage Nicknames") _("I cannot do that, I lack the '{perm}' permission.").format(
perm="Manage Nicknames"
)
) )
@commands.group() @commands.group()
@ -868,9 +892,7 @@ class Mod(commands.Cog):
audit_reason = get_audit_reason(ctx.author, reason) audit_reason = get_audit_reason(ctx.author, reason)
await channel.set_permissions(user, overwrite=overwrites, reason=audit_reason) await channel.set_permissions(user, overwrite=overwrites, reason=audit_reason)
await ctx.send( await ctx.send(
_("Muted {}#{} in channel {}").format( _("Muted {user} in channel {channel.name}").format(user, channel=channel)
user.name, user.discriminator, channel.name
)
) )
try: try:
await modlog.create_case( await modlog.create_case(
@ -888,7 +910,9 @@ class Mod(commands.Cog):
await ctx.send(e) await ctx.send(e)
return return
elif channel.permissions_for(user).speak is False: elif channel.permissions_for(user).speak is False:
await ctx.send(_("That user is already muted in {}!").format(channel.name)) await ctx.send(
_("That user is already muted in {channel}!").format(channel=channel.name)
)
return return
else: else:
await ctx.send(_("That user is not in a voice channel right now!")) await ctx.send(_("That user is not in a voice channel right now!"))
@ -908,10 +932,10 @@ class Mod(commands.Cog):
guild = ctx.guild guild = ctx.guild
if reason is None: if reason is None:
audit_reason = "Channel mute requested by {} (ID {})".format(author, author.id) audit_reason = "Channel mute requested by {a} (ID {a.id})".format(a=author)
else: else:
audit_reason = "Channel mute requested by {} (ID {}). Reason: {}".format( audit_reason = "Channel mute requested by {a} (ID {a.id}). Reason: {r}".format(
author, author.id, reason a=author, r=reason
) )
success, issue = await self.mute_user(guild, channel, author, user, audit_reason) success, issue = await self.mute_user(guild, channel, author, user, audit_reason)
@ -944,11 +968,13 @@ class Mod(commands.Cog):
guild = ctx.guild guild = ctx.guild
user_voice_state = user.voice user_voice_state = user.voice
if reason is None: if reason is None:
audit_reason = "server mute requested by {} (ID {})".format(author, author.id) audit_reason = "server mute requested by {author} (ID {author.id})".format(
else: author=author
audit_reason = "server mute requested by {} (ID {}). Reason: {}".format(
author, author.id, reason
) )
else:
audit_reason = (
"server mute requested by {author} (ID {author.id}). Reason: {reason}"
).format(author=author, reason=reason)
mute_success = [] mute_success = []
for channel in guild.channels: for channel in guild.channels: