college-bot-v1/utils/__init__.py

81 lines
2.3 KiB
Python
Raw Normal View History

2023-03-17 09:25:26 +00:00
from typing import Optional, TYPE_CHECKING
2022-10-09 19:27:02 +01:00
from urllib.parse import urlparse
2023-03-17 09:25:26 +00:00
import discord
2023-01-09 14:25:44 +00:00
from discord.ext import commands
2022-09-13 20:50:02 +01:00
from ._email import *
from .db import *
2022-09-13 21:19:23 +01:00
from .console import *
2022-10-04 18:21:44 +01:00
from .views import *
2022-10-09 19:27:02 +01:00
2023-03-17 09:25:26 +00:00
if TYPE_CHECKING:
from datetime import datetime
class JimmyBanException(discord.CheckFailure):
def __init__(self, until: "datetime", reason: str):
super().__init__(reason)
self.until = until
self.reason = reason
def __str__(self):
ok = discord.utils.format_dt(self.until, "R")
return (
f"\N{cross mark} You are not allowed to use commands right now. You will be unbanned {ok}.\n"
f"Ban reason:\n>>> {self.reason}"
)
def __repr__(self):
return f"<JimmyBanException until={self.until!r} reason={self.reason!r}>"
2022-10-09 19:27:02 +01:00
def simple_embed_paginator(
2022-10-30 16:31:38 +00:00
lines: list[str], *, assert_ten: bool = False, empty_is_none: bool = True, **kwargs
2022-10-09 19:27:02 +01:00
) -> Optional[list[discord.Embed]]:
"""Paginates x lines into x embeds."""
if not lines and empty_is_none is True:
return
kwargs.setdefault("description", "")
embeds = [discord.Embed(**kwargs)]
for line in lines:
embed = embeds[-1]
total_length = len(embed)
description_length = len(embed.description)
if total_length + len(line) > 6000 or description_length + len(line) > 4096:
embed = discord.Embed(**kwargs)
embed.description += line + "\n"
embeds.append(embed)
else:
embed.description += line + "\n"
if assert_ten:
assert len(embeds) <= 10, "Too many embeds."
return embeds
def hyperlink(url: str, *, text: str = None, max_length: int = None) -> str:
if max_length < len(url):
raise ValueError(f"Max length ({max_length}) is too low for provided URL ({len(url)}). Hyperlink impossible.")
fmt = "[{}]({})"
if text:
fmt = fmt.format(text, url)
else:
parsed = urlparse(url)
fmt = fmt.format(parsed.hostname, url)
if len(fmt) > max_length:
return url
return fmt
2023-01-09 14:25:44 +00:00
def owner_or_admin():
async def predicate(ctx: commands.Context):
if ctx.author.guild_permissions.administrator or await ctx.bot.is_owner(ctx.author):
return True
raise commands.MissingPermissions(["administrator"])
2023-01-15 19:38:02 +00:00
2023-01-09 14:25:44 +00:00
return commands.check(predicate)