[3.4] Improve validation in trivia (#5947) (#6046)

Co-authored-by: Vexed <vex@vexcodes.com>
This commit is contained in:
Jakub Kuczys
2023-04-19 23:13:40 +02:00
committed by GitHub
parent 44f67d792f
commit ad5395fee0
3 changed files with 180 additions and 25 deletions

View File

@@ -4,7 +4,7 @@ import math
import pathlib
from collections import Counter
from typing import Any, Dict, List, Literal
from schema import Schema, Optional, Or, SchemaError
import schema
import io
import yaml
@@ -23,26 +23,11 @@ from .checks import trivia_stop_check
from .converters import finite_float
from .log import LOG
from .session import TriviaSession
from .schema import TRIVIA_LIST_SCHEMA, format_schema_error
__all__ = ("Trivia", "UNIQUE_ID", "InvalidListError", "get_core_lists", "get_list")
UNIQUE_ID = 0xB3C0E453
TRIVIA_LIST_SCHEMA = Schema(
{
Optional("AUTHOR"): str,
Optional("CONFIG"): {
Optional("max_score"): int,
Optional("timeout"): Or(int, float),
Optional("delay"): Or(int, float),
Optional("bot_plays"): bool,
Optional("reveal_answer"): bool,
Optional("payout_multiplier"): Or(int, float),
Optional("use_spoilers"): bool,
},
str: [str, int, bool, float],
}
)
_ = Translator("Trivia", __file__)
@@ -119,7 +104,7 @@ class Trivia(commands.Cog):
@triviaset.command(name="maxscore")
async def triviaset_max_score(self, ctx: commands.Context, score: int):
"""Set the total points required to win."""
if score < 0:
if score <= 0:
await ctx.send(_("Score must be greater than 0."))
return
settings = self.config.guild(ctx.guild)
@@ -292,18 +277,18 @@ class Trivia(commands.Cog):
try:
await self._save_trivia_list(ctx=ctx, attachment=parsedfile)
except yaml.error.MarkedYAMLError as exc:
await ctx.send(_("Invalid syntax: ") + str(exc))
await ctx.send(_("Invalid syntax:\n") + box(str(exc)))
except yaml.error.YAMLError:
await ctx.send(
_("There was an error parsing the trivia list. See logs for more info.")
)
LOG.exception("Custom Trivia file %s failed to upload", parsedfile.filename)
except SchemaError as e:
except schema.SchemaError as exc:
await ctx.send(
_(
"The custom trivia list was not saved."
" The file does not follow the proper data format.\n{schema_error}"
).format(schema_error=box(e))
).format(schema_error=box(format_schema_error(exc)))
)
@commands.is_owner()
@@ -737,8 +722,6 @@ def get_list(path: pathlib.Path) -> Dict[str, Any]:
------
InvalidListError
Parsing of list's YAML file failed.
SchemaError
The list does not adhere to the schema.
"""
with path.open(encoding="utf-8") as file:
try:
@@ -748,6 +731,6 @@ def get_list(path: pathlib.Path) -> Dict[str, Any]:
try:
TRIVIA_LIST_SCHEMA.validate(trivia_dict)
except SchemaError as exc:
except schema.SchemaError as exc:
raise InvalidListError("The list does not adhere to the schema.") from exc
return trivia_dict