This commit is contained in:
Romain J 2021-03-31 18:08:41 +02:00
parent 3525b9aa4b
commit f0dc682047
22 changed files with 81 additions and 51 deletions

View file

@ -13,7 +13,9 @@ disable=
C0115, # missing-class-docstring C0115, # missing-class-docstring
C0116, # missing-function-docstring C0116, # missing-function-docstring
W0703, # broad-except W0703, # broad-except
W0707, # raise-missing-from
R0801, # duplicate-code R0801, # duplicate-code
R0901, # too-many-ancestors
R0902, # too-many-instance-attributes R0902, # too-many-instance-attributes
R0903, # too-few-public-methods R0903, # too-few-public-methods
E1136, # unsubscriptable-object (false positive with python 3.9) E1136, # unsubscriptable-object (false positive with python 3.9)

View file

@ -52,7 +52,18 @@ docker-start:
# Blackify code # Blackify code
.PHONY: black .PHONY: black
black: black:
$(PYTHON_PATH) -m black `git ls-files "*.py"` --line-length=79 && $(PYTHON_PATH) -m pylint tuxbot $(PYTHON_PATH) -m black `git ls-files "*.py"` --line-length=79
.PHONY: lint
lint:
$(PYTHON_PATH) -m pylint tuxbot
.PHONY: type
type:
$(PYTHON_PATH) -m mypy tuxbot
.PHONY: style
style: black lint type
# Translations # Translations
.PHONY: xgettext .PHONY: xgettext

View file

@ -110,9 +110,7 @@ def parse_cli_flags(args: list) -> Namespace:
"--token", "-T", type=str, help="Run Tuxbot with passed token" "--token", "-T", type=str, help="Run Tuxbot with passed token"
) )
args = parser.parse_args(args) return parser.parse_args(args)
return args
async def shutdown_handler(tux: Tux, signal_type, exit_code=None) -> None: async def shutdown_handler(tux: Tux, signal_type, exit_code=None) -> None:

View file

@ -1,3 +1,5 @@
from typing import Dict
from structured_config import Structure from structured_config import Structure
HAS_MODELS = True HAS_MODELS = True
@ -7,4 +9,4 @@ class AdminConfig(Structure):
pass pass
extra = {} extra: Dict[str, Dict] = {}

View file

@ -1,3 +1,5 @@
from typing import Dict
from structured_config import Structure from structured_config import Structure
HAS_MODELS = False HAS_MODELS = False
@ -7,4 +9,4 @@ class CryptoConfig(Structure):
pass pass
extra = {} extra: Dict[str, Dict] = {}

View file

