新增模块

This commit is contained in:
xtaodada 2021-07-25 16:38:21 +08:00
parent 6f187e654b
commit 862d01a475
No known key found for this signature in database
GPG Key ID: EE4DC37B55E24736
7 changed files with 192 additions and 8 deletions

View File

@ -9,6 +9,7 @@
# API Bot Token # API Bot Token
token: "Here" token: "Here"
color: "0x3498db"
# Either debug logging is enabled or not # Either debug logging is enabled or not
debug: "False" debug: "False"

View File

@ -1,10 +1,11 @@
""" PagerMaid initialization. """ """ PagerMaid initialization. """
from subprocess import run, PIPE
import discord import discord
from typing import Dict
from subprocess import run, PIPE
from discord.ext import commands from discord.ext import commands
from os import getcwd from os import getcwd
from distutils2.util import strtobool from distutils.util import strtobool
from yaml import load, FullLoader from yaml import load, FullLoader
from redis import StrictRedis from redis import StrictRedis
from coloredlogs import ColoredFormatter from coloredlogs import ColoredFormatter
@ -14,7 +15,8 @@ persistent_vars = {}
module_dir = __path__[0] module_dir = __path__[0]
working_dir = getcwd() working_dir = getcwd()
config = None config = None
help_messages = {} des_map: Dict[str, str] = {}
par_map: Dict[str, str] = {}
logs = getLogger(__name__) logs = getLogger(__name__)
logging_format = "%(levelname)s [%(asctime)s] [%(name)s] %(message)s" logging_format = "%(levelname)s [%(asctime)s] [%(name)s] %(message)s"
logging_handler = StreamHandler() logging_handler = StreamHandler()
@ -37,6 +39,7 @@ else:
logs.setLevel(INFO) logs.setLevel(INFO)
token = config['token'] token = config['token']
color = int(config['color'], 16)
prefix = config['prefix'] prefix = config['prefix']
game_des = config['game_des'] game_des = config['game_des']
redis_host = config['redis']['host'] redis_host = config['redis']['host']
@ -59,6 +62,20 @@ else:
bot.remove_command('help') 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(): def redis_status():
try: try:
redis.ping() redis.ping()

View File

@ -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))

View File

@ -1,6 +1,9 @@
""" The help module. """
import discord import discord
from pagermaid import prefix
from discord.ext import commands 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): class Help(commands.Cog):
@ -8,10 +11,25 @@ class Help(commands.Cog):
self.bot = bot self.bot = bot
@commands.command() @commands.command()
async def help(self, ctx): async def help(self, context):
embed = discord.Embed(title="帮助菜单", description="以下是 bot 支持的命令列表", color=0xff0000) message = process_command(context)
embed.add_field(name=f"{prefix}help", value="查看此帮助菜单。", inline=True) if len(message.parameters) == 0:
await ctx.send(embed=embed) 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', '<command>')
def setup(bot): def setup(bot):

View File

@ -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))

View File

@ -1,5 +1,6 @@
""" Libraries for python modules. """ """ Libraries for python modules. """
from discord.ext.commands import Context
from emoji import get_emoji_regexp from emoji import get_emoji_regexp
from random import choice from random import choice
from json import load as load_json from json import load as load_json
@ -9,6 +10,13 @@ from asyncio.subprocess import PIPE
from pagermaid import module_dir 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: # def lang(text: str) -> str:
# """ i18n """ # """ i18n """
# result = lang_dict.get(text, text) # result = lang_dict.get(text, text)
@ -68,3 +76,10 @@ def owoify(text):
def clear_emojis(target): def clear_emojis(target):
""" Removes all Emojis from provided string """ """ Removes all Emojis from provided string """
return get_emoji_regexp().sub(u'', target) 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)

View File

@ -3,3 +3,4 @@ emoji>=1.2.0
PyYAML>=5.4.1 PyYAML>=5.4.1
redis>=3.5.3 redis>=3.5.3
coloredlogs>=15.0.1 coloredlogs>=15.0.1
pytz>=2021.1