diff --git a/config.gen.yml b/config.gen.yml index 9c3b07b..ae63748 100644 --- a/config.gen.yml +++ b/config.gen.yml @@ -9,6 +9,7 @@ # API Bot Token token: "Here" +color: "0x3498db" # Either debug logging is enabled or not debug: "False" diff --git a/pagermaid/__init__.py b/pagermaid/__init__.py index 0f43f39..b86a8f6 100644 --- a/pagermaid/__init__.py +++ b/pagermaid/__init__.py @@ -1,10 +1,11 @@ """ PagerMaid initialization. """ -from subprocess import run, PIPE import discord +from typing import Dict +from subprocess import run, PIPE from discord.ext import commands from os import getcwd -from distutils2.util import strtobool +from distutils.util import strtobool from yaml import load, FullLoader from redis import StrictRedis from coloredlogs import ColoredFormatter @@ -14,7 +15,8 @@ persistent_vars = {} module_dir = __path__[0] working_dir = getcwd() config = None -help_messages = {} +des_map: Dict[str, str] = {} +par_map: Dict[str, str] = {} logs = getLogger(__name__) logging_format = "%(levelname)s [%(asctime)s] [%(name)s] %(message)s" logging_handler = StreamHandler() @@ -37,6 +39,7 @@ else: logs.setLevel(INFO) token = config['token'] +color = int(config['color'], 16) prefix = config['prefix'] game_des = config['game_des'] redis_host = config['redis']['host'] @@ -59,6 +62,20 @@ else: bot.remove_command('help') +def des_handler(cmd: str, des: str) -> None: + global des_map + if des_map.get(cmd) is not None: + return + des_map[cmd] = des + + +def par_handler(cmd: str, par: str) -> None: + global par_map + if par_map.get(cmd) is not None: + return + par_map[cmd] = par + + def redis_status(): try: redis.ping() diff --git a/pagermaid/modules/clock.py b/pagermaid/modules/clock.py new file mode 100644 index 0000000..402ae16 --- /dev/null +++ b/pagermaid/modules/clock.py @@ -0,0 +1,81 @@ +""" This module handles world clock related utility. """ + +from discord.ext import commands +from datetime import datetime +from pytz import country_names, country_timezones, timezone +from pagermaid import des_handler, par_handler +from pagermaid.utils import process_command + + +class Time(commands.Cog): + def __init__(self, bot): + self.bot = bot + + @commands.command() + async def clock(self, context): + """ For querying time. """ + message = process_command(context) + if len(message.parameters) > 1: + await context.reply("出错了呜呜呜 ~ 无效的参数。") + return + if len(message.parameters) == 1: + country = message.arguments.title() + else: + country = 'China' + time_form = "%I:%M %p" + date_form = "%A %d/%m/%y" + if not country: + time_zone = await get_timezone('China') + await context.reply( + f"**北京时间**\n" + f"`{datetime.now(time_zone).strftime(date_form)} " + f"{datetime.now(time_zone).strftime(time_form)}`" + ) + return + + time_zone = await get_timezone(country) + if not time_zone: + await context.reply("出错了呜呜呜 ~ 无效的参数。") + return + + try: + country_name = country_names[country] + except KeyError: + country_name = country + + await context.reply(f"**{country_name} 时间:**\n" + f"`{datetime.now(time_zone).strftime(date_form)} " + f"{datetime.now(time_zone).strftime(time_form)}`") + + +async def get_timezone(target): + """ Returns timezone of the parameter in command. """ + if "(Uk)" in target: + target = target.replace("Uk", "UK") + if "(Us)" in target: + target = target.replace("Us", "US") + if " Of " in target: + target = target.replace(" Of ", " of ") + if "(Western)" in target: + target = target.replace("(Western)", "(western)") + if "Minor Outlying Islands" in target: + target = target.replace("Minor Outlying Islands", "minor outlying islands") + if "Nl" in target: + target = target.replace("Nl", "NL") + + for country_code in country_names: + if target == country_names[country_code]: + return timezone(country_timezones[country_code][0]) + try: + if country_names[target]: + return timezone(country_timezones[target][0]) + except KeyError: + return + + +des_handler('clock', '显示特定区域的时间,如果参数为空,则默认显示中国。') +par_handler('clock', '<地区>') + + +def setup(bot): + bot.add_cog(Time(bot)) diff --git a/pagermaid/modules/help.py b/pagermaid/modules/help.py index f72ece8..65ccd0a 100644 --- a/pagermaid/modules/help.py +++ b/pagermaid/modules/help.py @@ -1,6 +1,9 @@ +""" The help module. """ + import discord -from pagermaid import prefix from discord.ext import commands +from pagermaid import color, prefix, des_handler, par_handler, des_map, par_map +from pagermaid.utils import process_command class Help(commands.Cog): @@ -8,10 +11,25 @@ class Help(commands.Cog): self.bot = bot @commands.command() - async def help(self, ctx): - embed = discord.Embed(title="帮助菜单", description="以下是 bot 支持的命令列表", color=0xff0000) - embed.add_field(name=f"{prefix}help", value="查看此帮助菜单。", inline=True) - await ctx.send(embed=embed) + async def help(self, context): + message = process_command(context) + if len(message.parameters) == 0: + embed = discord.Embed(title="帮助菜单", description="以下是 bot 支持的命令列表", color=color) + for com, des in des_map.items(): + embed.add_field(name=f"{prefix}{com} {par_map[com]}", value=f"{des}", inline=True) + await context.reply(embed=embed) + else: + if message.arguments in des_map: + com = message.arguments + embed = discord.Embed(title="使用帮助", description=f"命令 {com} 帮助", color=color) + embed.add_field(name=f"{prefix}{com} {par_map[com]}", value=f"{des_map[com]}", inline=True) + await context.reply(embed=embed) + else: + await context.reply('您好像输入了一个无效的参数。') + + +des_handler('help', '显示所有命令。') +par_handler('help', '') def setup(bot): diff --git a/pagermaid/modules/system.py b/pagermaid/modules/system.py new file mode 100644 index 0000000..eba8bfb --- /dev/null +++ b/pagermaid/modules/system.py @@ -0,0 +1,51 @@ +""" The system module. """ + +import sys +from platform import uname +import discord +from discord.ext import commands +from subprocess import run, PIPE +from pagermaid import color, des_handler, par_handler, redis_status + + +class Info(commands.Cog): + def __init__(self, bot): + self.bot = bot + + @commands.command() + async def info(self, ctx): + git_hash = run("git rev-parse --short HEAD", stdout=PIPE, shell=True).stdout.decode().strip() + get_hash_link = f"https://github.com/Xtao-Labs/PagerMaid-Discord/commit/{git_hash}" + dpy_repo = "https://github.com/Rapptz/discord.py" + python_url = "https://www.python.org/" + + app_info = await self.bot.application_info() + if app_info.team: + owner = app_info.team.name + else: + owner = app_info.owner + + dpy_version = "[{}]({})".format(discord.__version__, dpy_repo) + python_version = "[{}.{}.{}]({})".format(*sys.version_info[:3], python_url) + git_version = "[{}]({})".format(git_hash, get_hash_link) + database = '在线' if redis_status() else '离线' + + embed = discord.Embed(title="PagerMaid-Discord 运行状态", color=color) + embed.add_field(name="实例创建者", value=str(owner)) + embed.add_field(name="Python", value=python_version) + embed.add_field(name="discord.py", value=dpy_version) + embed.add_field(name="Git commit", value=git_version) + embed.add_field(name="主机名", value=uname().node) + embed.add_field(name="主机平台", value=sys.platform) + embed.add_field(name="Kernel", value=uname().release) + embed.add_field(name="数据库", value=database) + embed.add_field(name="交流群", value='[点击加入](https://discord.gg/A4mWpa83e6)') + await ctx.send(embed=embed) + + +des_handler('info', '查看程序信息。') +par_handler('info', '') + + +def setup(bot): + bot.add_cog(Info(bot)) diff --git a/pagermaid/utils.py b/pagermaid/utils.py index ebaa354..8e03859 100644 --- a/pagermaid/utils.py +++ b/pagermaid/utils.py @@ -1,5 +1,6 @@ """ Libraries for python modules. """ +from discord.ext.commands import Context from emoji import get_emoji_regexp from random import choice from json import load as load_json @@ -9,6 +10,13 @@ from asyncio.subprocess import PIPE from pagermaid import module_dir +class ProcessMessage: + def __init__(self, parameters, text, arguments): + self.parameters = parameters + self.text = text + self.arguments = arguments + + # def lang(text: str) -> str: # """ i18n """ # result = lang_dict.get(text, text) @@ -68,3 +76,10 @@ def owoify(text): def clear_emojis(target): """ Removes all Emojis from provided string """ return get_emoji_regexp().sub(u'', target) + + +def process_command(context: Context): + text = context.message.content + text_list = text.strip().split(' ')[1:] + arguments = ' '.join(text_list) + return ProcessMessage(text_list, text, arguments) diff --git a/requirements.txt b/requirements.txt index 8d56956..0d8504e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,3 +3,4 @@ emoji>=1.2.0 PyYAML>=5.4.1 redis>=3.5.3 coloredlogs>=15.0.1 +pytz>=2021.1