1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 19:44:20 +00:00

Add dnditem command

This commit is contained in:
Steffo 2019-08-26 17:46:12 +02:00
parent 1f13904ee9
commit fcc3bbe111
8 changed files with 93 additions and 8 deletions

View file

@ -17,3 +17,4 @@ werkzeug>=0.15.4
flask>=1.0.3 flask>=1.0.3
markdown2>=2.3.8 markdown2>=2.3.8
mcstatus>=2.2.1 mcstatus>=2.2.1
sortedcontainers>=2.1.0

View file

@ -20,6 +20,7 @@ from .skip import SkipCommand
from .smecds import SmecdsCommand from .smecds import SmecdsCommand
from .summon import SummonCommand from .summon import SummonCommand
from .videochannel import VideochannelCommand from .videochannel import VideochannelCommand
from .dnditem import DnditemCommand
__all__ = [ __all__ = [
"CiaoruoziCommand", "CiaoruoziCommand",
@ -38,5 +39,6 @@ __all__ = [
"SkipCommand", "SkipCommand",
"SmecdsCommand", "SmecdsCommand",
"SummonCommand", "SummonCommand",
"VideochannelCommand" "VideochannelCommand",
"DnditemCommand"
] ]

View file

@ -0,0 +1,72 @@
import typing
import aiohttp
import sortedcontainers
from ..command import Command
from ..commandargs import CommandArgs
from ..commanddata import CommandData
from ..commandinterface import CommandInterface
class DnditemCommand(Command):
name: str = "dnditem"
description: str = "Ottieni informazioni su un oggetto di D&D5e."
syntax = "(nomeoggetto)"
_dnddata: sortedcontainers.SortedKeyList = None
def __init__(self, interface: CommandInterface):
super().__init__(interface)
interface.loop.create_task(self._fetch_dnddata())
async def _fetch_dnddata(self):
async with aiohttp.ClientSession() as session:
async with session.get("https://scaleway.steffo.eu/dnd/items.json") as response:
j = await response.json()
self._dnddata = sortedcontainers.SortedKeyList(j["item"], key=lambda i: i["name"].lower())
def _parse_entry(self, entry):
if isinstance(entry, str):
return entry
elif isinstance(entry, dict):
string = ""
if entry["type"] == "entries":
string += f'[b]{entry.get("name", "")}[/b]\n'
for subentry in entry["entries"]:
string += self._parse_entry(subentry)
elif entry["type"] == "table":
string += "[i][table hidden][/i]"
# for label in entry["colLabels"]:
# string += f"| {label} "
# string += "|"
# for row in entry["rows"]:
# for column in row:
# string += f"| {self._parse_entry(column)} "
# string += "|\n"
elif entry["type"] == "cell":
return self._parse_entry(entry["entry"])
else:
string += "[i][unknown type][/i]"
else:
return "[/i][unknown data][/i]"
return string
async def run(self, args: CommandArgs, data: CommandData) -> None:
if self._dnddata is None:
await data.reply("⚠️ Il database degli oggetti di D&D non è ancora stato scaricato.")
return
search = args.joined().lower()
result = self._dnddata[self._dnddata.bisect_key_left(search)]
string = f'[b]{result["name"]}[/b]\n' \
f'[i]{result["source"]}, page {result["page"]}[/i]\n' \
f'\n' \
f'Type: [b]{result.get("type", "None")}[/b]\n' \
f'Value: [b]{result.get("value", "Priceless")}[/b]\n' \
f'Weight: [b]{result.get("weight", "0")} lb[/b]\n' \
f'Rarity: [b]{result["rarity"] if result["rarity"] != "None" else "Mundane"}[/b]\n' \
f'\n'
for entry in result.get("entries", []):
string += self._parse_entry(entry)
string += "\n\n"
await data.reply(string)

View file

@ -34,9 +34,9 @@ class ReminderCommand(Command):
.all() .all()
) )
for reminder in reminders: for reminder in reminders:
interface.loop.create_task(self.remind(reminder)) interface.loop.create_task(self._remind(reminder))
async def remind(self, reminder): async def _remind(self, reminder):
await sleep_until(reminder.datetime) await sleep_until(reminder.datetime)
if self.interface.name == "telegram": if self.interface.name == "telegram":
chat_id: int = pickle.loads(reminder.interface_data) chat_id: int = pickle.loads(reminder.interface_data)
@ -74,6 +74,6 @@ class ReminderCommand(Command):
interface_data=interface_data, interface_data=interface_data,
datetime=date, datetime=date,
message=reminder_text) message=reminder_text)
self.interface.loop.create_task(self.remind(reminder)) self.interface.loop.create_task(self._remind(reminder))
self.interface.session.add(reminder) self.interface.session.add(reminder)
await asyncify(self.interface.session.commit) await asyncify(self.interface.session.commit)

View file

@ -33,7 +33,8 @@ commands = [
SkipCommand, SkipCommand,
SmecdsCommand, SmecdsCommand,
SummonCommand, SummonCommand,
VideochannelCommand VideochannelCommand,
DnditemCommand
] ]
# noinspection PyUnreachableCode # noinspection PyUnreachableCode

View file

@ -6,8 +6,8 @@ from .safeformat import safeformat
from .classdictjanitor import cdj from .classdictjanitor import cdj
from .sleepuntil import sleep_until from .sleepuntil import sleep_until
from .networkhandler import NetworkHandler from .networkhandler import NetworkHandler
from .formatters import andformat, plusformat, fileformat, ytdldateformat, numberemojiformat from .formatters import andformat, plusformat, fileformat, ytdldateformat, numberemojiformat, splitstring
__all__ = ["asyncify", "safeformat", "cdj", "sleep_until", "plusformat", __all__ = ["asyncify", "safeformat", "cdj", "sleep_until", "plusformat",
"NetworkHandler", "andformat", "plusformat", "fileformat", "ytdldateformat", "numberemojiformat", "NetworkHandler", "andformat", "plusformat", "fileformat", "ytdldateformat", "numberemojiformat",
"telegram_escape", "discord_escape"] "telegram_escape", "discord_escape", "splitstring"]

View file

@ -70,3 +70,11 @@ def numberemojiformat(l: typing.List[str]) -> str:
except IndexError: except IndexError:
result += f"{extra_emoji} {element}\n" result += f"{extra_emoji} {element}\n"
return result return result
def splitstring(s: str, max: int) -> typing.List[str]:
l = []
while s:
l.append(s[:max])
s = s[max:]
return l

View file

@ -28,7 +28,8 @@ setuptools.setup(
"werkzeug>=0.15.4", "werkzeug>=0.15.4",
"flask>=1.0.3", "flask>=1.0.3",
"markdown2>=2.3.8", "markdown2>=2.3.8",
"mcstatus>=2.2.1"], "mcstatus>=2.2.1",
"sortedcontainers>=2.1.0"],
python_requires=">=3.7", python_requires=">=3.7",
classifiers=[ classifiers=[
"Development Status :: 3 - Alpha", "Development Status :: 3 - Alpha",