mirror of https://github.com/stijndcl/didier
Custom commands cleanup, remove train for my own sanity
parent
81a0d90a12
commit
a71232e292
|
@ -5,8 +5,6 @@ from data.menus import custom_commands
|
|||
from data.snipe import Action, Snipe
|
||||
from decorators import help
|
||||
from enums.help_categories import Category
|
||||
from functions.database.custom_commands import get_all
|
||||
from functions.stringFormatters import capitalize
|
||||
from startup.didier import Didier
|
||||
|
||||
|
||||
|
@ -14,10 +12,9 @@ class Other(commands.Cog):
|
|||
def __init__(self, client: Didier):
|
||||
self.client: Didier = client
|
||||
|
||||
# TODO add locked field to Didier instead of client
|
||||
# # Don't allow any commands to work when locked
|
||||
# def cog_check(self, ctx):
|
||||
# return not self.client.locked
|
||||
# Don't allow any commands to work when locked
|
||||
def cog_check(self, _):
|
||||
return not self.client.locked
|
||||
|
||||
@commands.command(name="Custom")
|
||||
@help.Category(category=Category.Didier)
|
||||
|
@ -25,10 +22,7 @@ class Other(commands.Cog):
|
|||
"""
|
||||
Get a list of all custom commands
|
||||
"""
|
||||
all_commands = get_all()
|
||||
formatted = list(sorted(map(lambda x: capitalize(x["name"]), all_commands)))
|
||||
src = custom_commands.CommandsList(formatted)
|
||||
await custom_commands.Pages(source=src, clear_reactions_after=True).start(ctx)
|
||||
await custom_commands.CommandsList(ctx).send()
|
||||
|
||||
@commands.command(name="Snipe")
|
||||
@help.Category(category=Category.Other)
|
||||
|
|
127
cogs/train.py
127
cogs/train.py
|
@ -1,127 +0,0 @@
|
|||
from data.menus import leaderboards
|
||||
from decorators import help
|
||||
import discord
|
||||
from discord.ext import commands, menus
|
||||
from enums.help_categories import Category
|
||||
from functions import checks, timeFormatters
|
||||
import requests
|
||||
|
||||
|
||||
class Train(commands.Cog):
|
||||
|
||||
def __init__(self, client):
|
||||
self.client = client
|
||||
|
||||
# Don't allow any commands to work when locked
|
||||
def cog_check(self, ctx):
|
||||
return not self.client.locked
|
||||
|
||||
@commands.command(name="Train", aliases=["Trein"], usage="[Vertrek]* [Bestemming]")
|
||||
@help.Category(category=Category.School)
|
||||
async def train(self, ctx, *args):
|
||||
if not args or len(args) > 2:
|
||||
await ctx.send("Controleer je argumenten.")
|
||||
return
|
||||
destination = args[-1]
|
||||
departure = args[0] if len(args) > 1 else "Gent Sint-Pieters"
|
||||
|
||||
req = requests.get(
|
||||
"http://api.irail.be/connections/?from={}&to={}&alerts=true&lang=nl&format=json".format(departure,
|
||||
destination)).json()
|
||||
if "error" in req:
|
||||
embed = discord.Embed(colour=discord.Colour.red())
|
||||
embed.set_author(name="Treinen van {} naar {}".format(
|
||||
self.formatCity(departure), self.formatCity(destination)))
|
||||
embed.add_field(name="Error", value="Er ging iets fout, probeer het later opnieuw.", inline=False)
|
||||
await self.sendEmbed(ctx, embed)
|
||||
return
|
||||
|
||||
pages = paginated_leaderboard.Pages(source=TrainPagination(self.formatConnections(req["connection"]),
|
||||
self.formatCity(departure),
|
||||
self.formatCity(destination)),
|
||||
clear_reactions_after=True)
|
||||
await pages.start(ctx)
|
||||
|
||||
def formatConnections(self, connections):
|
||||
response = []
|
||||
for connection in sorted(connections, key=lambda con: con["departure"]["time"]):
|
||||
conn = {}
|
||||
if connection["departure"]["canceled"] != "0" or connection["arrival"]["canceled"] != "0":
|
||||
conn = {"Canceled": "Afgeschaft"}
|
||||
dep = connection["departure"]
|
||||
arr = connection["arrival"]
|
||||
conn["depStation"] = self.formatCity(dep["station"])
|
||||
conn["depTime"] = self.formatTime(dep["time"])
|
||||
conn["delay"] = self.formatDelay(dep["delay"])
|
||||
conn["track"] = dep["platform"]
|
||||
conn["arrStation"] = self.formatCity(arr["station"])
|
||||
conn["direction"] = self.formatCity(dep["direction"]["name"])
|
||||
conn["arrTime"] = self.formatTime(arr["time"])
|
||||
conn["duration"] = self.formatTime(connection["duration"])
|
||||
response.append(conn)
|
||||
return response
|
||||
|
||||
def formatTime(self, timestamp):
|
||||
if int(timestamp) <= 86400:
|
||||
minutes = int(timestamp) // 60
|
||||
if minutes < 60:
|
||||
return str(minutes) + "m"
|
||||
return "{}h{:02}m".format(minutes // 60, minutes % 60)
|
||||
else:
|
||||
return timeFormatters.epochToDate(int(timestamp), "%H:%M")["date"]
|
||||
|
||||
def formatDelay(self, seconds):
|
||||
seconds = int(seconds)
|
||||
return self.sign(seconds) + self.formatTime(abs(seconds)) if seconds != 0 else ""
|
||||
|
||||
def sign(self, number):
|
||||
return "-" if int(number) < 0 else "+"
|
||||
|
||||
def formatCity(self, city):
|
||||
city = city[0].upper() + city[1:]
|
||||
arr = []
|
||||
for i, letter in enumerate(city):
|
||||
if (i > 0 and (city[i - 1] == " " or city[i - 1] == "-")) or i == 0:
|
||||
arr.append(letter.upper())
|
||||
else:
|
||||
arr.append(letter.lower())
|
||||
return "".join(arr)
|
||||
|
||||
async def sendEmbed(self, ctx, embed):
|
||||
if await checks.allowedChannels(ctx):
|
||||
await ctx.send(embed=embed)
|
||||
else:
|
||||
await ctx.author.send(embed=embed)
|
||||
|
||||
|
||||
class TrainPagination(menus.ListPageSource):
|
||||
def __init__(self, data, departure, destination):
|
||||
super().__init__(data, per_page=3)
|
||||
self.departure = departure
|
||||
self.destination = destination
|
||||
|
||||
async def format_page(self, menu: menus.MenuPages, entries):
|
||||
offset = menu.current_page * self.per_page
|
||||
embed = discord.Embed(colour=discord.Colour.blue())
|
||||
embed.set_author(name="Treinen van {} naar {}".format(self.departure, self.destination))
|
||||
embed.set_footer(text="{}/{}".format(menu.current_page + 1, self.get_max_pages()))
|
||||
|
||||
for i, connection in enumerate(entries, start=offset):
|
||||
afgeschaft = "Canceled" in connection
|
||||
embed.add_field(name="Van", value=str(connection["depStation"]), inline=True)
|
||||
embed.add_field(name="Om", value=str(connection["depTime"]), inline=True)
|
||||
embed.add_field(name="Spoor", value=str(connection["track"]), inline=True)
|
||||
embed.add_field(name="Richting", value=str(connection["direction"]), inline=True)
|
||||
embed.add_field(name="Aankomst", value=(str(connection["arrTime"])
|
||||
if not afgeschaft else "**AFGESCHAFT**"), inline=True)
|
||||
embed.add_field(name="Vertraging", value=str(connection["delay"]) if connection["delay"] != "" else "0",
|
||||
inline=True)
|
||||
|
||||
# White space
|
||||
if i - offset < 2:
|
||||
embed.add_field(name="\u200b", value="\u200b", inline=False)
|
||||
return embed
|
||||
|
||||
|
||||
def setup(client):
|
||||
client.add_cog(Train(client))
|
|
@ -1,22 +1,18 @@
|
|||
import discord
|
||||
from discord.ext import menus
|
||||
from typing import Union
|
||||
|
||||
from discord import ApplicationContext
|
||||
from discord.ext.commands import Context
|
||||
|
||||
from data.menus.paginated import Paginated
|
||||
from functions.database.custom_commands import get_all
|
||||
from functions.stringFormatters import capitalize
|
||||
|
||||
|
||||
# TODO rework pagination
|
||||
class CommandsList(menus.ListPageSource):
|
||||
def __init__(self, data, colour=discord.Colour.blue()):
|
||||
super().__init__(data, per_page=15)
|
||||
self.colour = colour
|
||||
class CommandsList(Paginated):
|
||||
def __init__(self, ctx: Union[ApplicationContext, Context]):
|
||||
all_commands = get_all()
|
||||
commands_sorted = list(sorted(map(lambda x: (capitalize(x["name"]),), all_commands)))
|
||||
super().__init__(ctx=ctx, title="Custom Commands", data=commands_sorted, per_page=15)
|
||||
|
||||
async def format_page(self, menu: menus.MenuPages, entries):
|
||||
embed = discord.Embed(colour=self.colour)
|
||||
embed.set_author(name="Custom Commands")
|
||||
embed.description = "\n".join(entries)
|
||||
embed.set_footer(text="{}/{}".format(menu.current_page + 1, self.get_max_pages()))
|
||||
|
||||
return embed
|
||||
|
||||
|
||||
class Pages(menus.MenuPages):
|
||||
def __init__(self, source, clear_reactions_after, timeout=30.0):
|
||||
super().__init__(source, timeout=timeout, delete_message_after=True, clear_reactions_after=clear_reactions_after)
|
||||
def format_entry(self, index: int, value: tuple) -> str:
|
||||
return value[0]
|
||||
|
|
|
@ -6,7 +6,6 @@ from typing import Union, Optional
|
|||
import discord
|
||||
import requests
|
||||
from discord import ApplicationContext
|
||||
from discord.ext import menus
|
||||
from discord.ext.commands import Context
|
||||
|
||||
from data.menus.paginated import Paginated
|
||||
|
@ -80,7 +79,7 @@ class Leaderboard(Paginated, ABC):
|
|||
def empty_description(self) -> str:
|
||||
return ""
|
||||
|
||||
async def empty_leaderboard(self, ctx: Union[ApplicationContext, Context]):
|
||||
async def empty_leaderboard(self, ctx: Union[ApplicationContext, Context], **kwargs):
|
||||
embed = discord.Embed(colour=self.colour)
|
||||
embed.set_author(name=self.title)
|
||||
embed.description = self.empty_description
|
||||
|
@ -88,19 +87,19 @@ class Leaderboard(Paginated, ABC):
|
|||
if isinstance(ctx, ApplicationContext):
|
||||
return await ctx.respond(embed=embed)
|
||||
|
||||
return await ctx.reply(embed=embed, mention_author=False)
|
||||
return await ctx.reply(embed=embed, **kwargs)
|
||||
|
||||
async def respond(self, **kwargs) -> discord.Message:
|
||||
if self.data is None:
|
||||
return await self.empty_leaderboard(self.ctx)
|
||||
return await self.empty_leaderboard(self.ctx, **kwargs)
|
||||
|
||||
return await super().respond(**kwargs)
|
||||
|
||||
async def send(self, **kwargs) -> discord.Message:
|
||||
if self.data is None:
|
||||
return await self.empty_leaderboard(self.ctx)
|
||||
return await self.empty_leaderboard(self.ctx, mention_author=False, **kwargs)
|
||||
|
||||
return await super().send(**kwargs)
|
||||
return await super().send(mention_author=False, **kwargs)
|
||||
|
||||
|
||||
@dataclass
|
||||
|
@ -245,31 +244,3 @@ class XPLeaderboard(Leaderboard):
|
|||
def format_entry_data(self, data: tuple) -> str:
|
||||
entry = data[2]
|
||||
return f"Level {xp.calculate_level(entry):,} | {entry:,} XP"
|
||||
|
||||
|
||||
class Source(menus.ListPageSource):
|
||||
def __init__(self, data, name, colour=discord.Colour.blue()):
|
||||
super().__init__(data, per_page=10)
|
||||
self.name = name
|
||||
self.colour = colour
|
||||
|
||||
async def format_page(self, menu: menus.MenuPages, entries):
|
||||
offset = menu.current_page * self.per_page
|
||||
|
||||
description = ""
|
||||
for i, v in enumerate(entries, start=offset):
|
||||
# Check if the person's name has to be highlighted
|
||||
if v.startswith("**") and v.endswith("**"):
|
||||
description += "**"
|
||||
v = v[2:]
|
||||
description += "{}: {}\n".format(i + 1, v)
|
||||
embed = discord.Embed(colour=self.colour)
|
||||
embed.set_author(name=self.name)
|
||||
embed.description = description
|
||||
embed.set_footer(text="{}/{}".format(menu.current_page + 1, self.get_max_pages()))
|
||||
return embed
|
||||
|
||||
|
||||
class Pages(menus.MenuPages):
|
||||
def __init__(self, source, clear_reactions_after, timeout=30.0):
|
||||
super().__init__(source, timeout=timeout, delete_message_after=True, clear_reactions_after=clear_reactions_after)
|
||||
|
|
Loading…
Reference in New Issue