Massive refactor of pretty much everything in the bot

This commit is contained in:
Ske
2018-07-24 22:47:57 +02:00
parent 086fa84b4b
commit 8936029dc8
27 changed files with 1799 additions and 1450 deletions

View File

@@ -0,0 +1,98 @@
import logging
from collections import namedtuple
import asyncpg
import discord
import pluralkit
from pluralkit import db
from pluralkit.bot import utils
command_list = {}
class InvalidCommandSyntax(Exception):
pass
class NoSystemRegistered(Exception):
pass
class CommandError(Exception):
def __init__(self, message):
self.message = message
class CommandContext(namedtuple("CommandContext", ["client", "conn", "message", "system"])):
client: discord.Client
conn: asyncpg.Connection
message: discord.Message
system: pluralkit.System
async def reply(self, message=None, embed=None):
return await self.client.send_message(self.message.channel, message, embed=embed)
class MemberCommandContext(namedtuple("MemberCommandContext", CommandContext._fields + ("member",)), CommandContext):
client: discord.Client
conn: asyncpg.Connection
message: discord.Message
system: pluralkit.System
member: pluralkit.Member
class CommandEntry(namedtuple("CommandEntry", ["command", "function", "usage", "description", "category"])):
pass
def command(cmd, usage=None, description=None, category=None, system_required=True):
def wrap(func):
async def wrapper(client, conn, message, args):
system = await db.get_system_by_account(conn, message.author.id)
if system_required and system is None:
await client.send_message(message.channel, embed=utils.make_error_embed("No system registered to this account"))
return
ctx = CommandContext(client=client, conn=conn, message=message, system=system)
try:
res = await func(ctx, args)
if res:
embed = res if isinstance(res, discord.Embed) else utils.make_default_embed(res)
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"))
except InvalidCommandSyntax:
usage_str = "**Usage:** pk;{} {}".format(cmd, usage or "")
await client.send_message(message.channel, embed=utils.make_default_embed(usage_str))
except CommandError as e:
embed = e.message if isinstance(e.message, discord.Embed) else utils.make_error_embed(e.message)
await client.send_message(message.channel, embed=embed)
# Put command in map
command_list[cmd] = CommandEntry(command=cmd, function=wrapper, usage=usage, description=description, category=category)
return wrapper
return wrap
def member_command(cmd, usage=None, description=None, category=None, system_only=True):
def wrap(func):
async def wrapper(ctx: CommandContext, args):
# Return if no member param
if len(args) == 0:
raise InvalidCommandSyntax()
# System is allowed to be none if not system_only
system_id = ctx.system.id if ctx.system else None
# And find member by key
member = await utils.get_member_fuzzy(ctx.conn, system_id=system_id, key=args[0], system_only=system_only)
if member is None:
raise CommandError("Can't find member \"{}\".".format(args[0]))
ctx = MemberCommandContext(client=ctx.client, conn=ctx.conn, message=ctx.message, system=ctx.system, member=member)
return await func(ctx, args[1:])
return command(cmd=cmd, usage="<name|id> {}".format(usage or ""), description=description, category=category, system_required=False)(wrapper)
return wrap
import pluralkit.bot.commands.import_commands
import pluralkit.bot.commands.member_commands
import pluralkit.bot.commands.message_commands
import pluralkit.bot.commands.misc_commands
import pluralkit.bot.commands.mod_commands
import pluralkit.bot.commands.switch_commands
import pluralkit.bot.commands.system_commands

View File

