mirror of
https://github.com/Matthww/TuneBot.git
synced 2026-09-21 21:27:48 +00:00
WIP Cleaning up the code base + impl slash commands
This commit is contained in:
+10
-16
@@ -7,26 +7,21 @@ from discord.ext.commands import Context
|
||||
|
||||
class EmbedGenerator:
|
||||
@staticmethod
|
||||
async def Error(ctx: Context, message: str, **kwargs):
|
||||
async def Error(ctx: Context, message: str, **kwargs) -> Embed:
|
||||
color = ctx.bot.colors["embed"]
|
||||
em = Embed(title='Error:', description=message, color=color)
|
||||
em = Embed(title="Error:", description=message, color=color)
|
||||
return await EmbedGenerator.SendWithFooter(ctx, em, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
async def Message(ctx: Context,
|
||||
title: str,
|
||||
message: Optional[str] = '',
|
||||
**kwargs):
|
||||
async def Message(ctx: Context, title: str, message: Optional[str] = "", **kwargs):
|
||||
color = ctx.bot.colors["embed"]
|
||||
em = Embed(title=title, description=message, color=color)
|
||||
return await EmbedGenerator.SendWithFooter(ctx, em, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
async def Image(ctx: Context,
|
||||
title: str,
|
||||
url: str,
|
||||
message: Optional[str] = '',
|
||||
**kwargs):
|
||||
async def Image(
|
||||
ctx: Context, title: str, url: str, message: Optional[str] = "", **kwargs
|
||||
):
|
||||
color = ctx.bot.colors["embed"]
|
||||
em = Embed(title=title, description=message, url=url, color=color)
|
||||
em.set_image(url=url)
|
||||
@@ -39,10 +34,9 @@ class EmbedGenerator:
|
||||
return await EmbedGenerator.SendWithFooter(ctx, em, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
async def SendWithFooter(ctx: Context, em: Embed,
|
||||
**kwargs) -> discord.Message:
|
||||
avatar = ctx.author.avatar_url_as()
|
||||
em.set_footer(text=f'Requested by: {ctx.author}', icon_url=avatar)
|
||||
if kwargs.get('no_send', False):
|
||||
async def SendWithFooter(ctx: Context, em: Embed, **kwargs) -> discord.Message:
|
||||
avatar = ctx.author.avatar.with_static_format("jpeg")
|
||||
em.set_footer(text=f"Requested by: {ctx.author}", icon_url=avatar)
|
||||
if kwargs.get("no_send", False):
|
||||
return em
|
||||
return await ctx.send(embed=em, **kwargs)
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import aiomysql
|
||||
import asyncio
|
||||
from bot import CloudKid
|
||||
from aiomysql.sa import SAConnection
|
||||
from sqlalchemy import Table
|
||||
from typing import Sequence
|
||||
|
||||
|
||||
class AutoJoin:
|
||||
@staticmethod
|
||||
async def get_channels(bot: CloudKid) -> Sequence[tuple]:
|
||||
autojoin: Table = bot.database.tables["autojoin"]
|
||||
conn: SAConnection = await bot.database.engine.acquire()
|
||||
result = await conn.execute(autojoin.select())
|
||||
channels: Sequence[tuple] = await result.fetchall()
|
||||
return channels
|
||||
|
||||
@staticmethod
|
||||
async def update_channel(bot, guild_id, channel_id):
|
||||
autojoin: Table = bot.database.tables["autojoin"]
|
||||
conn: SAConnection = await bot.database.engine.acquire()
|
||||
await conn.execute(autojoin.insert().values({
|
||||
"guild_id": guild_id,
|
||||
"channel_id": channel_id
|
||||
}))
|
||||
|
||||
@staticmethod
|
||||
async def del_channel(bot, guild_id):
|
||||
autojoin: Table = bot.database.tables["autojoin"]
|
||||
conn: SAConnection = await bot.database.engine.acquire()
|
||||
await conn.execute(
|
||||
autojoin.delete().where(autojoin.c.guild_id == guild_id))
|
||||
@@ -1,60 +0,0 @@
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
import urllib.request as urllib2
|
||||
import aiohttp
|
||||
|
||||
key = "b9803d262fab977f:04c791f69496359d638fc634e60c08d0"
|
||||
|
||||
|
||||
def hasNumbers(inputString):
|
||||
return any(char.isdigit() for char in inputString)
|
||||
|
||||
|
||||
def process_stream_title(title: str) -> list:
|
||||
l = title.split(' - ', 1)
|
||||
if l[0].isdigit():
|
||||
return l[1].rsplit(" - ", 1)
|
||||
return title.rsplit(" - ", 1)
|
||||
|
||||
|
||||
async def fetch_metadata():
|
||||
url = "https://azuracast.exobot.site/api/nowplaying"
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url) as response:
|
||||
data = await response.json()
|
||||
source = data["playing_next"]["text"]
|
||||
name, vid = process_stream_title(source["title"])
|
||||
return {"name": name, "thumbnail": data["playing_next"]["art"]}
|
||||
|
||||
|
||||
async def get_metadata():
|
||||
"""Deprecated: use fetch_metadata()"""
|
||||
url = 'https://icecast.exobot.site/stream' # radio stream
|
||||
encoding = 'iso-8859-1' # default: iso-8859-1 for mp3 and utf-8 for ogg streams
|
||||
request = urllib2.Request(url, headers={'Icy-MetaData':
|
||||
1}) # request metadata
|
||||
response = urllib2.urlopen(request)
|
||||
# print(response.headers, file=sys.stderr)
|
||||
metaint = int(response.headers['icy-metaint'])
|
||||
for _ in range(10): # title may be empty initially, try several times
|
||||
response.read(metaint) # skip to metadata
|
||||
metadata_length = struct.unpack(
|
||||
'B', response.read(1))[0] * 16 # length byte
|
||||
metadata = response.read(metadata_length).rstrip(b'\0')
|
||||
# print(metadata, file=sys.stderr)
|
||||
# extract title from the metadata
|
||||
m = re.search(br"StreamTitle='([^']*)';", metadata)
|
||||
if m:
|
||||
title = m.group(1)
|
||||
if title:
|
||||
break
|
||||
else:
|
||||
sys.exit('no title found')
|
||||
|
||||
title = title.decode(encoding, errors='replace')
|
||||
#print(f"DEBUG: {title}")
|
||||
if hasNumbers(str(title[:4])):
|
||||
return title[7:][:-14]
|
||||
else:
|
||||
return title[:-14]
|
||||
+192
-169
@@ -43,13 +43,10 @@ class Pages:
|
||||
permissions: discord.Permissions
|
||||
Our permissions for the channel.
|
||||
"""
|
||||
def __init__(self,
|
||||
ctx,
|
||||
*,
|
||||
entries,
|
||||
per_page=12,
|
||||
show_entry_count=True,
|
||||
hide_no_results=False):
|
||||
|
||||
def __init__(
|
||||
self, ctx, *, entries, per_page=12, show_entry_count=True, hide_no_results=False
|
||||
):
|
||||
self.hide_no_results = hide_no_results
|
||||
self.bot = ctx.bot
|
||||
self.entries = entries
|
||||
@@ -65,15 +62,19 @@ class Pages:
|
||||
self.paginating = len(entries) > per_page
|
||||
self.show_entry_count = show_entry_count
|
||||
self.reaction_emojis = [
|
||||
('\N{BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}',
|
||||
self.first_page),
|
||||
('\N{BLACK LEFT-POINTING TRIANGLE}', self.previous_page),
|
||||
('\N{BLACK RIGHT-POINTING TRIANGLE}', self.next_page),
|
||||
('\N{BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}',
|
||||
self.last_page),
|
||||
('\N{INPUT SYMBOL FOR NUMBERS}', self.numbered_page),
|
||||
('\N{BLACK SQUARE FOR STOP}', self.stop_pages),
|
||||
('\N{INFORMATION SOURCE}', self.show_help),
|
||||
(
|
||||
"\N{BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}",
|
||||
self.first_page,
|
||||
),
|
||||
("\N{BLACK LEFT-POINTING TRIANGLE}", self.previous_page),
|
||||
("\N{BLACK RIGHT-POINTING TRIANGLE}", self.next_page),
|
||||
(
|
||||
"\N{BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}",
|
||||
self.last_page,
|
||||
),
|
||||
("\N{INPUT SYMBOL FOR NUMBERS}", self.numbered_page),
|
||||
("\N{BLACK SQUARE FOR STOP}", self.stop_pages),
|
||||
("\N{INFORMATION SOURCE}", self.show_help),
|
||||
]
|
||||
|
||||
if ctx.guild is not None:
|
||||
@@ -82,63 +83,64 @@ class Pages:
|
||||
self.permissions = self.channel.permissions_for(ctx.bot.user)
|
||||
|
||||
if not self.permissions.embed_links:
|
||||
raise CannotPaginate('Bot does not have embed links permission.')
|
||||
raise CannotPaginate("Bot does not have embed links permission.")
|
||||
|
||||
if not self.permissions.send_messages:
|
||||
raise CannotPaginate('Bot cannot send messages.')
|
||||
raise CannotPaginate("Bot cannot send messages.")
|
||||
|
||||
if self.paginating:
|
||||
# verify we can actually use the pagination session
|
||||
if not self.permissions.add_reactions:
|
||||
raise CannotPaginate(
|
||||
'Bot does not have add reactions permission.')
|
||||
raise CannotPaginate("Bot does not have add reactions permission.")
|
||||
|
||||
if not self.permissions.read_message_history:
|
||||
raise CannotPaginate(
|
||||
'Bot does not have Read Message History permission.')
|
||||
"Bot does not have Read Message History permission."
|
||||
)
|
||||
|
||||
def get_page(self, page):
|
||||
base = (page - 1) * self.per_page
|
||||
return self.entries[base:base + self.per_page]
|
||||
return self.entries[base : base + self.per_page]
|
||||
|
||||
async def show_page(self, page, *, first=False):
|
||||
# noinspection PyAttributeOutsideInit
|
||||
self.current_page = page
|
||||
entries = self.get_page(page)
|
||||
p = []
|
||||
for index, entry in enumerate(entries,
|
||||
1 + ((page - 1) * self.per_page)):
|
||||
p.append(f'{index}. {entry}')
|
||||
for index, entry in enumerate(entries, 1 + ((page - 1) * self.per_page)):
|
||||
p.append(f"{index}. {entry}")
|
||||
|
||||
if self.maximum_pages > 1:
|
||||
if self.show_entry_count:
|
||||
text = f'Page {page}/{self.maximum_pages}' \
|
||||
f' ({len(self.entries)} entries)'
|
||||
text = (
|
||||
f"Page {page}/{self.maximum_pages}"
|
||||
f" ({len(self.entries)} entries)"
|
||||
)
|
||||
else:
|
||||
text = f'Page {page}/{self.maximum_pages}'
|
||||
text = f"Page {page}/{self.maximum_pages}"
|
||||
|
||||
self.embed.set_footer(text=text)
|
||||
|
||||
if not self.paginating:
|
||||
self.embed.description = '\n'.join(p)
|
||||
self.embed.description = "\n".join(p)
|
||||
return await self.channel.send(embed=self.embed)
|
||||
|
||||
if not first:
|
||||
self.embed.description = '\n'.join(p)
|
||||
self.embed.description = "\n".join(p)
|
||||
await self.message.edit(embed=self.embed)
|
||||
return
|
||||
|
||||
p.append('')
|
||||
p.append('Confused? React with \N{INFORMATION SOURCE} for more info.')
|
||||
self.embed.description = '\n'.join(p)
|
||||
p.append("")
|
||||
p.append("Confused? React with \N{INFORMATION SOURCE} for more info.")
|
||||
self.embed.description = "\n".join(p)
|
||||
self.message = await self.channel.send(embed=self.embed)
|
||||
|
||||
await self.message.add_reaction('🔣')
|
||||
await self.message.add_reaction("🔣")
|
||||
|
||||
async def add_rest_reactions(self):
|
||||
await self.message.remove_reaction('🔣', self.message.guild.me)
|
||||
await self.message.remove_reaction("🔣", self.message.guild.me)
|
||||
for (reaction, _) in self.reaction_emojis:
|
||||
if self.maximum_pages == 2 and reaction in ('\u23ed', '\u23ee'):
|
||||
if self.maximum_pages == 2 and reaction in ("\u23ed", "\u23ee"):
|
||||
# no |<< or >>| buttons if we only have two pages
|
||||
# we can't forbid it if someone ends up using it but remove
|
||||
# it from the default set
|
||||
@@ -174,20 +176,19 @@ class Pages:
|
||||
"""lets you type a page number to go to"""
|
||||
# noinspection PyListCreation
|
||||
to_delete = []
|
||||
to_delete.append(await
|
||||
self.channel.send('What page do you want to go to?'))
|
||||
to_delete.append(await self.channel.send("What page do you want to go to?"))
|
||||
|
||||
def message_check(m):
|
||||
return m.author == self.author and \
|
||||
self.channel == m.channel and \
|
||||
m.content.isdigit()
|
||||
return (
|
||||
m.author == self.author
|
||||
and self.channel == m.channel
|
||||
and m.content.isdigit()
|
||||
)
|
||||
|
||||
try:
|
||||
msg = await self.bot.wait_for('message',
|
||||
check=message_check,
|
||||
timeout=30.0)
|
||||
msg = await self.bot.wait_for("message", check=message_check, timeout=30.0)
|
||||
except asyncio.TimeoutError:
|
||||
to_delete.append(await self.channel.send('Took too long.'))
|
||||
to_delete.append(await self.channel.send("Took too long."))
|
||||
await asyncio.sleep(5)
|
||||
else:
|
||||
page = int(msg.content)
|
||||
@@ -195,8 +196,11 @@ class Pages:
|
||||
if page != 0 and page <= self.maximum_pages:
|
||||
await self.show_page(page)
|
||||
else:
|
||||
to_delete.append(await self.channel.send(
|
||||
f'Invalid page given. ({page}/{self.maximum_pages})'))
|
||||
to_delete.append(
|
||||
await self.channel.send(
|
||||
f"Invalid page given. ({page}/{self.maximum_pages})"
|
||||
)
|
||||
)
|
||||
await asyncio.sleep(5)
|
||||
|
||||
# noinspection PyBroadException
|
||||
@@ -208,19 +212,20 @@ class Pages:
|
||||
async def show_help(self):
|
||||
"""shows this message"""
|
||||
messages = [
|
||||
'Welcome to the interactive paginator!\n',
|
||||
'This interactively allows you to see pages '
|
||||
'of text by navigating with '
|
||||
'reactions. They are as follows:\n'
|
||||
"Welcome to the interactive paginator!\n",
|
||||
"This interactively allows you to see pages "
|
||||
"of text by navigating with "
|
||||
"reactions. They are as follows:\n",
|
||||
]
|
||||
|
||||
for (emoji, func) in self.reaction_emojis:
|
||||
messages.append(f'{emoji} {func.__doc__}')
|
||||
messages.append(f"{emoji} {func.__doc__}")
|
||||
|
||||
self.embed.description = '\n'.join(messages)
|
||||
self.embed.description = "\n".join(messages)
|
||||
self.embed.clear_fields()
|
||||
self.embed.set_footer(
|
||||
text=f'We were on page {self.current_page} before this message.')
|
||||
text=f"We were on page {self.current_page} before this message."
|
||||
)
|
||||
await self.message.edit(embed=self.embed)
|
||||
|
||||
async def go_back_to_current_page():
|
||||
@@ -241,7 +246,7 @@ class Pages:
|
||||
if reaction.message.id != self.message.id:
|
||||
return False
|
||||
|
||||
if reaction.emoji == '🔣':
|
||||
if reaction.emoji == "🔣":
|
||||
self.match = self.add_rest_reactions
|
||||
return True
|
||||
|
||||
@@ -258,7 +263,7 @@ class Pages:
|
||||
if not self.entries and not self.hide_no_results:
|
||||
# I just say no results found because that's my most common use
|
||||
# case.
|
||||
return await self.channel.send('No results found.')
|
||||
return await self.channel.send("No results found.")
|
||||
|
||||
first_page = self.show_page(1, first=True)
|
||||
if not self.paginating:
|
||||
@@ -270,7 +275,8 @@ class Pages:
|
||||
while self.paginating:
|
||||
try:
|
||||
reaction, user = await self.bot.wait_for(
|
||||
'reaction_add', check=self.react_check, timeout=120.0)
|
||||
"reaction_add", check=self.react_check, timeout=120.0
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
self.paginating = False
|
||||
# noinspection PyBroadException
|
||||
@@ -285,13 +291,14 @@ class Pages:
|
||||
try:
|
||||
await self.message.remove_reaction(reaction, user)
|
||||
except Exception:
|
||||
pass # can't remove it so don't bother doing so
|
||||
pass # can't remove it so don't bother doing so
|
||||
|
||||
await self.match()
|
||||
|
||||
|
||||
class EmbedPages:
|
||||
"""Similar to Pages, but you use [`discord.Embed`]"""
|
||||
|
||||
def __init__(self, ctx, *, embeds):
|
||||
self.bot = ctx.bot
|
||||
self.embeds = embeds
|
||||
@@ -302,15 +309,19 @@ class EmbedPages:
|
||||
self.maximum_pages = pages
|
||||
self.paginating = len(embeds) > 1
|
||||
self.reaction_emojis = [
|
||||
('\N{BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}',
|
||||
self.first_page),
|
||||
('\N{BLACK LEFT-POINTING TRIANGLE}', self.previous_page),
|
||||
('\N{BLACK RIGHT-POINTING TRIANGLE}', self.next_page),
|
||||
('\N{BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}',
|
||||
self.last_page),
|
||||
('\N{INPUT SYMBOL FOR NUMBERS}', self.numbered_page),
|
||||
('\N{BLACK SQUARE FOR STOP}', self.stop_pages),
|
||||
('\N{INFORMATION SOURCE}', self.show_help),
|
||||
(
|
||||
"\N{BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}",
|
||||
self.first_page,
|
||||
),
|
||||
("\N{BLACK LEFT-POINTING TRIANGLE}", self.previous_page),
|
||||
("\N{BLACK RIGHT-POINTING TRIANGLE}", self.next_page),
|
||||
(
|
||||
"\N{BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}",
|
||||
self.last_page,
|
||||
),
|
||||
("\N{INPUT SYMBOL FOR NUMBERS}", self.numbered_page),
|
||||
("\N{BLACK SQUARE FOR STOP}", self.stop_pages),
|
||||
("\N{INFORMATION SOURCE}", self.show_help),
|
||||
]
|
||||
|
||||
if ctx.guild is not None:
|
||||
@@ -319,20 +330,20 @@ class EmbedPages:
|
||||
self.permissions = self.channel.permissions_for(ctx.bot.user)
|
||||
|
||||
if not self.permissions.embed_links:
|
||||
raise CannotPaginate('Bot does not have embed links permission.')
|
||||
raise CannotPaginate("Bot does not have embed links permission.")
|
||||
|
||||
if not self.permissions.send_messages:
|
||||
raise CannotPaginate('Bot cannot send messages.')
|
||||
raise CannotPaginate("Bot cannot send messages.")
|
||||
|
||||
if self.paginating:
|
||||
# verify we can actually use the pagination session
|
||||
if not self.permissions.add_reactions:
|
||||
raise CannotPaginate(
|
||||
'Bot does not have add reactions permission.')
|
||||
raise CannotPaginate("Bot does not have add reactions permission.")
|
||||
|
||||
if not self.permissions.read_message_history:
|
||||
raise CannotPaginate(
|
||||
'Bot does not have Read Message History permission.')
|
||||
"Bot does not have Read Message History permission."
|
||||
)
|
||||
|
||||
async def show_page(self, page, *, first=False):
|
||||
# noinspection PyAttributeOutsideInit
|
||||
@@ -341,7 +352,7 @@ class EmbedPages:
|
||||
p = []
|
||||
|
||||
if self.maximum_pages > 1:
|
||||
text = f'Page {page}/{self.maximum_pages}'
|
||||
text = f"Page {page}/{self.maximum_pages}"
|
||||
|
||||
embed.set_footer(text=text)
|
||||
|
||||
@@ -351,19 +362,20 @@ class EmbedPages:
|
||||
if not first:
|
||||
return await self.message.edit(embed=embed)
|
||||
|
||||
p.append('')
|
||||
p.append('Confused? React with \N{INFORMATION SOURCE} for more info.')
|
||||
embed.description = '' if embed.description == discord.Embed.Empty \
|
||||
else embed.description
|
||||
embed.description += '\n'.join(p)
|
||||
p.append("")
|
||||
p.append("Confused? React with \N{INFORMATION SOURCE} for more info.")
|
||||
embed.description = (
|
||||
"" if embed.description == discord.Embed.Empty else embed.description
|
||||
)
|
||||
embed.description += "\n".join(p)
|
||||
self.message = await self.channel.send(embed=embed)
|
||||
|
||||
await self.message.add_reaction('🔣')
|
||||
await self.message.add_reaction("🔣")
|
||||
|
||||
async def add_rest_reactions(self):
|
||||
await self.message.remove_reaction('🔣', self.message.guild.me)
|
||||
await self.message.remove_reaction("🔣", self.message.guild.me)
|
||||
for (reaction, _) in self.reaction_emojis:
|
||||
if self.maximum_pages == 2 and reaction in ('\u23ed', '\u23ee'):
|
||||
if self.maximum_pages == 2 and reaction in ("\u23ed", "\u23ee"):
|
||||
# no |<< or >>| buttons if we only have two pages
|
||||
# we can't forbid it if someone ends up using it but remove
|
||||
# it from the default set
|
||||
@@ -399,20 +411,19 @@ class EmbedPages:
|
||||
"""lets you type a page number to go to"""
|
||||
# noinspection PyListCreation
|
||||
to_delete = []
|
||||
to_delete.append(await
|
||||
self.channel.send('What page do you want to go to?'))
|
||||
to_delete.append(await self.channel.send("What page do you want to go to?"))
|
||||
|
||||
def message_check(m):
|
||||
return m.author == self.author and \
|
||||
self.channel == m.channel and \
|
||||
m.content.isdigit()
|
||||
return (
|
||||
m.author == self.author
|
||||
and self.channel == m.channel
|
||||
and m.content.isdigit()
|
||||
)
|
||||
|
||||
try:
|
||||
msg = await self.bot.wait_for('message',
|
||||
check=message_check,
|
||||
timeout=30.0)
|
||||
msg = await self.bot.wait_for("message", check=message_check, timeout=30.0)
|
||||
except asyncio.TimeoutError:
|
||||
to_delete.append(await self.channel.send('Took too long.'))
|
||||
to_delete.append(await self.channel.send("Took too long."))
|
||||
await asyncio.sleep(5)
|
||||
else:
|
||||
page = int(msg.content)
|
||||
@@ -420,8 +431,11 @@ class EmbedPages:
|
||||
if page != 0 and page <= self.maximum_pages:
|
||||
await self.show_page(page)
|
||||
else:
|
||||
to_delete.append(await self.channel.send(
|
||||
f'Invalid page given. ({page}/{self.maximum_pages})'))
|
||||
to_delete.append(
|
||||
await self.channel.send(
|
||||
f"Invalid page given. ({page}/{self.maximum_pages})"
|
||||
)
|
||||
)
|
||||
await asyncio.sleep(5)
|
||||
|
||||
# noinspection PyBroadException
|
||||
@@ -433,21 +447,22 @@ class EmbedPages:
|
||||
async def show_help(self):
|
||||
"""shows this message"""
|
||||
messages = [
|
||||
'Welcome to the interactive paginator!\n',
|
||||
'This interactively allows you to see pages '
|
||||
'of text by navigating with '
|
||||
'reactions. They are as follows:\n'
|
||||
"Welcome to the interactive paginator!\n",
|
||||
"This interactively allows you to see pages "
|
||||
"of text by navigating with "
|
||||
"reactions. They are as follows:\n",
|
||||
]
|
||||
|
||||
for (emoji, func) in self.reaction_emojis:
|
||||
messages.append(f'{emoji} {func.__doc__}')
|
||||
messages.append(f"{emoji} {func.__doc__}")
|
||||
|
||||
embed = discord.Embed()
|
||||
|
||||
embed.description = '\n'.join(messages)
|
||||
embed.description = "\n".join(messages)
|
||||
embed.clear_fields()
|
||||
embed.set_footer(
|
||||
text=f'We were on page {self.current_page} before this message.')
|
||||
text=f"We were on page {self.current_page} before this message."
|
||||
)
|
||||
await self.message.edit(embed=embed)
|
||||
|
||||
async def go_back_to_current_page():
|
||||
@@ -468,7 +483,7 @@ class EmbedPages:
|
||||
if reaction.message.id != self.message.id:
|
||||
return False
|
||||
|
||||
if reaction.emoji == '🔣':
|
||||
if reaction.emoji == "🔣":
|
||||
self.match = self.add_rest_reactions
|
||||
return True
|
||||
|
||||
@@ -492,7 +507,8 @@ class EmbedPages:
|
||||
while self.paginating:
|
||||
try:
|
||||
reaction, user = await self.bot.wait_for(
|
||||
'reaction_add', check=self.react_check, timeout=120.0)
|
||||
"reaction_add", check=self.react_check, timeout=120.0
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
self.paginating = False
|
||||
# noinspection PyBroadException
|
||||
@@ -507,7 +523,7 @@ class EmbedPages:
|
||||
try:
|
||||
await self.message.remove_reaction(reaction, user)
|
||||
except Exception:
|
||||
pass # can't remove it so don't bother doing so
|
||||
pass # can't remove it so don't bother doing so
|
||||
|
||||
await self.match()
|
||||
|
||||
@@ -516,6 +532,7 @@ class FieldPages(Pages):
|
||||
"""Similar to Pages except entries should be a list of
|
||||
tuples having (key, value) to show as embed fields instead.
|
||||
"""
|
||||
|
||||
async def show_page(self, page, *, first=False):
|
||||
# noinspection PyAttributeOutsideInit
|
||||
self.current_page = page
|
||||
@@ -529,10 +546,12 @@ class FieldPages(Pages):
|
||||
|
||||
if self.maximum_pages > 1:
|
||||
if self.show_entry_count:
|
||||
text = f'Page {page}/{self.maximum_pages} ' \
|
||||
f'({len(self.entries)} entries)'
|
||||
text = (
|
||||
f"Page {page}/{self.maximum_pages} "
|
||||
f"({len(self.entries)} entries)"
|
||||
)
|
||||
else:
|
||||
text = f'Page {page}/{self.maximum_pages}'
|
||||
text = f"Page {page}/{self.maximum_pages}"
|
||||
|
||||
self.embed.set_footer(text=text)
|
||||
|
||||
@@ -545,7 +564,7 @@ class FieldPages(Pages):
|
||||
|
||||
self.message = await self.channel.send(embed=self.embed)
|
||||
for (reaction, _) in self.reaction_emojis:
|
||||
if self.maximum_pages == 2 and reaction in ('\u23ed', '\u23ee'):
|
||||
if self.maximum_pages == 2 and reaction in ("\u23ed", "\u23ee"):
|
||||
# no |<< or >>| buttons if we only have two pages
|
||||
# we can't forbid it if someone ends up using it but remove
|
||||
# it from the default set
|
||||
@@ -559,7 +578,7 @@ class FieldPages(Pages):
|
||||
# ?help command
|
||||
# -> could be a subcommand
|
||||
|
||||
_mention = re.compile(r'<@!?([0-9]{1,19})>')
|
||||
_mention = re.compile(r"<@!?([0-9]{1,19})>")
|
||||
|
||||
|
||||
def cleanup_prefix(bot, prefix):
|
||||
@@ -567,7 +586,7 @@ def cleanup_prefix(bot, prefix):
|
||||
if m:
|
||||
user = bot.get_user(int(m.group(1)))
|
||||
if user:
|
||||
return f'@{user.name} '
|
||||
return f"@{user.name} "
|
||||
return prefix
|
||||
|
||||
|
||||
@@ -586,39 +605,40 @@ def _command_signature(cmd):
|
||||
result = [cmd.qualified_name]
|
||||
if cmd.usage:
|
||||
result.append(cmd.usage)
|
||||
return ' '.join(result)
|
||||
return " ".join(result)
|
||||
|
||||
params = cmd.clean_params
|
||||
if not params:
|
||||
return ' '.join(result)
|
||||
return " ".join(result)
|
||||
|
||||
for name, param in params.items():
|
||||
if param.default is not param.empty:
|
||||
# We don't want None or '' to trigger the [name=value] case and
|
||||
# instead it should do [name] since [name=None] or [name=] are
|
||||
# not exactly useful for the user.
|
||||
should_print = param.default if isinstance(
|
||||
param.default, str) else param.default is not None
|
||||
should_print = (
|
||||
param.default
|
||||
if isinstance(param.default, str)
|
||||
else param.default is not None
|
||||
)
|
||||
if should_print:
|
||||
result.append(f'[{name}={param.default!r}]')
|
||||
result.append(f"[{name}={param.default!r}]")
|
||||
else:
|
||||
result.append(f'[{name}]')
|
||||
result.append(f"[{name}]")
|
||||
elif param.kind == param.VAR_POSITIONAL:
|
||||
result.append(f'[{name}...]')
|
||||
result.append(f"[{name}...]")
|
||||
else:
|
||||
result.append(f'<{name}>')
|
||||
result.append(f"<{name}>")
|
||||
|
||||
return ' '.join(result)
|
||||
return " ".join(result)
|
||||
|
||||
|
||||
class HelpPaginator(Pages):
|
||||
def __init__(self, ctx, entries, *, per_page=4):
|
||||
super().__init__(ctx,
|
||||
entries=entries,
|
||||
per_page=per_page,
|
||||
hide_no_results=True)
|
||||
super().__init__(ctx, entries=entries, per_page=per_page, hide_no_results=True)
|
||||
self.reaction_emojis.append(
|
||||
('\N{WHITE QUESTION MARK ORNAMENT}', self.show_bot_help))
|
||||
("\N{WHITE QUESTION MARK ORNAMENT}", self.show_bot_help)
|
||||
)
|
||||
self.total = len(entries)
|
||||
|
||||
@classmethod
|
||||
@@ -630,12 +650,11 @@ class HelpPaginator(Pages):
|
||||
|
||||
# remove the ones we can't run
|
||||
entries = [
|
||||
cmd for cmd in entries
|
||||
if (await _can_run(cmd, ctx)) and not cmd.hidden
|
||||
cmd for cmd in entries if (await _can_run(cmd, ctx)) and not cmd.hidden
|
||||
]
|
||||
|
||||
self = cls(ctx, entries)
|
||||
self.title = f'{cog_name} Commands'.upper()
|
||||
self.title = f"{cog_name} Commands".upper()
|
||||
self.description = inspect.getdoc(cog)
|
||||
self.prefix = cleanup_prefix(ctx.bot, ctx.prefix)
|
||||
|
||||
@@ -651,17 +670,16 @@ class HelpPaginator(Pages):
|
||||
entries = []
|
||||
else:
|
||||
entries = [
|
||||
cmd for cmd in entries
|
||||
if (await _can_run(cmd, ctx)) and not cmd.hidden
|
||||
cmd for cmd in entries if (await _can_run(cmd, ctx)) and not cmd.hidden
|
||||
]
|
||||
|
||||
self = cls(ctx, entries)
|
||||
self.title = command.signature
|
||||
|
||||
if command.description:
|
||||
self.description = f'{command.description}\n\n{command.help}'
|
||||
self.description = f"{command.description}\n\n{command.help}"
|
||||
else:
|
||||
self.description = command.help or 'No help given.'
|
||||
self.description = command.help or "No help given."
|
||||
|
||||
self.prefix = cleanup_prefix(ctx.bot, ctx.prefix)
|
||||
return self
|
||||
@@ -669,7 +687,7 @@ class HelpPaginator(Pages):
|
||||
@classmethod
|
||||
async def from_bot(cls, ctx):
|
||||
def key(c):
|
||||
return c.cog_name or '\u200bMisc'
|
||||
return c.cog_name or "\u200bMisc"
|
||||
|
||||
entries = sorted(ctx.bot.commands, key=key)
|
||||
nested_pages = []
|
||||
@@ -681,8 +699,7 @@ class HelpPaginator(Pages):
|
||||
|
||||
for cog, commands in itertools.groupby(entries, key=key):
|
||||
plausible = [
|
||||
cmd for cmd in commands
|
||||
if (await _can_run(cmd, ctx)) and not cmd.hidden
|
||||
cmd for cmd in commands if (await _can_run(cmd, ctx)) and not cmd.hidden
|
||||
]
|
||||
if len(plausible) == 0:
|
||||
continue
|
||||
@@ -691,14 +708,14 @@ class HelpPaginator(Pages):
|
||||
if description is None:
|
||||
description = discord.Embed.Empty
|
||||
else:
|
||||
description = inspect.getdoc(
|
||||
description) or discord.Embed.Empty
|
||||
description = inspect.getdoc(description) or discord.Embed.Empty
|
||||
|
||||
nested_pages.extend((cog, description, plausible[i:i + per_page])
|
||||
for i in range(0, len(plausible), per_page))
|
||||
nested_pages.extend(
|
||||
(cog, description, plausible[i : i + per_page])
|
||||
for i in range(0, len(plausible), per_page)
|
||||
)
|
||||
|
||||
self = cls(ctx, nested_pages,
|
||||
per_page=1) # this forces the pagination session
|
||||
self = cls(ctx, nested_pages, per_page=1) # this forces the pagination session
|
||||
self.prefix = cleanup_prefix(ctx.bot, ctx.prefix)
|
||||
|
||||
# swap the get_page implementation with
|
||||
@@ -713,7 +730,7 @@ class HelpPaginator(Pages):
|
||||
# noinspection PyAttributeOutsideInit
|
||||
def get_bot_page(self, page):
|
||||
cog, description, commands = self.entries[page - 1]
|
||||
self.title = f'{cog} Commands'
|
||||
self.title = f"{cog} Commands"
|
||||
self.description = description
|
||||
return commands
|
||||
|
||||
@@ -734,13 +751,15 @@ class HelpPaginator(Pages):
|
||||
signature = _command_signature
|
||||
|
||||
for entry in entries:
|
||||
self.embed.add_field(name=signature(entry),
|
||||
value=entry.short_doc or "No help given",
|
||||
inline=False)
|
||||
self.embed.add_field(
|
||||
name=signature(entry),
|
||||
value=entry.short_doc or "No help given",
|
||||
inline=False,
|
||||
)
|
||||
|
||||
if self.maximum_pages:
|
||||
self.embed.set_author(
|
||||
name=f'Page {page}/{self.maximum_pages} ({self.total} commands)'
|
||||
name=f"Page {page}/{self.maximum_pages} ({self.total} commands)"
|
||||
)
|
||||
|
||||
if not self.paginating:
|
||||
@@ -752,7 +771,7 @@ class HelpPaginator(Pages):
|
||||
|
||||
self.message = await self.channel.send(embed=self.embed)
|
||||
for (reaction, _) in self.reaction_emojis:
|
||||
if self.maximum_pages == 2 and reaction in ('\u23ed', '\u23ee'):
|
||||
if self.maximum_pages == 2 and reaction in ("\u23ed", "\u23ee"):
|
||||
# no |<< or >>| buttons if we only have two pages
|
||||
# we can't forbid it if someone ends up using it but remove
|
||||
# it from the default set
|
||||
@@ -763,19 +782,20 @@ class HelpPaginator(Pages):
|
||||
async def show_help(self):
|
||||
"""shows this message"""
|
||||
|
||||
self.embed.title = 'Paginator help'
|
||||
self.embed.description = 'Hello! Welcome to the help page.'
|
||||
self.embed.title = "Paginator help"
|
||||
self.embed.description = "Hello! Welcome to the help page."
|
||||
|
||||
messages = [
|
||||
f'{emoji} {func.__doc__}' for emoji, func in self.reaction_emojis
|
||||
]
|
||||
messages = [f"{emoji} {func.__doc__}" for emoji, func in self.reaction_emojis]
|
||||
self.embed.clear_fields()
|
||||
self.embed.add_field(name='What are these reactions for?',
|
||||
value='\n'.join(messages),
|
||||
inline=False)
|
||||
self.embed.add_field(
|
||||
name="What are these reactions for?",
|
||||
value="\n".join(messages),
|
||||
inline=False,
|
||||
)
|
||||
|
||||
self.embed.set_footer(
|
||||
text=f'We were on page {self.current_page} before this message.')
|
||||
text=f"We were on page {self.current_page} before this message."
|
||||
)
|
||||
await self.message.edit(embed=self.embed)
|
||||
|
||||
async def go_back_to_current_page():
|
||||
@@ -787,31 +807,34 @@ class HelpPaginator(Pages):
|
||||
async def show_bot_help(self):
|
||||
"""shows how to use the bot"""
|
||||
|
||||
self.embed.title = 'Using the bot'
|
||||
self.embed.description = 'Hello! Welcome to the help page.'
|
||||
self.embed.title = "Using the bot"
|
||||
self.embed.description = "Hello! Welcome to the help page."
|
||||
self.embed.clear_fields()
|
||||
|
||||
entries = (('<argument>',
|
||||
'This means the argument is __**required**__.'),
|
||||
('[argument]',
|
||||
'This means the argument is __**optional**__.'),
|
||||
('[A|B]',
|
||||
'This means the it can be __**either A or B**__.'),
|
||||
('[argument...]',
|
||||
'This means you can have multiple arguments.\n'
|
||||
'Now that you know the basics, it should be '
|
||||
'noted that...\n'
|
||||
'__**You do not type in the brackets!**__'))
|
||||
entries = (
|
||||
("<argument>", "This means the argument is __**required**__."),
|
||||
("[argument]", "This means the argument is __**optional**__."),
|
||||
("[A|B]", "This means the it can be __**either A or B**__."),
|
||||
(
|
||||
"[argument...]",
|
||||
"This means you can have multiple arguments.\n"
|
||||
"Now that you know the basics, it should be "
|
||||
"noted that...\n"
|
||||
"__**You do not type in the brackets!**__",
|
||||
),
|
||||
)
|
||||
|
||||
self.embed.add_field(
|
||||
name='How do I use this bot?',
|
||||
value='Reading the bot signature is pretty simple.')
|
||||
name="How do I use this bot?",
|
||||
value="Reading the bot signature is pretty simple.",
|
||||
)
|
||||
|
||||
for name, value in entries:
|
||||
self.embed.add_field(name=name, value=value, inline=False)
|
||||
|
||||
self.embed.set_footer(
|
||||
text=f'We were on page {self.current_page} before this message.')
|
||||
text=f"We were on page {self.current_page} before this message."
|
||||
)
|
||||
await self.message.edit(embed=self.embed)
|
||||
|
||||
async def go_back_to_current_page():
|
||||
|
||||
Reference in New Issue
Block a user