Compare commits

...

4 Commits

17 changed files with 387 additions and 14 deletions

View File

@ -13,6 +13,8 @@ install-dev:
$(VENV)/bin/pip install -r dev.requirements.txt
update:
$(VENV)/bin/pip install --upgrade --force-reinstall .
update_soft:
$(VENV)/bin/pip install --upgrade .
# Blackify code
reformat:

View File

@ -1,4 +1,4 @@
|image0| |image1| |image2|
|image0| |image1| |image2| |image3|
.. role:: bash(code)
:language: bash
@ -87,4 +87,6 @@ To update the whole bot after a :bash:`git pull`, just execute
.. |image0| image:: https://img.shields.io/badge/python-3.8%20%7C%203.9%20%7C%203.10-%23007ec6
.. |image1| image:: https://img.shields.io/badge/dynamic/json?color=%23dfb317&label=issues&query=%24.open_issues_count&suffix=%20open&url=https%3A%2F%2Fgit.gnous.eu%2Fapi%2Fv1%2Frepos%2FGnousEU%2Ftuxbot-bot%2F
.. |image2| image:: https://img.shields.io/badge/code%20style-black-000000.svg
.. |image2| image:: https://img.shields.io/badge/code%20style-black-000000.svg
.. |image3| image:: https://wakatime.com/badge/github/Rom1-J/tuxbot-bot.svg
:target: https://wakatime.com/badge/github/Rom1-J/tuxbot-bot

View File