@@ -0,0 +1,143 @@
import asyncio
import re
from datetime import datetime
import logging
from typing import List
from pluralkit.bot import utils
from pluralkit.bot.commands import *
logger = logging.getLogger("pluralkit.commands")
@command(cmd="import tupperware", description="Import data from Tupperware.")
async def import_tupperware(ctx: CommandContext, args: List[str]):
tupperware_member = ctx.message.server.get_member("431544605209788416") or ctx.message.server.get_member("433916057053560832")
if not tupperware_member:
raise CommandError("This command only works in a server where the Tupperware bot is also present.")
channel_permissions = ctx.message.channel.permissions_for(tupperware_member)
if not (channel_permissions.read_messages and channel_permissions.send_messages):
raise CommandError("This command only works in a channel where the Tupperware bot has read/send access.")
await ctx.reply(embed=utils.make_default_embed("Please reply to this message with `tul!list` (or the server equivalent)."))
# Check to make sure the Tupperware response actually belongs to the correct user
def ensure_account(tw_msg):
if not tw_msg.embeds:
return False
if not tw_msg.embeds[0]["title"]:
return False
return tw_msg.embeds[0]["title"].startswith("{}#{}".format(ctx.message.author.name, ctx.message.author.discriminator))
embeds = []
tw_msg: discord.Message = await ctx.client.wait_for_message(author=tupperware_member, channel=ctx.message.channel, timeout=60.0, check=ensure_account)
if not tw_msg:
raise CommandError("Tupperware import timed out.")
embeds.append(tw_msg.embeds[0])
# Handle Tupperware pagination
def match_pagination():
pagination_match = re.search(r"\(page (\d+)/(\d+), \d+ total\)", tw_msg.embeds[0]["title"])
if not pagination_match:
return None
return int(pagination_match.group(1)), int(pagination_match.group(2))
pagination_match = match_pagination()
if pagination_match:
status_msg = await ctx.reply("Multi-page member list found. Please manually scroll through all the pages.")
current_page = 0
total_pages = 1
pages_found = {}
# Keep trying to read the embed with new pages
last_found_time = datetime.utcnow()
while len(pages_found) < total_pages:
new_page, total_pages = match_pagination()
# Put the found page in the pages dict
pages_found[new_page] = dict(tw_msg.embeds[0])
# If this isn't the same page as last check, edit the status message
if new_page != current_page:
last_found_time = datetime.utcnow()
await ctx.client.edit_message(status_msg, "Multi-page member list found. Please manually scroll through all the pages. Read {}/{} pages.".format(len(pages_found), total_pages))
current_page = new_page
# And sleep a bit to prevent spamming the CPU
await asyncio.sleep(0.25)
# Make sure it doesn't spin here for too long, time out after 30 seconds since last new page
if (datetime.utcnow() - last_found_time).seconds > 30:
raise CommandError("Pagination scan timed out.")
# Now that we've got all the pages, put them in the embeds list
# Make sure to erase the original one we put in above too
embeds = list([embed for page, embed in sorted(pages_found.items(), key=lambda x: x[0])])
# Also edit the status message to indicate we're now importing, and it may take a while because there's probably a lot of members
await ctx.client.edit_message(status_msg, "All pages read. Now importing...")
logger.debug("Importing from Tupperware...")
# Create new (nameless) system if there isn't any registered
system = ctx.system
if system is None:
hid = utils.generate_hid()
logger.debug("Creating new system (hid={})...".format(hid))
system = await db.create_system(ctx.conn, system_name=None, system_hid=hid)
await db.link_account(ctx.conn, system_id=system["id"], account_id=ctx.message.author.id)
for embed in embeds:
for field in embed["fields"]:
name = field["name"]
lines = field["value"].split("\n")
member_prefix = None
member_suffix = None
member_avatar = None
member_birthdate = None
member_description = None
# Read the message format line by line
for line in lines:
if line.startswith("Brackets:"):
brackets = line[len("Brackets: "):]
member_prefix = brackets[:brackets.index("text")].strip() or None
member_suffix = brackets[brackets.index("text")+4:].strip() or None
elif line.startswith("Avatar URL: "):
url = line[len("Avatar URL: "):]
member_avatar = url
elif line.startswith("Birthday: "):
bday_str = line[len("Birthday: "):]
bday = datetime.strptime(bday_str, "%a %b %d %Y")
if bday:
member_birthdate = bday.date()
elif line.startswith("Total messages sent: ") or line.startswith("Tag: "):
# Ignore this, just so it doesn't catch as the description
pass
else:
member_description = line
# Read by name - TW doesn't allow name collisions so we're safe here (prevents dupes)
existing_member = await db.get_member_by_name(ctx.conn, system_id=system.id, member_name=name)
if not existing_member:
# Or create a new member
hid = utils.generate_hid()
logger.debug("Creating new member {} (hid={})...".format(name, hid))
existing_member = await db.create_member(ctx.conn, system_id=system.id, member_name=name, member_hid=hid)
# Save the new stuff in the DB
logger.debug("Updating fields...")
await db.update_member_field(ctx.conn, member_id=existing_member.id, field="prefix", value=member_prefix)
await db.update_member_field(ctx.conn, member_id=existing_member.id, field="suffix", value=member_suffix)
await db.update_member_field(ctx.conn, member_id=existing_member.id, field="avatar_url", value=member_avatar)
await db.update_member_field(ctx.conn, member_id=existing_member.id, field="birthday", value=member_birthdate)
await db.update_member_field(ctx.conn, member_id=existing_member.id, field="description", value=member_description)
return "System information imported. Try using `pk;system` now.\nYou should probably remove your members from Tupperware to avoid double-posting."

View File

@@ -0,0 +1,150 @@
import logging
import re
from datetime import datetime
from typing import List
from urllib.parse import urlparse
from pluralkit.bot import utils
from pluralkit.bot.commands import *
logger = logging.getLogger("pluralkit.commands")
@member_command(cmd="member", description="Shows information about a system member.", system_only=False, category="Member commands")
async def member_info(ctx: MemberCommandContext, args: List[str]):
await ctx.reply(embed=await utils.generate_member_info_card(ctx.conn, ctx.member))
@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()
name = " ".join(args)
bounds_error = utils.bounds_check_member_name(name, ctx.system.tag)
if bounds_error:
raise CommandError(bounds_error)
# TODO: figure out what to do if this errors out on collision on generate_hid
hid = utils.generate_hid()
# Insert member row
await db.create_member(ctx.conn, system_id=ctx.system.id, member_name=name, member_hid=hid)
return "Member \"{}\" (`{}`) registered!".format(name, hid)
@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()
allowed_properties = ["name", "description", "color", "pronouns", "birthdate", "avatar"]
db_properties = {
"name": "name",
"description": "description",
"color": "color",
"pronouns": "pronouns",
"birthdate": "birthday",
"avatar": "avatar_url"
}
prop = args[0]
if prop not in allowed_properties:
raise CommandError("Unknown property {}. Allowed properties are {}.".format(prop, ", ".join(allowed_properties)))
if len(args) >= 2:
value = " ".join(args[1:])
# Sanity/validity checks and type conversions
if prop == "name":
bounds_error = utils.bounds_check_member_name(value, ctx.system.tag)
if bounds_error:
raise CommandError(bounds_error)
if prop == "color":
match = re.fullmatch("#?([0-9A-Fa-f]{6})", value)
if not match:
raise CommandError("Color must be a valid hex color (eg. #ff0000)")
value = match.group(1).lower()
if prop == "birthdate":
try:
value = datetime.strptime(value, "%Y-%m-%d").date()
except ValueError:
try:
# Try again, adding 0001 as a placeholder year
# This is considered a "null year" and will be omitted from the info card
# Useful if you want your birthday to be displayed yearless.
value = datetime.strptime("0001-" + value, "%Y-%m-%d").date()
except ValueError:
raise CommandError("Invalid date. Date must be in ISO-8601 format (eg. 1999-07-25).")
if prop == "avatar":
user = await utils.parse_mention(ctx.client, value)
if user:
# Set the avatar to the mentioned user's avatar
# Discord doesn't like webp, but also hosts png alternatives
value = user.avatar_url.replace(".webp", ".png")
else:
# Validate URL
u = urlparse(value)
if u.scheme in ["http", "https"] and u.netloc and u.path:
value = value
else:
raise CommandError("Invalid URL.")
else:
# Can't clear member name
if prop == "name":
raise CommandError("Can't clear member name.")
# Clear from DB
value = None
db_prop = db_properties[prop]
await db.update_member_field(ctx.conn, member_id=ctx.member.id, field=db_prop, value=value)
response = utils.make_default_embed("{} {}'s {}.".format("Updated" if value else "Cleared", ctx.member.name, prop))
if prop == "avatar" and value:
response.set_image(url=value)
if prop == "color" and value:
response.colour = int(value, 16)
return response
@member_command(cmd="member proxy", usage="[example]", description="Updates a member's proxy settings. Needs an \"example\" proxied message containing the string \"text\" (eg. [text], |text|, etc).", category="Member commands")
async def member_proxy(ctx: MemberCommandContext, args: List[str]):
if len(args) == 0:
prefix, suffix = None, None
else:
# Sanity checking
example = " ".join(args)
if "text" not in example:
raise CommandError("Example proxy message must contain the string 'text'.")
if example.count("text") != 1:
raise CommandError("Example proxy message must contain the string 'text' exactly once.")
# Extract prefix and suffix
prefix = example[:example.index("text")].strip()
suffix = example[example.index("text")+4:].strip()
logger.debug("Matched prefix '{}' and suffix '{}'".format(prefix, suffix))
# DB stores empty strings as None, make that work
if not prefix:
prefix = None
if not suffix:
suffix = None
async with ctx.conn.transaction():
await db.update_member_field(ctx.conn, member_id=ctx.member.id, field="prefix", value=prefix)
await db.update_member_field(ctx.conn, member_id=ctx.member.id, field="suffix", value=suffix)
return "Proxy settings updated." if prefix or suffix else "Proxy settings cleared."
@member_command("member delete", description="Deletes a member from your system ***permanently***.", category="Member commands")
async def member_delete(ctx: MemberCommandContext, args: List[str]):
await ctx.reply("Are you sure you want to delete {}? If so, reply to this message with the member's ID (`{}`).".format(ctx.member.name, ctx.member.hid))
msg = await ctx.client.wait_for_message(author=ctx.message.author, channel=ctx.message.channel, timeout=60.0)
if msg and msg.content == ctx.member.hid:
await db.delete_member(ctx.conn, member_id=ctx.member.id)
return "Member deleted."
else:
return "Member deletion cancelled."