@ -12,8 +12,8 @@ async def extract(
kwargs = data_parser(data) kwargs = data_parser(data)
if len(attachments) > 0: if attachments and attachments[0]:
file = attachments[0] file: Attachment = attachments[0]
if file.size > max_size: if file.size > max_size:
raise ValueError raise ValueError

View file

@ -3,7 +3,10 @@ import re
def data_parser(data: str) -> dict: def data_parser(data: str) -> dict:
output = { output = {
"message": None, "message": "",
"compressed": False,
"graphical": False,
"chars": tuple(),
} }
if not data: if not data:
@ -22,8 +25,8 @@ def data_parser(data: str) -> dict:
if "--chars" in data: if "--chars" in data:
regex = r"--chars=(\S\S)" regex = r"--chars=(\S\S)"
match = re.search(regex, data)
if match := re.search(regex, data):
output["chars"] = tuple(match.group()[-2:]) output["chars"] = tuple(match.group()[-2:])
data = "".join(data.rsplit(match.group(), 1)) data = "".join(data.rsplit(match.group(), 1))

View file

@ -1,3 +1,5 @@
from typing import Dict
from structured_config import Structure from structured_config import Structure
HAS_MODELS = False HAS_MODELS = False
@ -7,4 +9,4 @@ class CustomConfig(Structure):
pass pass
extra = {} extra: Dict[str, Dict] = {}

View file

@ -0,0 +1 @@
# pylint: disable=cyclic-import

View file

@ -1,3 +1,5 @@
from typing import Dict
from structured_config import Structure from structured_config import Structure
HAS_MODELS = False HAS_MODELS = False
@ -7,4 +9,4 @@ class DevConfig(Structure):
pass pass
extra = {} extra: Dict[str, Dict] = {}

View file

@ -1,3 +1,5 @@
from typing import Dict
from structured_config import Structure, StrField from structured_config import Structure, StrField
HAS_MODELS = False HAS_MODELS = False
@ -12,7 +14,7 @@ class LogsConfig(Structure):
sentryKey: str = StrField("") sentryKey: str = StrField("")
extra = { extra: Dict[str, Dict] = {
"dm": { "dm": {
"type": str, "type": str,
"description": "URL of the webhook used for send DMs " "description": "URL of the webhook used for send DMs "

View file

@ -1,4 +1,5 @@
from collections import Counter from collections import Counter
from typing import Dict
def sort_by(_events: Counter) -> dict[str, dict]: def sort_by(_events: Counter) -> dict[str, dict]:
@ -12,7 +13,7 @@ def sort_by(_events: Counter) -> dict[str, dict]:
"voice", "voice",
"other", "other",
] ]
sorted_events = {m: {} for m in majors} sorted_events: Dict[str, Dict] = {m: {} for m in majors}
for event, count in _events: for event, count in _events:
done = False done = False

View file

@ -1,3 +1,5 @@
from typing import Dict
from structured_config import Structure, StrField from structured_config import Structure, StrField
HAS_MODELS = False HAS_MODELS = False
@ -7,7 +9,7 @@ class NetworkConfig(Structure):
ipinfoKey: str = StrField("") ipinfoKey: str = StrField("")
extra = { extra: Dict[str, Dict] = {
"ipinfoKey": { "ipinfoKey": {
"type": str, "type": str,
"description": "API Key for ipinfo.io (.iplocalise command)", "description": "API Key for ipinfo.io (.iplocalise command)",

View file

@ -1,13 +1,5 @@
import re
from discord.ext import commands from discord.ext import commands
from tuxbot.cogs.Network.functions.exceptions import (
InvalidIp,
InvalidDomain,
InvalidQueryType,
)
def _(x): def _(x):
return x return x

View file

@ -23,15 +23,15 @@ def _(x):
async def get_ip(ip: str, inet: str = "", tmp: discord.Message = None) -> str: async def get_ip(ip: str, inet: str = "", tmp: discord.Message = None) -> str:
_inet: Union[socket.AddressFamily, int] = 0 # pylint: disable=no-member
if inet == "6": if inet == "6":
inet = socket.AF_INET6 _inet = socket.AF_INET6
elif inet == "4": elif inet == "4":
inet = socket.AF_INET _inet = socket.AF_INET
else:
inet = 0
try: try:
return socket.getaddrinfo(str(ip), None, inet)[1][4][0] return socket.getaddrinfo(str(ip), None, _inet)[1][4][0]
except socket.gaierror as e: except socket.gaierror as e:
if tmp: if tmp:
await tmp.delete() await tmp.delete()

View file

@ -1,3 +1,5 @@
from typing import Dict
from structured_config import Structure from structured_config import Structure
HAS_MODELS = True HAS_MODELS = True
@ -7,4 +9,4 @@ class PollsConfig(Structure):
pass pass
extra = {} extra: Dict[str, Dict] = {}

View file

@ -49,8 +49,10 @@ async def _suggest_reaction_add(
or (await self.bot.is_owner(discord.Object(pld.user_id))) or (await self.bot.is_owner(discord.Object(pld.user_id)))
or ( or (
(channel := await self.bot.fetch_channel(pld.channel_id)) (channel := await self.bot.fetch_channel(pld.channel_id))
.permissions_for(await channel.guild.fetch_member(pld.user_id)) # pylint: disable=used-before-assignment
.administrator .permissions_for(
await channel.guild.fetch_member(pld.user_id)
).administrator
) )
): ):

View file

@ -13,7 +13,8 @@ class Poll(tortoise.Model):
available_choices = fields.IntField() available_choices = fields.IntField()
choices: fields.ManyToManyRelation["Response"] = fields.ManyToManyField( # noinspection PyUnresolvedReferences
choices: fields.ManyToManyRelation["Response"] = fields.ManyToManyField( # type: ignore
"models.Response", related_name="choices" "models.Response", related_name="choices"
) )

View file

@ -1,3 +1,5 @@
from typing import Dict
from structured_config import Structure from structured_config import Structure
HAS_MODELS = False HAS_MODELS = False
@ -7,4 +9,4 @@ class UtilsConfig(Structure):
pass pass
extra = {} extra: Dict[str, Dict] = {}

View file

@ -1,7 +1,7 @@
import logging import logging
import os import os
from pathlib import Path from pathlib import Path
from typing import Callable, Union, Dict, List from typing import Union, Dict, List, NoReturn, Any
from babel.messages.pofile import read_po from babel.messages.pofile import read_po
@ -19,7 +19,7 @@ available_locales: Dict[str, List[str]] = {
} }
def find_locale(locale: str) -> str: def find_locale(locale: str) -> Union[str, NoReturn]:
"""We suppose `locale` is in `_available_locales.values()`""" """We suppose `locale` is in `_available_locales.values()`"""
for key, val in available_locales.items(): for key, val in available_locales.items():
@ -40,10 +40,10 @@ def list_locales() -> str:
def get_locale_name(locale: str) -> str: def get_locale_name(locale: str) -> str:
"""Return the name of this `locale`""" """Return the name of this `locale`"""
return available_locales.get(find_locale(locale))[0] return available_locales[find_locale(locale)][0]
class Translator(Callable[[str], str]): class Translator:
"""Class to load texts at init.""" """Class to load texts at init."""
def __init__(self, name: str, file_location: Union[Path, os.PathLike]): def __init__(self, name: str, file_location: Union[Path, os.PathLike]):
@ -59,7 +59,7 @@ class Translator(Callable[[str], str]):
""" """
self.cog_folder = Path(file_location).resolve().parent self.cog_folder = Path(file_location).resolve().parent
self.cog_name = name self.cog_name = name
self.translations = {} self.translations: Dict[str, Any] = {}
_translators.append(self) _translators.append(self)

View file

@ -1,5 +1,6 @@
import asyncio import asyncio
import functools import functools
from typing import Dict
import aiohttp import aiohttp
from discord.ext import commands from discord.ext import commands
@ -27,7 +28,7 @@ def typing(func):
async def shorten(session, text: str, length: int) -> dict: async def shorten(session, text: str, length: int) -> dict:
output = {"text": text[:length], "link": None} output: Dict[str, str] = {"text": text[:length], "link": ""}
if len(text) > length: if len(text) > length:
output["text"] += "[...]" output["text"] += "[...]"
@ -51,7 +52,7 @@ def replace_in_dict(value: dict, search: str, replace: str) -> dict:
for k, v in value.items(): for k, v in value.items():
if isinstance(v, (str, bytes)): if isinstance(v, (str, bytes)):
v = v.replace(search, replace) v = v.replace(search, replace) # type: ignore
elif isinstance(v, list): elif isinstance(v, list):
v = replace_in_list(v, search, replace) v = replace_in_list(v, search, replace)
elif isinstance(v, dict): elif isinstance(v, dict):
@ -67,7 +68,7 @@ def replace_in_list(value: list, search: str, replace: str) -> list:
for v in value: for v in value:
if isinstance(v, (str, bytes)): if isinstance(v, (str, bytes)):
v = v.replace(search, replace) v = v.replace(search, replace) # type: ignore
elif isinstance(v, list): elif isinstance(v, list):
v = replace_in_list(v, search, replace) v = replace_in_list(v, search, replace)
elif isinstance(v, dict): elif isinstance(v, dict):

View file

@ -138,7 +138,9 @@ def get_multiple(
List[Union[str, int]] List[Union[str, int]]
List containing user filled values. List containing user filled values.
""" """
prompt = IntPrompt if value_type is int else Prompt prompt: Union[IntPrompt, Prompt] = (
IntPrompt() if value_type is int else Prompt()
)
user_input = prompt.ask(question, console=console) user_input = prompt.ask(question, console=console)
@ -167,11 +169,13 @@ def get_multiple(
def get_extra(question: str, value_type: type) -> Union[str, int]: def get_extra(question: str, value_type: type) -> Union[str, int]:
prompt = IntPrompt if value_type is int else Prompt prompt: Union[IntPrompt, Prompt] = (
IntPrompt() if value_type is int else Prompt()
)
return prompt.ask(question, console=console) return prompt.ask(question, console=console)
def additional_config(cogs: str = "**"): def additional_config(cogs: Union[str, list] = "**"):
"""Asking for additional configs in cogs. """Asking for additional configs in cogs.
Returns Returns
@ -185,7 +189,7 @@ def additional_config(cogs: str = "**"):
cogs = sum(cogs, []) cogs = sum(cogs, [])
if len(cogs) == 0: if len(cogs) == 0:
paths = Path("tuxbot/cogs").glob("**/config.py") paths = list(Path("tuxbot/cogs").glob("**/config.py"))
else: else:
paths = [Path(f"tuxbot/cogs/{cog}/config.py") for cog in cogs] paths = [Path(f"tuxbot/cogs/{cog}/config.py") for cog in cogs]
@ -195,7 +199,7 @@ def additional_config(cogs: str = "**"):
console.print(Rule(f"\nConfiguration for `{cog_name}` module")) console.print(Rule(f"\nConfiguration for `{cog_name}` module"))
mod = importlib.import_module(str(path).replace("/", ".")[:-3]) mod = importlib.import_module(str(path).replace("/", ".")[:-3])
mod_config_type = getattr(mod, cog_name.capitalize() + "Config") mod_config_type = getattr(mod, cog_name.capitalize() + "Config")
mod_extra = mod.extra mod_extra = getattr(mod, "extra")
mod_config = config.ConfigFile( mod_config = config.ConfigFile(
str(cogs_data_path(cog_name) / "config.yaml"), str(cogs_data_path(cog_name) / "config.yaml"),
@ -362,9 +366,7 @@ def parse_cli_flags(args: list) -> Namespace:
help="Check for update", help="Check for update",
) )
args = parser.parse_args(args) return parser.parse_args(args)
return args
def setup() -> None: def setup() -> None: