Files
qrm2/exts/base.py
T

254 lines
9.9 KiB
Python
Raw Normal View History

2019-10-04 13:10:27 -04:00
"""
Base extension for qrm
2019-10-04 13:10:27 -04:00
---
2020-01-06 23:27:48 -05:00
Copyright (C) 2019-2020 Abigail Gold, 0x5c
2019-10-04 18:05:57 -04:00
This file is part of qrm2 and is released under the terms of
2020-01-31 06:50:50 -05:00
the GNU General Public License, version 2.
2019-10-04 13:10:27 -04:00
"""
2020-01-08 02:19:35 -05:00
import random
import re
2020-01-08 02:19:35 -05:00
from typing import Union
2021-01-25 17:25:26 -05:00
import pathlib
2019-10-04 13:10:27 -04:00
import discord
import discord.ext.commands as commands
2019-12-06 01:19:42 -05:00
import info
2020-01-08 02:19:35 -05:00
import common as cmn
2019-12-06 01:19:42 -05:00
class QrmHelpCommand(commands.HelpCommand):
def __init__(self):
2020-01-30 06:15:42 -05:00
super().__init__(command_attrs={"help": "Shows help about qrm or a command", "aliases": ["h"]})
self.verify_checks = True
2021-03-13 17:48:18 -05:00
self.context: commands.Context
2019-12-06 01:19:42 -05:00
async def get_bot_mapping(self):
2019-12-06 01:19:42 -05:00
bot = self.context.bot
mapping = {}
for cmd in await self.filter_commands(bot.commands, sort=True):
2020-01-30 06:15:42 -05:00
cat = cmd.__original_kwargs__.get("category", None)
2019-12-06 01:19:42 -05:00
if cat in mapping:
mapping[cat].append(cmd)
else:
mapping[cat] = [cmd]
return mapping
async def get_command_signature(self, command):
2019-12-06 01:19:42 -05:00
parent = command.full_parent_name
if command.aliases != []:
2020-01-30 06:15:42 -05:00
aliases = ", ".join(command.aliases)
2019-12-06 01:19:42 -05:00
fmt = command.name
if parent:
2020-01-30 06:15:42 -05:00
fmt = f"{parent} {fmt}"
2019-12-06 01:19:42 -05:00
alias = fmt
2021-03-13 17:48:18 -05:00
return f"{self.context.prefix}{alias} {command.signature}\n *Aliases:* {aliases}"
2020-01-30 06:15:42 -05:00
alias = command.name if not parent else f"{parent} {command.name}"
2021-03-13 17:48:18 -05:00
return f"{self.context.prefix}{alias} {command.signature}"
2019-12-06 01:19:42 -05:00
async def send_error_message(self, error):
2019-12-16 03:49:34 -05:00
embed = cmn.embed_factory(self.context)
2020-01-30 06:15:42 -05:00
embed.title = "qrm Help Error"
2019-12-16 03:49:34 -05:00
embed.description = error
embed.colour = cmn.colours.bad
2019-12-06 01:19:42 -05:00
await self.context.send(embed=embed)
async def send_bot_help(self, mapping):
2019-12-16 03:49:34 -05:00
embed = cmn.embed_factory(self.context)
2020-01-30 06:15:42 -05:00
embed.title = "qrm Help"
2021-03-13 17:48:18 -05:00
embed.description = (f"For command-specific help and usage, use `{self.context.prefix}help [command name]`."
2020-01-30 06:15:42 -05:00
" Many commands have shorter aliases.")
2021-03-13 18:16:58 -05:00
if isinstance(self.context.bot.command_prefix, list):
embed.description += (" All of the following prefixes work with the bot: `"
+ "`, `".join(self.context.bot.command_prefix) + "`.")
mapping = await mapping
2019-12-06 01:19:42 -05:00
for cat, cmds in mapping.items():
if cmds == []:
continue
names = sorted([cmd.name for cmd in cmds])
if cat is not None:
2020-01-30 06:15:42 -05:00
embed.add_field(name=cat.title(), value=", ".join(names), inline=False)
2019-12-06 01:19:42 -05:00
else:
2020-01-30 06:15:42 -05:00
embed.add_field(name="Other", value=", ".join(names), inline=False)
2019-12-06 01:19:42 -05:00
await self.context.send(embed=embed)
async def send_command_help(self, command):
if self.verify_checks:
if not await command.can_run(self.context):
raise commands.CheckFailure
for p in command.parents:
if not await p.can_run(self.context):
raise commands.CheckFailure
embed = cmn.embed_factory(self.context)
embed.title = await self.get_command_signature(command)
embed.description = command.help
await self.context.send(embed=embed)
2019-12-06 01:19:42 -05:00
async def send_group_help(self, group):
if self.verify_checks and not await group.can_run(self.context):
raise commands.CheckFailure
embed = cmn.embed_factory(self.context)
embed.title = await self.get_command_signature(group)
embed.description = group.help
for cmd in await self.filter_commands(group.commands, sort=True):
embed.add_field(name=await self.get_command_signature(cmd), value=cmd.help, inline=False)
await self.context.send(embed=embed)
2019-12-06 01:19:42 -05:00
2019-10-04 13:10:27 -04:00
2019-10-04 18:16:47 -04:00
class BaseCog(commands.Cog):
def __init__(self, bot: commands.Bot):
2019-10-04 13:10:27 -04:00
self.bot = bot
2019-11-06 00:44:39 -05:00
self.changelog = parse_changelog()
2021-01-25 17:25:26 -05:00
commit_file = pathlib.Path("git_commit")
dot_git = pathlib.Path(".git")
if commit_file.is_file():
with commit_file.open() as f:
self.commit = f.readline().strip()[:7]
elif dot_git.is_dir():
head_file = pathlib.Path(dot_git, "HEAD")
if head_file.is_file():
with head_file.open() as hf:
head = hf.readline().split(": ")[1].strip()
branch_file = pathlib.Path(dot_git, head)
if branch_file.is_file():
with branch_file.open() as bf:
self.commit = bf.readline().strip()[:7]
else:
self.commit = ""
2019-10-04 13:10:27 -04:00
@commands.command(name="info", aliases=["about"])
2019-12-06 01:19:42 -05:00
async def _info(self, ctx: commands.Context):
2019-10-04 13:10:27 -04:00
"""Shows info about qrm."""
2019-12-16 03:49:34 -05:00
embed = cmn.embed_factory(ctx)
embed.title = "About qrm"
embed.description = info.description
embed.add_field(name="Authors", value=", ".join(info.authors))
embed.add_field(name="License", value=info.license)
2021-01-25 17:25:26 -05:00
embed.add_field(name="Version", value=f"v{info.release} {'(`' + self.commit + '`)' if self.commit else ''}")
embed.add_field(name="Contributing", value=info.contributing, inline=False)
2019-12-24 21:04:59 -05:00
embed.add_field(name="Official Server", value=info.bot_server, inline=False)
2019-11-11 21:13:43 -05:00
embed.set_thumbnail(url=str(self.bot.user.avatar_url))
2019-10-04 13:10:27 -04:00
await ctx.send(embed=embed)
2020-01-30 06:15:42 -05:00
@commands.command(name="ping", aliases=["beep"])
async def _ping(self, ctx: commands.Context):
2020-02-15 04:59:25 -05:00
"""Shows the current latency to the discord endpoint."""
2019-12-16 03:49:34 -05:00
embed = cmn.embed_factory(ctx)
2020-01-30 06:15:42 -05:00
content = ""
2020-01-04 01:40:17 -05:00
if ctx.invoked_with == "beep":
embed.title = "**Boop!**"
else:
2020-01-30 06:15:42 -05:00
content = ctx.message.author.mention if random.random() < 0.05 else ""
2020-01-04 01:40:17 -05:00
embed.title = "🏓 **Pong!**"
2020-01-30 06:15:42 -05:00
embed.description = f"Current ping is {self.bot.latency*1000:.1f} ms"
2020-01-04 01:40:17 -05:00
await ctx.send(content, embed=embed)
2019-10-04 19:45:59 -04:00
@commands.command(name="changelog", aliases=["clog"])
2020-01-30 06:15:42 -05:00
async def _changelog(self, ctx: commands.Context, version: str = "latest"):
2020-02-15 04:59:25 -05:00
"""Shows what has changed in a bot version. Defaults to the latest version."""
2019-12-16 03:49:34 -05:00
embed = cmn.embed_factory(ctx)
embed.title = "qrm Changelog"
embed.description = ("For a full listing, visit [Github](https://"
"github.com/miaowware/qrm2/blob/master/CHANGELOG.md).")
2019-11-06 00:44:39 -05:00
changelog = self.changelog
vers = list(changelog.keys())
vers.remove("Unreleased")
version = version.lower()
2020-01-30 06:15:42 -05:00
if version == "latest":
version = info.release
2020-01-30 06:15:42 -05:00
if version == "unreleased":
version = "Unreleased"
try:
log = changelog[version]
except KeyError:
embed.title += ": Version Not Found"
2020-01-30 06:15:42 -05:00
embed.description += "\n\n**Valid versions:** latest, "
embed.description += ", ".join(vers)
embed.colour = cmn.colours.bad
await ctx.send(embed=embed)
return
2020-01-30 06:15:42 -05:00
if "date" in log:
embed.description += f"\n\n**v{version}** ({log['date']})"
else:
2020-01-30 06:15:42 -05:00
embed.description += f"\n\n**v{version}**"
embed = await format_changelog(log, embed)
await ctx.send(embed=embed)
2020-01-04 01:49:37 -05:00
@commands.command(name="issue")
async def _issue(self, ctx: commands.Context):
2020-02-15 04:59:25 -05:00
"""Shows how to create a bug report or feature request about the bot."""
2020-01-04 01:49:37 -05:00
embed = cmn.embed_factory(ctx)
embed.title = "Found a bug? Have a feature request?"
embed.description = """Submit an issue on the [issue tracker](https://github.com/miaowware/qrm2/issues)!
All issues and requests related to resources (including maps, band charts, data) \
should be added in \
[miaowware/qrm-resources](https://github.com/miaowware/qrm-resources/issues)."""
2020-01-04 01:49:37 -05:00
await ctx.send(embed=embed)
@commands.command(name="echo", aliases=["e"], category=cmn.cat.admin)
@commands.check(cmn.check_if_owner)
2020-01-08 02:19:35 -05:00
async def _echo(self, ctx: commands.Context,
channel: Union[cmn.GlobalChannelConverter, commands.UserConverter], *, msg: str):
2020-02-15 04:59:25 -05:00
"""Sends a message in a channel as qrm. Accepts channel/user IDs/mentions.
2020-01-08 02:19:35 -05:00
Channel names are current-guild only.
Does not work with the ID of the bot user."""
if isinstance(channel, discord.ClientUser):
raise commands.BadArgument("Can't send to the bot user!")
await channel.send(msg)
2019-11-06 00:44:39 -05:00
def parse_changelog():
changelog = {}
2020-01-30 06:15:42 -05:00
ver = ""
heading = ""
2020-01-30 06:15:42 -05:00
with open("CHANGELOG.md") as changelog_file:
for line in changelog_file.readlines():
2020-01-30 06:15:42 -05:00
if line.strip() == "":
continue
2020-01-30 06:15:42 -05:00
if re.match(r"##[^#]", line):
ver_match = re.match(r"\[(.+)\](?: - )?(\d{4}-\d{2}-\d{2})?", line.lstrip("#").strip())
if ver_match is not None:
ver = ver_match.group(1)
changelog[ver] = dict()
if ver_match.group(2):
2020-01-30 06:15:42 -05:00
changelog[ver]["date"] = ver_match.group(2)
elif re.match(r"###[^#]", line):
heading = line.lstrip("#").strip()
changelog[ver][heading] = []
2020-01-30 06:15:42 -05:00
elif ver != "" and heading != "":
if line.startswith("-"):
changelog[ver][heading].append(line.lstrip("-").strip())
return changelog
async def format_changelog(log: dict, embed: discord.Embed):
for header, lines in log.items():
2020-01-30 06:15:42 -05:00
formatted = ""
if header != "date":
for line in lines:
2020-01-30 06:15:42 -05:00
formatted += f"- {line}\n"
embed.add_field(name=f"**{header}**", value=formatted, inline=False)
return embed
2019-10-04 19:45:59 -04:00
def setup(bot: commands.Bot):
2019-10-04 18:16:47 -04:00
bot.add_cog(BaseCog(bot))
2019-12-06 01:19:42 -05:00
bot._original_help_command = bot.help_command
bot.help_command = QrmHelpCommand()
def teardown(bot: commands.Bot):
bot.help_command = bot._original_help_command