View File

@@ -0,0 +1,57 @@
import logging
from typing import List
from pluralkit.bot import utils
from pluralkit.bot.commands import *
logger = logging.getLogger("pluralkit.commands")
@command(cmd="message", usage="<id>", description="Shows information about a proxied message. Requires the message ID.",
category="Message commands")
async def message_info(ctx: CommandContext, args: List[str]):
if len(args) == 0:
raise InvalidCommandSyntax()
try:
mid = int(args[0])
except ValueError:
raise InvalidCommandSyntax()
# Find the message in the DB
message = await db.get_message(ctx.conn, str(mid))
if not message:
raise CommandError("Message not found.")
# Get the original sender of the messages
try:
original_sender = await ctx.client.get_user_info(str(message.sender))
except discord.NotFound:
# Account was since deleted - rare but we're handling it anyway
original_sender = None
embed = discord.Embed()
embed.timestamp = discord.utils.snowflake_time(str(mid))
embed.colour = discord.Colour.blue()
if message.system_name:
system_value = "{} (`{}`)".format(message.system_name, message.system_hid)
else:
system_value = "`{}`".format(message.system_hid)
embed.add_field(name="System", value=system_value)
embed.add_field(name="Member", value="{} (`{}`)".format(message.name, message.hid))
if original_sender:
sender_name = "{}#{}".format(original_sender.name, original_sender.discriminator)
else:
sender_name = "(deleted account {})".format(message.sender)
embed.add_field(name="Sent by", value=sender_name)
if message.content: # Content can be empty string if there's an attachment
embed.add_field(name="Content", value=message.content, inline=False)
embed.set_author(name=message.name, icon_url=message.avatar_url or discord.Embed.Empty)
return embed

View File

@@ -0,0 +1,89 @@
import io
import json
import logging
import os
from typing import List
from discord.utils import oauth_url
from pluralkit.bot import utils
from pluralkit.bot.commands import *
logger = logging.getLogger("pluralkit.commands")
@command(cmd="help", usage="[system|member|proxy|switch|mod]", description="Shows help messages.")
async def show_help(ctx: CommandContext, args: List[str]):
embed = utils.make_default_embed("")
embed.title = "PluralKit Help"
embed.set_footer(text="By Astrid (Ske#6201, or 'qoxvy' on PK) | GitHub: https://github.com/xSke/PluralKit/")
category = args[0] if len(args) > 0 else None
from pluralkit.bot.help import help_pages
if category in help_pages:
for name, text in help_pages[category]:
if name:
embed.add_field(name=name, value=text)
else:
embed.description = text
else:
raise InvalidCommandSyntax()
return embed
@command(cmd="invite", description="Generates an invite link for this bot.")
async def invite_link(ctx: CommandContext, args: List[str]):
client_id = os.environ["CLIENT_ID"]
permissions = discord.Permissions()
permissions.manage_webhooks = True
permissions.send_messages = True
permissions.manage_messages = True
permissions.embed_links = True
permissions.attach_files = True
permissions.read_message_history = True
permissions.add_reactions = True
url = oauth_url(client_id, permissions)
logger.debug("Sending invite URL: {}".format(url))
return url
@command(cmd="export", description="Exports system data to a machine-readable format.")
async def export(ctx: CommandContext, args: List[str]):
members = await db.get_all_members(ctx.conn, ctx.system.id)
accounts = await db.get_linked_accounts(ctx.conn, ctx.system.id)
switches = await utils.get_front_history(ctx.conn, ctx.system.id, 999999)
system = ctx.system
data = {
"name": system.name,
"id": system.hid,
"description": system.description,
"tag": system.tag,
"avatar_url": system.avatar_url,
"created": system.created.isoformat(),
"members": [
{
"name": member.name,
"id": member.hid,
"color": member.color,
"avatar_url": member.avatar_url,
"birthday": member.birthday.isoformat() if member.birthday else None,
"pronouns": member.pronouns,
"description": member.description,
"prefix": member.prefix,
"suffix": member.suffix,
"created": member.created.isoformat()
} for member in members
],
"accounts": [str(uid) for uid in accounts],
"switches": [
{
"timestamp": timestamp.isoformat(),
"members": [member.hid for member in members]
} for timestamp, members in switches
]
}
f = io.BytesIO(json.dumps(data).encode("utf-8"))
await ctx.client.send_file(ctx.message.channel, f, filename="system.json")

View File

@@ -0,0 +1,24 @@
import logging
from typing import List
from pluralkit.bot import utils
from pluralkit.bot.commands import *
logger = logging.getLogger("pluralkit.commands")
@command(cmd="mod log", usage="[channel]", description="Sets the bot to log events to a specified channel. Leave blank to disable.", category="Moderation commands")
async def set_log(ctx: CommandContext, args: List[str]):
if not ctx.message.author.server_permissions.administrator:
raise CommandError("You must be a server administrator to use this command.")
server = ctx.message.server
if len(args) == 0:
channel_id = None
else:
channel = utils.parse_channel_mention(args[0], server=server)
if not channel:
raise CommandError("Channel not found.")
channel_id = channel.id
await db.update_server(ctx.conn, server.id, logging_channel_id=channel_id)
return "Updated logging channel." if channel_id else "Cleared logging channel."

View File

