feat(commands|Utils): add info command

This commit is contained in:
Romain J 2020-11-09 01:18:55 +01:00
parent 7d588b2dbc
commit d6e9cd6512
42 changed files with 287 additions and 36 deletions

View file

@ -3,5 +3,5 @@
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.8 (tuxbot-bot)" project-jdk-type="Python SDK" />
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9 (tuxbot-bot)" project-jdk-type="Python SDK" />
</project>

View file

@ -6,7 +6,7 @@
<excludeFolder url="file://$MODULE_DIR$/dist" />
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.8 (tuxbot-bot)" jdkType="Python SDK" />
<orderEntry type="jdk" jdkName="Python 3.9 (tuxbot-bot)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">

View file

@ -8,6 +8,7 @@ good-names=
[MASTER]
disable=
C0103, # invalid-name
C0114, # missing-module-docstring
C0115, # missing-class-docstring
C0116, # missing-function-docstring
@ -15,3 +16,4 @@ disable=
R0801, # duplicate-code
R0902, # too-many-instance-attributes
R0903, # too-few-public-methods
E1136, # unsubscriptable-object (false positive with python 3.9)

View file

@ -2,7 +2,7 @@ import os
from collections import namedtuple
build = os.popen("/usr/bin/git rev-parse --short HEAD").read().strip()
info = os.popen('/usr/bin/git log -n 1 -s --format="%s"').read().strip()
info = os.popen('/usr/bin/git log -n 3 -s --format="%s"').read().strip()
VersionInfo = namedtuple(
"VersionInfo", "major minor micro releaselevel build, info"

View file

@ -19,7 +19,7 @@ from tuxbot.core.utils.functions.extra import (
ContextPlus,
)
log = logging.getLogger("tuxbot.cogs.admin")
log = logging.getLogger("tuxbot.cogs.Admin")
_ = Translator("Admin", __file__)

View file

@ -13,10 +13,12 @@ class AliasesModel(tortoise.Model):
table = "aliases"
def __str__(self):
return f"<AliasesModel id={self.id} " \
f"user_id={self.user_id} " \
f"alias='{self.alias}' " \
f"command='{self.command}' " \
f"guild={self.guild}>"
return (
f"<AliasesModel id={self.id} "
f"user_id={self.user_id} "
f"alias='{self.alias}' "
f"command='{self.command}' "
f"guild={self.guild}>"
)
__repr__ = __str__

View file

@ -13,10 +13,12 @@ class WarnsModel(tortoise.Model):
table = "warns"
def __str__(self):
return f"<WarnsModel id={self.id} " \
f"server_id={self.server_id} " \
f"user_id={self.user_id} " \
f"reason='{self.reason}' " \
f"created_at={self.created_at}>"
return (
f"<WarnsModel id={self.id} "
f"server_id={self.server_id} "
f"user_id={self.user_id} "
f"reason='{self.reason}' "
f"created_at={self.created_at}>"
)
__repr__ = __str__

View file

@ -12,12 +12,9 @@ class DevConfig(Structure):
extra = {
"url": {
"type": str,
"description": "URL of the YouTrack instance (without /youtrack/)"
},
"login": {
"type": str,
"description": "Login for YouTrack instance"
"description": "URL of the YouTrack instance (without /youtrack/)",
},
"login": {"type": str, "description": "Login for YouTrack instance"},
"password": {
"type": str,
"description": "Password for YouTrack instance",

View file

@ -12,7 +12,7 @@ from .config import DevConfig
from ...core.utils import checks
from ...core.utils.functions.extra import group_extra, ContextPlus
log = logging.getLogger("tuxbot.cogs.dev")
log = logging.getLogger("tuxbot.cogs.Dev")
_ = Translator("Dev", __file__)
@ -22,17 +22,15 @@ class Dev(commands.Cog, name="Dev"):
def __init__(self, bot: Tux):
self.bot = bot
self.config: DevConfig = ConfigFile(
str(
cogs_data_path(self.bot.instance_name, "dev") / "config.yaml"
),
str(cogs_data_path(self.bot.instance_name, "Dev") / "config.yaml"),
DevConfig,
).config
# pylint: disable=invalid-name
self.yt = YouTrack(
self.config.url.rstrip('/') + '/youtrack/',
self.config.url.rstrip("/") + "/youtrack/",
login=self.config.login,
password=self.config.password
password=self.config.password,
)
@group_extra(name="issue", aliases=["issues"], deletable=True)

View file

@ -24,7 +24,7 @@ from tuxbot.core.utils.functions.extra import (
from tuxbot.core.utils.data_manager import cogs_data_path
from .config import LogsConfig
log = logging.getLogger("tuxbot.cogs.logs")
log = logging.getLogger("tuxbot.cogs.Logs")
_ = Translator("Logs", __file__)
@ -55,7 +55,7 @@ class Logs(commands.Cog, name="Logs"):
self.config: LogsConfig = ConfigFile(
str(
cogs_data_path(self.bot.instance_name, "logs") / "config.yaml"
cogs_data_path(self.bot.instance_name, "Logs") / "config.yaml"
),
LogsConfig,
).config

View file

@ -0,0 +1,19 @@
from collections import namedtuple
from .utils import Utils
from .config import UtilsConfig, HAS_MODELS
from ...core.bot import Tux
VersionInfo = namedtuple("VersionInfo", "major minor micro release_level")
version_info = VersionInfo(major=2, minor=0, micro=0, release_level="alpha")
__version__ = "v{}.{}.{}-{}".format(
version_info.major,
version_info.minor,
version_info.micro,
version_info.release_level,
).replace("\n", "")
def setup(bot: Tux):
bot.add_cog(Utils(bot))

View file

@ -0,0 +1,10 @@
from structured_config import Structure
HAS_MODELS = False
class UtilsConfig(Structure):
pass
extra = {}

View file

@ -0,0 +1,50 @@
import os
import pathlib
def fetch_info():
total_lines = 0
total_python_class = 0
total_python_functions = 0
total_python_coroutines = 0
total_python_comments = 0
file_amount = 0
python_file_amount = 0
for path, _, files in os.walk("."):
for name in files:
file_dir = str(pathlib.PurePath(path, name))
if (
not name.endswith(".py")
and not name.endswith(".po")
and not name.endswith(".json")
) or "env" in file_dir:
continue
file_amount += 1
python_file_amount += 1 if name.endswith(".py") else 0
with open(file_dir, "r", encoding="utf-8") as file:
for line in file.readlines():
line = line.strip()
if line.startswith("class"):
total_python_class += 1
if line.startswith("def"):
total_python_functions += 1
if line.startswith("async def"):
total_python_coroutines += 1
if "#" in line:
total_python_comments += 1
total_lines += 1
return {
"total_lines": total_lines,
"total_python_class": total_python_class,
"total_python_functions": total_python_functions,
"total_python_coroutines": total_python_coroutines,
"total_python_comments": total_python_comments,
"file_amount": file_amount,
"python_file_amount": python_file_amount,
}

View file

@ -0,0 +1,18 @@
# English translations for Tuxbot-bot package.
# Copyright (C) 2020 THE Tuxbot-bot'S COPYRIGHT HOLDER
# This file is distributed under the same license as the Tuxbot-bot package.
# Automatically generated, 2020.
#
msgid ""
msgstr ""
"Project-Id-Version: Tuxbot-bot\n"
"Report-Msgid-Bugs-To: rick@gnous.eu\n"
"POT-Creation-Date: 2020-06-11 19:07+0200\n"
"PO-Revision-Date: 2020-06-10 00:38+0200\n"
"Last-Translator: Automatically generated\n"
"Language-Team: none\n"
"Language: en_US\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

View file

@ -0,0 +1,19 @@
# French translations for Tuxbot-bot package
# Traductions françaises du paquet Tuxbot-bot.
# Copyright (C) 2020 THE Tuxbot-bot'S COPYRIGHT HOLDER
# This file is distributed under the same license as the Tuxbot-bot package.
# Automatically generated, 2020.
#
msgid ""
msgstr ""
"Project-Id-Version: Tuxbot-bot\n"
"Report-Msgid-Bugs-To: rick@gnous.eu\n"
"POT-Creation-Date: 2020-06-11 19:07+0200\n"
"PO-Revision-Date: 2020-06-10 00:38+0200\n"
"Last-Translator: Automatically generated\n"
"Language-Team: none\n"
"Language: fr\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"

View file

@ -0,0 +1,18 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the Tuxbot-bot package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Tuxbot-bot\n"
"Report-Msgid-Bugs-To: rick@gnous.eu\n"
"POT-Creation-Date: 2020-10-21 01:13+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"

View file

115
tuxbot/cogs/Utils/utils.py Normal file
View file

@ -0,0 +1,115 @@
import logging
import platform
import discord
import humanize
import psutil
from discord.ext import commands
from tuxbot import version_info, __version__
from tuxbot.core.utils.functions.extra import command_extra, ContextPlus
from tuxbot.core.bot import Tux
from tuxbot.core.i18n import (
Translator,
)
from .functions.info import fetch_info
log = logging.getLogger("tuxbot.cogs.Utils")
_ = Translator("Utils", __file__)
class Utils(commands.Cog, name="Utils"):
def __init__(self, bot: Tux):
self.bot = bot
@command_extra(name="info", aliases=["about"])
async def _info(self, ctx: ContextPlus):
proc = psutil.Process()
infos = fetch_info()
with proc.oneshot():
mem = proc.memory_full_info()
e = discord.Embed(
title=_("Information about TuxBot", ctx, self.bot.config),
color=0x89C4F9,
)
e.add_field(
name=f"__:busts_in_silhouette: "
f"{_('Development', ctx, self.bot.config)}__",
value="**Romain#5117:** [git](https://git.gnous.eu/Romain)\n"
"**Outout#4039:** [git](https://git.gnous.eu/mael)\n",
inline=True,
)
e.add_field(
name="__<:python:596577462335307777> Python__",
value=f"**python** `{platform.python_version()}`\n"
f"**discord.py** `{discord.__version__}`",
inline=True,
)
e.add_field(
name="__:gear: Usage__",
value=f"**{humanize.naturalsize(mem.rss)}** "
f"{_('physical memory', ctx, self.bot.config)}\n"
f"**{humanize.naturalsize(mem.vms)}** "
f"{_('virtual memory', ctx, self.bot.config)}\n",
inline=True,
)
e.add_field(
name=f"__{_('Servers count', ctx, self.bot.config)}__",
value=str(len(self.bot.guilds)),
inline=True,
)
e.add_field(
name=f"__{_('Channels count', ctx, self.bot.config)}__",
value=str(len(list(self.bot.get_all_channels()))),
inline=True,
)
e.add_field(
name=f"__{_('Members count', ctx, self.bot.config)}__",
value=str(len(list(self.bot.get_all_members()))),
inline=True,
)
e.add_field(
name=f"__:file_folder: "
f"{_('Files', ctx, self.bot.config)}__",
value=f"{infos.get('file_amount')} "
f"*({infos.get('python_file_amount')}"
f" <:python:596577462335307777>)*",
inline=True,
)
e.add_field(
name=f"__¶ {_('Lines', ctx, self.bot.config)}__",
value=f"{infos.get('total_lines')} "
f"*({infos.get('total_python_class')} class,"
f" {infos.get('total_python_functions')} functions,"
f" {infos.get('total_python_coroutines')} coroutines,"
f" {infos.get('total_python_comments')} comments)*",
inline=True,
)
e.add_field(
name=f"__{_('Latest changes', ctx, self.bot.config)}__",
value=version_info.info,
inline=False,
)
e.add_field(
name=f"__:link: {_('Links', ctx, self.bot.config)}__",
value="[tuxbot.gnous.eu](https://tuxbot.gnous.eu/) "
"| [gnous.eu](https://gnous.eu/) "
"| [git](https://git.gnous.eu/gnouseu/tuxbot-bot) "
"| [status](https://status.gnous.eu/check/154250) "
f"| [{_('Invite', ctx, self.bot.config)}]"
f"(https://discordapp.com/oauth2/authorize?client_id="
f"301062143942590465&scope=bot&permissions=268749888)",
inline=False,
)
e.set_footer(
text=f"version: {__version__} • prefix: {ctx.prefix}"
)
await ctx.send(embed=e)

View file

@ -39,9 +39,10 @@ console = Console()
packages: List[str] = [
"jishaku",
"tuxbot.cogs.admin",
"tuxbot.cogs.logs",
"tuxbot.cogs.dev",
"tuxbot.cogs.Admin",
"tuxbot.cogs.Logs",
"tuxbot.cogs.Dev",
"tuxbot.cogs.Utils",
]

View file

@ -36,7 +36,7 @@ def is_mod():
def is_admin():
"""Is the user admin ?"""
"""Is the user Admin ?"""
async def pred(ctx):
if await ctx.bot.is_owner(ctx.author):

View file

@ -26,7 +26,7 @@ def data_path(instance_name: str) -> Path:
def logs_data_path(instance_name: str) -> Path:
"""Return Path for logs.
"""Return Path for Logs.
Parameters
----------
@ -35,9 +35,9 @@ def logs_data_path(instance_name: str) -> Path:
Returns
-------
Path
Generated path for logs files.
Generated path for Logs files.
"""
return data_path(instance_name) / "logs"
return data_path(instance_name) / "Logs"
def cogs_data_path(instance_name: str, cog_name: str = "") -> Path:

View file

@ -21,7 +21,7 @@ def init_logging(level: int, location: pathlib.Path) -> None:
level:int
Level of debug.
location:Path
Where to store logs.
Where to store Logs.
"""
# dpy_logger = logging.getLogger("discord")

View file

@ -131,7 +131,7 @@ def get_data_dir(instance_name: str) -> Path:
console.print("Rerun the process to redo this configuration.")
sys.exit(0)
(data_path_input / "logs").mkdir(parents=True, exist_ok=True)
(data_path_input / "Logs").mkdir(parents=True, exist_ok=True)
return data_path_input