Remove syntax error exception, add help pages to some errors

This commit is contained in:
Ske 2018-09-02 19:41:14 +02:00
parent 16fc976971
commit 0869f94cdf
7 changed files with 30 additions and 35 deletions

View File

@ -12,9 +12,6 @@ logger = logging.getLogger("pluralkit.bot.commands")
command_list = {}
class InvalidCommandSyntax(Exception):
pass
class NoSystemRegistered(Exception):
pass
@ -55,9 +52,6 @@ def command(cmd, usage=None, description=None, category=None, system_required=Tr
await client.send_message(message.channel, embed=embed)
except NoSystemRegistered:
await client.send_message(message.channel, embed=utils.make_error_embed("No system registered to this account. Use `pk;system new` to register one."))
except InvalidCommandSyntax:
usage_str = "**Usage:** pk;{} {}".format(cmd, usage or "")
await client.send_message(message.channel, embed=utils.make_default_embed(usage_str))
except Exception:
logger.exception("Exception while handling command {} (args={}, system={})".format(cmd, args, system.hid if system else "(none)"))
@ -71,7 +65,7 @@ def member_command(cmd, usage=None, description=None, category=None, system_only
async def wrapper(ctx: CommandContext, args):
# Return if no member param
if len(args) == 0:
raise InvalidCommandSyntax()
return embeds.error("You must pass a member name or ID.")
# System is allowed to be none if not system_only
system_id = ctx.system.id if ctx.system else None

View File

@ -1,11 +1,10 @@
import logging
import re
from datetime import datetime
from typing import List
from urllib.parse import urlparse
from pluralkit.bot import utils, embeds
from pluralkit.bot.commands import *
from pluralkit.bot import help
logger = logging.getLogger("pluralkit.commands")
@ -16,7 +15,7 @@ async def member_info(ctx: MemberCommandContext, args: List[str]):
@command(cmd="member new", usage="<name>", description="Adds a new member to your system.", category="Member commands")
async def new_member(ctx: MemberCommandContext, args: List[str]):
if len(args) == 0:
raise InvalidCommandSyntax()
return embeds.error("You must pass a member name or ID.", help=help.add_member)
name = " ".join(args)
bounds_error = utils.bounds_check_member_name(name, ctx.system.tag)
@ -33,8 +32,8 @@ async def new_member(ctx: MemberCommandContext, args: List[str]):
@member_command(cmd="member set", usage="<name|description|color|pronouns|birthdate|avatar> [value]", description="Edits a member property. Leave [value] blank to clear.", category="Member commands")
async def member_set(ctx: MemberCommandContext, args: List[str]):
if len(args) == 0:
raise InvalidCommandSyntax()
if len(args) == 0:
return embeds.error("You must pass a property name to set.", help=help.edit_member)
allowed_properties = ["name", "description", "color", "pronouns", "birthdate", "avatar"]
db_properties = {
@ -48,7 +47,7 @@ async def member_set(ctx: MemberCommandContext, args: List[str]):
prop = args[0]
if prop not in allowed_properties:
return embeds.error("Unknown property {}. Allowed properties are {}.".format(prop, ", ".join(allowed_properties)))
return embeds.error("Unknown property {}. Allowed properties are {}.".format(prop, ", ".join(allowed_properties)), help=help.edit_member)
if len(args) >= 2:
value = " ".join(args[1:])
@ -90,11 +89,11 @@ async def member_set(ctx: MemberCommandContext, args: List[str]):
if u.scheme in ["http", "https"] and u.netloc and u.path:
value = value
else:
return embeds.error("Invalid URL.")
return embeds.error("Invalid image URL.")
else:
# Can't clear member name
if prop == "name":
return embeds.error("Can't clear member name.")
return embeds.error("You can't clear the member name.")
# Clear from DB
value = None
@ -117,10 +116,10 @@ async def member_proxy(ctx: MemberCommandContext, args: List[str]):
# Sanity checking
example = " ".join(args)
if "text" not in example:
return embeds.error("Example proxy message must contain the string 'text'.")
return embeds.error("Example proxy message must contain the string 'text'.", help=help.member_proxy)
if example.count("text") != 1:
return embeds.error("Example proxy message must contain the string 'text' exactly once.")
return embeds.error("Example proxy message must contain the string 'text' exactly once.", help=help.member_proxy)
# Extract prefix and suffix
prefix = example[:example.index("text")].strip()
@ -147,4 +146,4 @@ async def member_delete(ctx: MemberCommandContext, args: List[str]):
await db.delete_member(ctx.conn, member_id=ctx.member.id)
return embeds.success("Member deleted.")
else:
return embeds.success("Member deletion cancelled.")
return embeds.error("Member deletion cancelled.")

View File

@ -1,7 +1,7 @@
import logging
from typing import List
from pluralkit.bot import utils, embeds
from pluralkit.bot import utils, embeds, help
from pluralkit.bot.commands import *
logger = logging.getLogger("pluralkit.commands")
@ -11,12 +11,12 @@ logger = logging.getLogger("pluralkit.commands")
category="Message commands", system_required=False)
async def message_info(ctx: CommandContext, args: List[str]):
if len(args) == 0:
raise InvalidCommandSyntax()
return embeds.error("You must pass a message ID.", help=help.message_lookup)
try:
mid = int(args[0])
except ValueError:
raise InvalidCommandSyntax()
return embeds.error("You must pass a valid number as a message ID.", help=help.message_lookup)
# Find the message in the DB
message = await db.get_message(ctx.conn, str(mid))

View File

@ -28,7 +28,7 @@ async def show_help(ctx: CommandContext, args: List[str]):
else:
embed.description = text
else:
raise InvalidCommandSyntax()
return embeds.error("Unknown help page '{}'.".format(category))
return embed

View File

@ -7,7 +7,7 @@ import humanize
import pluralkit.utils
from pluralkit import Member
from pluralkit.bot import utils, embeds
from pluralkit.bot import utils, embeds, help
from pluralkit.bot.commands import *
logger = logging.getLogger("pluralkit.commands")
@ -15,7 +15,7 @@ logger = logging.getLogger("pluralkit.commands")
@command(cmd="switch", usage="<name|id> [name|id]...", description="Registers a switch and changes the current fronter.", category="Switching commands")
async def switch_member(ctx: MemberCommandContext, args: List[str]):
if len(args) == 0:
raise InvalidCommandSyntax()
return embeds.error("You must pass at least one member name or ID to register a switch to.", help=help.switch_register)
members: List[Member] = []
for member_name in args:
@ -36,7 +36,7 @@ async def switch_member(ctx: MemberCommandContext, args: List[str]):
# Also make sure there aren't any duplicates
if len(set(member_ids)) != len(member_ids):
return embeds.error("Duplicate members in switch list.")
return embeds.error("Duplicate members in member list.")
# Log the switch
async with ctx.conn.transaction():
@ -54,7 +54,7 @@ async def switch_out(ctx: MemberCommandContext, args: List[str]):
# Get current fronters
fronters, _ = await pluralkit.utils.get_fronter_ids(ctx.conn, system_id=ctx.system.id)
if not fronters:
raise embeds.error("There's already no one in front.")
return embeds.error("There's already no one in front.")
# Log it, and don't log any members
await db.add_switch(ctx.conn, system_id=ctx.system.id)
@ -63,7 +63,7 @@ async def switch_out(ctx: MemberCommandContext, args: List[str]):
@command(cmd="switch move", usage="<time>", description="Moves the most recent switch to a different point in time.", category="Switching commands")
async def switch_move(ctx: MemberCommandContext, args: List[str]):
if len(args) == 0:
raise InvalidCommandSyntax()
return embeds.error("You must pass a time to move the switch to.", help=help.switch_move)
# Parse the time to move to
new_time = dateparser.parse(" ".join(args), languages=["en"], settings={

View File

@ -6,7 +6,7 @@ import dateparser
import humanize
import pluralkit.utils
from pluralkit.bot import embeds
from pluralkit.bot import embeds, help
from pluralkit.bot.commands import *
logger = logging.getLogger("pluralkit.commands")
@ -48,7 +48,7 @@ async def new_system(ctx: CommandContext, args: List[str]):
@command(cmd="system set", usage="<name|description|tag|avatar> [value]", description="Edits a system property. Leave [value] blank to clear.", category="System commands")
async def system_set(ctx: CommandContext, args: List[str]):
if len(args) == 0:
raise InvalidCommandSyntax()
return embeds.error("You must pass a property name to set.", help=help.edit_system)
allowed_properties = ["name", "description", "tag", "avatar"]
db_properties = {
@ -60,14 +60,14 @@ async def system_set(ctx: CommandContext, args: List[str]):
prop = args[0]
if prop not in allowed_properties:
raise embeds.error("Unknown property {}. Allowed properties are {}.".format(prop, ", ".join(allowed_properties)))
raise embeds.error("Unknown property {}. Allowed properties are {}.".format(prop, ", ".join(allowed_properties)), help=help.edit_system)
if len(args) >= 2:
value = " ".join(args[1:])
# Sanity checking
if prop == "tag":
if len(value) > 32:
raise embeds.error("Can't have system tag longer than 32 characters.")
raise embeds.error("You can't have a system tag longer than 32 characters.")
# Make sure there are no members which would make the combined length exceed 32
members_exceeding = await db.get_members_exceeding(ctx.conn, system_id=ctx.system.id, length=32 - len(value) - 1)
@ -90,7 +90,7 @@ async def system_set(ctx: CommandContext, args: List[str]):
if u.scheme in ["http", "https"] and u.netloc and u.path:
value = value
else:
raise embeds.error("Invalid URL.")
raise embeds.error("Invalid image URL.")
else:
# Clear from DB
value = None
@ -106,7 +106,7 @@ async def system_set(ctx: CommandContext, args: List[str]):
@command(cmd="system link", usage="<account>", description="Links another account to your system.", category="System commands")
async def system_link(ctx: CommandContext, args: List[str]):
if len(args) == 0:
raise InvalidCommandSyntax()
return embeds.error("You must pass an account to link this system to.", help=help.link_account)
# Find account to link
linkee = await utils.parse_mention(ctx.client, args[0])
@ -116,7 +116,7 @@ async def system_link(ctx: CommandContext, args: List[str]):
# Make sure account doesn't already have a system
account_system = await db.get_system_by_account(ctx.conn, linkee.id)
if account_system:
return embeds.error("Account is already linked to a system (`{}`)".format(account_system.hid))
return embeds.error("The mentioned account is already linked to a system (`{}`)".format(account_system.hid))
# Send confirmation message
msg = await ctx.reply("{}, please confirm the link by clicking the ✅ reaction on this message.".format(linkee.mention))

View File

@ -65,9 +65,11 @@ For example:
You will need to confirm the deletion.""")
member_proxy = ("Setting up member proxying", """To register a member for proxying, use the `pk;member proxy` command.
You will need to pass an "example proxy" message containing "text", surrounded by the brackets or prefixes you want to select.
For example:
`pk;member proxy John [text]` - Registers John to use [square brackets] as tags.
`pk;member proxy John [text]` - Registers John to use [square brackets] as proxy brackets.
`pk;member proxy John J:text` - Registers John to use the prefix "J:".
After setting proxy tags, you can use them in any message, and they'll be interpreted by the bot and proxied appropriately.""")