@@ -0,0 +1,119 @@
from datetime import datetime
import logging
from typing import List
import dateparser
import humanize
from pluralkit import Member
from pluralkit.bot import utils
from pluralkit.bot.commands import *
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()
members: List[Member] = []
for member_name in args:
# Find the member
member = await utils.get_member_fuzzy(ctx.conn, ctx.system.id, member_name)
if not member:
raise CommandError("Couldn't find member \"{}\".".format(member_name))
members.append(member)
# Compare requested switch IDs and existing fronter IDs to check for existing switches
# Lists, because order matters, it makes sense to just swap fronters
member_ids = [member.id for member in members]
fronter_ids = (await utils.get_fronter_ids(ctx.conn, ctx.system.id))[0]
if member_ids == fronter_ids:
if len(members) == 1:
raise CommandError("{} is already fronting.".format(members[0].name))
raise CommandError("Members {} are already fronting.".format(", ".join([m.name for m in members])))
# Also make sure there aren't any duplicates
if len(set(member_ids)) != len(member_ids):
raise CommandError("Duplicate members in switch list.")
# Log the switch
async with ctx.conn.transaction():
switch_id = await db.add_switch(ctx.conn, system_id=ctx.system.id)
for member in members:
await db.add_switch_member(ctx.conn, switch_id=switch_id, member_id=member.id)
if len(members) == 1:
return "Switch registered. Current fronter is now {}.".format(members[0].name)
else:
return "Switch registered. Current fronters are now {}.".format(", ".join([m.name for m in members]))
@command(cmd="switch out", description="Registers a switch with no one in front.", category="Switching commands")
async def switch_out(ctx: MemberCommandContext, args: List[str]):
# Get current fronters
fronters, _ = await utils.get_fronter_ids(ctx.conn, system_id=ctx.system.id)
if not fronters:
raise CommandError("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)
return "Switch-out registered."
@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()
# Parse the time to move to
new_time = dateparser.parse(" ".join(args), languages=["en"], settings={
"TO_TIMEZONE": "UTC",
"RETURN_AS_TIMEZONE_AWARE": False
})
if not new_time:
raise CommandError("{} can't be parsed as a valid time.".format(" ".join(args)))
# Make sure the time isn't in the future
if new_time > datetime.now():
raise CommandError("Can't move switch to a time in the future.")
# Make sure it all runs in a big transaction for atomicity
async with ctx.conn.transaction():
# Get the last two switches to make sure the switch to move isn't before the second-last switch
last_two_switches = await utils.get_front_history(ctx.conn, ctx.system.id, count=2)
if len(last_two_switches) == 0:
raise CommandError("There are no registered switches for this system.")
last_timestamp, last_fronters = last_two_switches[0]
if len(last_two_switches) > 1:
second_last_timestamp, _ = last_two_switches[1]
if new_time < second_last_timestamp:
time_str = humanize.naturaltime(second_last_timestamp)
raise CommandError("Can't move switch to before last switch time ({}), as it would cause conflicts.".format(time_str))
# Display the confirmation message w/ humanized times
members = ", ".join([member.name for member in last_fronters]) or "nobody"
last_absolute = last_timestamp.isoformat(sep=" ", timespec="seconds")
last_relative = humanize.naturaltime(last_timestamp)
new_absolute = new_time.isoformat(sep=" ", timespec="seconds")
new_relative = humanize.naturaltime(new_time)
embed = utils.make_default_embed("This will move the latest switch ({}) from {} ({}) to {} ({}). Is this OK?".format(members, last_absolute, last_relative, new_absolute, new_relative))
# Await and handle confirmation reactions
confirm_msg = await ctx.reply(embed=embed)
await ctx.client.add_reaction(confirm_msg, "")
await ctx.client.add_reaction(confirm_msg, "")
reaction = await ctx.client.wait_for_reaction(emoji=["", ""], message=confirm_msg, user=ctx.message.author, timeout=60.0)
if not reaction:
raise CommandError("Switch move timed out.")
if reaction.reaction.emoji == "":
raise CommandError("Switch move cancelled.")
# DB requires the actual switch ID which our utility method above doesn't return, do this manually
switch_id = (await db.front_history(ctx.conn, ctx.system.id, count=1))[0]["id"]
# Change the switch in the DB
await db.move_last_switch(ctx.conn, ctx.system.id, switch_id, new_time)
return "Switch moved."

View File

@@ -0,0 +1,215 @@
import logging
from typing import List
from urllib.parse import urlparse
import humanize
from pluralkit.bot import utils
from pluralkit.bot.commands import *
logger = logging.getLogger("pluralkit.commands")
@command(cmd="system", usage="[system]", description="Shows information about a system.", category="System commands", system_required=False)
async def system_info(ctx: CommandContext, args: List[str]):
if len(args) == 0:
if not ctx.system:
raise NoSystemRegistered()
system = ctx.system
else:
# Look one up
system = await utils.get_system_fuzzy(ctx.conn, ctx.client, args[0])
if system is None:
raise CommandError("Unable to find system \"{}\".".format(args[0]))
await ctx.reply(embed=await utils.generate_system_info_card(ctx.conn, ctx.client, system))
@command(cmd="system new", usage="[name]", description="Registers a new system to this account.", category="System commands", system_required=False)
async def new_system(ctx: CommandContext, args: List[str]):
if ctx.system:
raise CommandError("You already have a system registered. To delete your system, use `pk;system delete`, or to unlink your system from this account, use `pk;system unlink`.")
system_name = None
if len(args) > 0:
system_name = " ".join(args)
async with ctx.conn.transaction():
# TODO: figure out what to do if this errors out on collision on generate_hid
hid = utils.generate_hid()
system = await db.create_system(ctx.conn, system_name=system_name, system_hid=hid)
# Link account
await db.link_account(ctx.conn, system_id=system.id, account_id=ctx.message.author.id)
return "System registered! To begin adding members, use `pk;member new <name>`."
@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()
allowed_properties = ["name", "description", "tag", "avatar"]
db_properties = {
"name": "name",
"description": "description",
"tag": "tag",
"avatar": "avatar_url"
}
prop = args[0]
if prop not in allowed_properties:
raise CommandError("Unknown property {}. Allowed properties are {}.".format(prop, ", ".join(allowed_properties)))
if len(args) >= 2:
value = " ".join(args[1:])
# Sanity checking
if prop == "tag":
if len(value) > 32:
raise CommandError("Can't have 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)
if len(members_exceeding) > 0:
# If so, error out and warn
member_names = ", ".join([member.name
for member in members_exceeding])
logger.debug("Members exceeding combined length with tag '{}': {}".format(value, member_names))
raise CommandError("The maximum length of a name plus the system tag is 32 characters. The following members would exceed the limit: {}. Please reduce the length of the tag, or rename the members.".format(member_names))
if prop == "avatar":
user = await utils.parse_mention(ctx.client, value)
if user:
# Set the avatar to the mentioned user's avatar
# Discord doesn't like webp, but also hosts png alternatives
value = user.avatar_url.replace(".webp", ".png")
else:
# Validate URL
u = urlparse(value)
if u.scheme in ["http", "https"] and u.netloc and u.path:
value = value
else:
raise CommandError("Invalid URL.")
else:
# Clear from DB
value = None
db_prop = db_properties[prop]
await db.update_system_field(ctx.conn, system_id=ctx.system.id, field=db_prop, value=value)
response = utils.make_default_embed("{} system {}.".format("Updated" if value else "Cleared", prop))
if prop == "avatar" and value:
response.set_image(url=value)
return response
@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()
# Find account to link
linkee = await utils.parse_mention(ctx.client, args[0])
if not linkee:
raise CommandError("Account not found.")
# Make sure account doesn't already have a system
account_system = await db.get_system_by_account(ctx.conn, linkee.id)
if account_system:
raise CommandError("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))
await ctx.client.add_reaction(msg, "")
await ctx.client.add_reaction(msg, "")
reaction = await ctx.client.wait_for_reaction(emoji=["", ""], message=msg, user=linkee, timeout=60.0)
# If account to be linked confirms...
if not reaction:
raise CommandError("Account link timed out.")
if not reaction.reaction.emoji == "":
raise CommandError("Account link cancelled.")
await db.link_account(ctx.conn, system_id=ctx.system.id, account_id=linkee.id)
return "Account linked to system."
@command(cmd="system unlink", description="Unlinks your system from this account. There must be at least one other account linked.", category="System commands")
async def system_unlink(ctx: CommandContext, args: List[str]):
# Make sure you can't unlink every account
linked_accounts = await db.get_linked_accounts(ctx.conn, system_id=ctx.system.id)
if len(linked_accounts) == 1:
raise CommandError("This is the only account on your system, so you can't unlink it.")
await db.unlink_account(ctx.conn, system_id=ctx.system.id, account_id=ctx.message.author.id)
return "Account unlinked."
@command(cmd="system fronter", usage="[system]", description="Gets the current fronter(s) in the system.", category="Switching commands", system_required=False)
async def system_fronter(ctx: CommandContext, args: List[str]):
if len(args) == 0:
if not ctx.system:
raise NoSystemRegistered()
else:
system = await utils.get_system_fuzzy(ctx.conn, ctx.client, args[0])
if system is None:
raise CommandError("Can't find system \"{}\".".format(args[0]))
fronters, timestamp = await utils.get_fronters(ctx.conn, system_id=ctx.system.id)
fronter_names = [member.name for member in fronters]
embed = utils.make_default_embed(None)
if len(fronter_names) == 0:
embed.add_field(name="Current fronter", value="(no fronter)")
elif len(fronter_names) == 1:
embed.add_field(name="Current fronter", value=fronter_names[0])
else:
embed.add_field(name="Current fronters", value=", ".join(fronter_names))
if timestamp:
embed.add_field(name="Since", value="{} ({})".format(timestamp.isoformat(sep=" ", timespec="seconds"), humanize.naturaltime(timestamp)))
return embed
@command(cmd="system fronthistory", usage="[system]", description="Shows the past 10 switches in the system.", category="Switching commands", system_required=False)
async def system_fronthistory(ctx: CommandContext, args: List[str]):
if len(args) == 0:
if not ctx.system:
raise NoSystemRegistered()
else:
system = await utils.get_system_fuzzy(ctx.conn, ctx.client, args[0])
if system is None:
raise CommandError("Can't find system \"{}\".".format(args[0]))
lines = []
front_history = await utils.get_front_history(ctx.conn, ctx.system.id, count=10)
for i, (timestamp, members) in enumerate(front_history):
# Special case when no one's fronting
if len(members) == 0:
name = "(no fronter)"
else:
name = ", ".join([member.name for member in members])
# Make proper date string
time_text = timestamp.isoformat(sep=" ", timespec="seconds")
rel_text = humanize.naturaltime(timestamp)
delta_text = ""
if i > 0:
last_switch_time = front_history[i-1][0]
delta_text = ", for {}".format(humanize.naturaldelta(timestamp - last_switch_time))
lines.append("**{}** ({}, {}{})".format(name, time_text, rel_text, delta_text))
embed = utils.make_default_embed("\n".join(lines) or "(none)")
embed.title = "Past switches"
return embed
@command(cmd="system delete", description="Deletes your system from the database ***permanently***.", category="System commands")
async def system_delete(ctx: CommandContext, args: List[str]):
await ctx.reply("Are you sure you want to delete your system? If so, reply to this message with the system's ID (`{}`).".format(ctx.system.hid))
msg = await ctx.client.wait_for_message(author=ctx.message.author, channel=ctx.message.channel, timeout=60.0)
if msg and msg.content == ctx.system.hid:
await db.remove_system(ctx.conn, system_id=ctx.system.id)
return "System deleted."
else:
return "System deletion cancelled."