@ -11,7 +11,7 @@ from tuxbot.core.i18n import (
Translator,
find_locale,
get_locale_name,
available_locales,
list_locales,
)
from tuxbot.core.utils.functions.extra import (
group_extra,
@ -57,13 +57,9 @@ class Admin(commands.Cog, name="Admin"):
@_lang.command(name="list", aliases=["liste", "all", "view"])
async def _lang_list(self, ctx: ContextPlus):
description = ""
for key, value in available_locales.items():
description += f":flag_{key[-2:].lower()}: {value[0]}\n"
e = discord.Embed(
title=_("List of available locales: ", ctx, self.bot.config),
description=description,
description=list_locales,
color=0x36393E,
)

View File

@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: Tuxbot-bot\n"
"Report-Msgid-Bugs-To: rick@gnous.eu\n"
"POT-Creation-Date: 2020-11-11 16:42+0100\n"
"POT-Creation-Date: 2021-01-19 14:42+0100\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"
@ -22,6 +22,6 @@ msgstr ""
msgid "Locale changed to {lang} successfully"
msgstr ""
#: tuxbot/cogs/Admin/admin.py:65
#: tuxbot/cogs/Admin/admin.py:61
msgid "List of available locales: "
msgstr ""

View File

@ -0,0 +1,19 @@
from collections import namedtuple
from .custom import Custom
from .config import CustomConfig, HAS_MODELS
from ...core.bot import Tux
VersionInfo = namedtuple("VersionInfo", "major minor micro release_level")
version_info = VersionInfo(major=1, 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(Custom(bot))

View File

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

View File

@ -0,0 +1,128 @@
import logging
import discord
from discord.ext import commands
from tuxbot.cogs.Custom.functions.converters import AliasConvertor
from tuxbot.core.bot import Tux
from tuxbot.core.config import set_for_key, search_for
from tuxbot.core.config import Config
from tuxbot.core.i18n import (
Translator,
find_locale,
get_locale_name,
list_locales,
)
from tuxbot.core.utils.functions.extra import (
group_extra,
ContextPlus,
)
log = logging.getLogger("tuxbot.cogs.Custom")
_ = Translator("Custom", __file__)
class Custom(commands.Cog, name="Custom"):
def __init__(self, bot: Tux):
self.bot = bot
async def cog_command_error(self, ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send(
_(
str(error),
ctx,
self.bot.config,
)
)
# =========================================================================
# =========================================================================
async def _save_lang(self, ctx: ContextPlus, lang: str) -> None:
set_for_key(
self.bot.config.Users, ctx.author.id, Config.User, locale=lang
)
async def _get_aliases(self, ctx: ContextPlus) -> dict:
return search_for(self.bot.config.Users, ctx.author.id, "aliases")
async def _save_alias(self, ctx: ContextPlus, alias: dict) -> None:
set_for_key(
self.bot.config.Users, ctx.author.id, Config.User, alias=alias
)
# =========================================================================
# =========================================================================
@group_extra(name="custom", aliases=["perso"], deletable=True)
@commands.guild_only()
async def _custom(self, ctx: ContextPlus):
"""Manage custom settings."""
@_custom.command(name="locale", aliases=["langue", "lang"])
async def _custom_locale(self, ctx: ContextPlus, lang: str):
try:
await self._save_lang(ctx, find_locale(lang.lower()))
await ctx.send(
_(
"Locale changed for you to {lang} successfully",
ctx,
self.bot.config,
).format(lang=f"`{get_locale_name(lang).lower()}`")
)
except NotImplementedError:
e = discord.Embed(
title=_("List of available locales: ", ctx, self.bot.config),
description=list_locales,
color=0x36393E,
)
await ctx.send(embed=e)
@_custom.command(name="alias", aliases=["aliases"])
async def _custom_alias(self, ctx: ContextPlus, *, alias: AliasConvertor):
args = alias.split(" | ")
command = args[0]
alias = args[1]
user_aliases = await self._get_aliases(ctx)
if alias in user_aliases.keys():
return await ctx.send(
_(
"The alias `{alias}` is already defined "
"for the command `{command}`",
ctx,
self.bot.config,
).format(alias=alias, command=user_aliases.get(alias))
)
if command in user_aliases.values():
return await ctx.send(
_(
"There is already an alias for `{command}` "
"which is `{alias}`",
ctx,
self.bot.config,
).format(
command=command,
alias=list(user_aliases.keys())[
list(user_aliases.values()).index(command)
],
)
)
user_aliases[alias] = command
await self._save_alias(ctx, user_aliases)
await ctx.send(
_(
"The alias `{alias}` for the command `{command}` "
"was successfully created",
ctx,
self.bot.config,
).format(alias=alias, command=command)
)

View File

@ -0,0 +1,28 @@
from discord.ext import commands
from jishaku.models import copy_context_with
_ = lambda x: x
class AliasConvertor(commands.Converter):
async def convert(self, ctx, argument):
args = argument.split(" | ")
if len(args) <= 1:
raise commands.BadArgument(
_("Alias must be like `[command] | [alias]`")
)
command_ctx = await copy_context_with(
ctx, content=ctx.prefix + args[0]
)
alias_ctx = await copy_context_with(ctx, content=ctx.prefix + args[1])
if command_ctx.command is None:
raise commands.BadArgument(_("Unknown command"))
if alias_ctx.command is not None:
raise commands.BadArgument(_("Command already exists"))
return argument

View File

@ -0,0 +1,27 @@
# 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: 2021-01-19 14:39+0100\n"
"PO-Revision-Date: 2021-01-19 14:39+0100\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"
#: tuxbot/cogs/Admin/admin.py:50
#, python-brace-format
msgid "Locale changed to {lang} successfully"
msgstr ""
#: tuxbot/cogs/Admin/admin.py:65
msgid "List of available locales: "
msgstr ""

View File

@ -0,0 +1,57 @@
# 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: 2021-01-19 14:39+0100\n"
"PO-Revision-Date: 2021-01-19 14:39+0100\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"
#: tuxbot/cogs/Custom/custom.py:69
#, python-brace-format
msgid "Locale changed for you to {lang} successfully"
msgstr "Langue changée pour vous en {lang} avec succès"
#: tuxbot/cogs/Custom/custom.py:76
msgid "List of available locales: "
msgstr "Liste des langues disponibles: "
#: tuxbot/cogs/Custom/custom.py:95
#, python-brace-format
msgid "The alias `{alias}` is already defined for the command `{command}`"
msgstr "L'alias `{alias}` est déjà défini pour la commande `{command}`"
#: tuxbot/cogs/Custom/custom.py:105
#, python-brace-format
msgid "There is already an alias for `{command}` which is `{alias}`"
msgstr "Il existe déjà un alias pour `{command}`, qui est `{alias}`"
#: tuxbot/cogs/Custom/custom.py:123
#, python-brace-format
msgid "The alias `{alias}` for the command `{command}` was successfully created"
msgstr "L'alias `{alias}` pour la commande `{command}` a été créé avec succès"
#: tuxbot/cogs/Custom/functions/converters.py:14
msgid "Alias must be like `[command] | [alias]`"
msgstr "L'alias doit être comme `[command] | [alias"
#: tuxbot/cogs/Custom/functions/converters.py:23
#, python-brace-format
msgid "Unknown command"
msgstr "Commande inconnue"
#: tuxbot/cogs/Custom/functions/converters.py:26
#, python-brace-format
msgid "Command already exists"
msgstr "La commande existe déjà"

View File

@ -0,0 +1,56 @@
# 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: 2021-01-19 14:42+0100\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"
#: tuxbot/cogs/Custom/custom.py:69
#, python-brace-format
msgid "Locale changed for you to {lang} successfully"
msgstr ""
#: tuxbot/cogs/Custom/custom.py:76
msgid "List of available locales: "
msgstr ""
#: tuxbot/cogs/Custom/custom.py:95
#, python-brace-format
msgid "The alias `{alias}` is already defined for the command `{command}`"
msgstr ""
#: tuxbot/cogs/Custom/custom.py:105
#, python-brace-format
msgid "There is already an alias for `{command}` which is `{alias}`"
msgstr ""
#: tuxbot/cogs/Custom/custom.py:123
#, python-brace-format
msgid "The alias `{alias}` for the command `{command}` was successfully created"
msgstr ""
#: tuxbot/cogs/Custom/functions/converters.py:14
msgid "Alias must be like `[command] | [alias]`"
msgstr ""
#: tuxbot/cogs/Custom/functions/converters.py:23
#, python-brace-format
msgid "Unknown command"
msgstr ""
#: tuxbot/cogs/Custom/functions/converters.py:26
#, python-brace-format
msgid "Command already exists"
msgstr ""

View File

View File

@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: Tuxbot-bot\n"
"Report-Msgid-Bugs-To: rick@gnous.eu\n"
"POT-Creation-Date: 2020-11-11 16:42+0100\n"
"POT-Creation-Date: 2021-01-19 14:42+0100\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"

View File

@ -41,9 +41,10 @@ packages: List[str] = [
"jishaku",
"tuxbot.cogs.Admin",
"tuxbot.cogs.Logs",
"tuxbot.cogs.Dev",
# "tuxbot.cogs.Dev",
"tuxbot.cogs.Utils",
"tuxbot.cogs.Polls",
"tuxbot.cogs.Custom",
]
@ -230,7 +231,7 @@ class Tux(commands.AutoShardedBot):
ctx: ContextPlus = await self.get_context(message)
if ctx is None or ctx.valid is False:
if ctx is None or not ctx.valid:
self.dispatch("message_without_command", message)
else:
if ctx.command in search_for(

View File

@ -33,7 +33,7 @@ class Config(Structure):
blacklisted: bool = BoolField(False)
class User(Structure):
aliases: List[dict] = []
aliases: dict = {}
locale: str = StrField("")
blacklisted: bool = BoolField(False)

View File

@ -29,6 +29,15 @@ def find_locale(locale: str) -> str:
raise NotImplementedError("This locale isn't implemented")
def list_locales() -> str:
description = ""
for key, value in available_locales.items():
description += f":flag_{key[-2:].lower()}: {value[0]}\n"
return description
def get_locale_name(locale: str) -> str:
"""Return the name of this `locale`"""
return available_locales.get(find_locale(locale))[0]

View File

@ -1,11 +1,14 @@
import argparse
import importlib
import json
import logging
import os
import re
import sys
from argparse import Namespace
from pathlib import Path
from typing import Union, List
from urllib.request import urlopen
from rich.prompt import Prompt, IntPrompt
from rich.console import Console
@ -13,6 +16,7 @@ from rich.rule import Rule
from rich.style import Style
from rich.traceback import install
from tuxbot import version_info
from tuxbot.core.config import set_for, set_for_key
from tuxbot.logging import formatter
from tuxbot.core.utils.data_manager import config_dir, app_dir, cogs_data_path
@ -396,6 +400,30 @@ def basic_setup() -> None:
)
def update() -> None:
response = (
urlopen(
"https://api.github.com/repos/Rom1-J/tuxbot-bot/commits/master"
)
.read()
.decode("utf-8")
)
json_response = json.loads(response)
if json_response.get("sha")[:6] == version_info.build:
print(
"Nothing to update, you can run `tuxbot [instance_name]` "
"to start the bot"
)
else:
print(f"Updating to {json_response.get('sha')[:6]}...")
os.popen("/usr/bin/git pull")
print("Done!")
def parse_cli_flags(args: list) -> Namespace:
"""Parser for cli values.
@ -423,6 +451,12 @@ def parse_cli_flags(args: list) -> Namespace:
nargs="+",
help="Execute setup to additional configs",
)
parser.add_argument(
"-U",
"--update",
action="store_true",
help="Check for update",
)
args = parser.parse_args(args)
@ -433,6 +467,10 @@ def setup() -> None:
cli_flags = parse_cli_flags(sys.argv[1:])
try:
if cli_flags.update:
update()
sys.exit()
# Create a new instance.
level = logging.DEBUG
base_logger = logging.getLogger("tuxbot")