13 Commits

Author SHA1 Message Date
3201026242 Update paginator.py 2021-10-09 22:16:57 +02:00
f7398c9acd Fix paginator.py typo 2021-10-09 21:00:58 +02:00
d06bfce837 Include minimal working example 2021-10-09 20:57:02 +02:00
cb782ce3d8 Update paginator.py 2021-10-09 20:40:44 +02:00
fae85d072f Black paginator.py with 120 char limit per line 2021-10-09 20:37:26 +02:00
c74fd90a9c Update paginator.py 2021-10-09 20:29:00 +02:00
7228ef64a5 Create a working button paginator
Simple Embed paginator that I've been using for a while. Thought it could help others too.
2021-10-09 19:03:16 +02:00
0abac8698d Fix slash command flag parsing
Also removes the extra space at the end of fake message content
2021-10-08 20:06:05 +01:00
d781af8be5 Remove maintainer list from README.rst
This list became outdated straight away, and is a bad idea in general.
2021-10-08 18:24:22 +01:00
9e31aad96d Fix code style issues with Black 2021-10-07 17:34:29 +01:00
eca1d9a470 Sort events by categories (#88) 2021-10-07 16:48:38 +01:00
0bbcfd7f33 Update resource links (#65)
* Updated links

* Remove github discussions from getting help
2021-10-06 20:32:48 +01:00
ec1e2add21 Update user-agent (#92) 2021-10-04 21:11:10 +01:00
10 changed files with 886 additions and 661 deletions

View File

@ -17,18 +17,6 @@ The Future of enhanced-discord.py
--------------------------
Enhanced discord.py is a fork of Rapptz's discord.py, that went unmaintained (`gist <https://gist.github.com/Rapptz/4a2f62751b9600a31a0d3c78100287f1>`_)
It is currently maintained by (in alphabetical order)
- Chillymosh#8175
- Daggy#9889
- dank Had0cK#6081
- Dutchy#6127
- Eyesofcreeper#0001
- Gnome!#6669
- IAmTomahawkx#1000
- Jadon#2494
An overview of added features is available on the `custom features page <https://enhanced-dpy.readthedocs.io/en/latest/index.html#custom-features>`_.
Key Features

View File

@ -122,7 +122,7 @@ class _FakeSlashMessage(discord.PartialMessage):
def mentions(self) -> List[Union[discord.Member, discord.User]]:
client = self._state._get_client()
if self.guild:
ensure_user = lambda id: self.guild.get_member(id) or client.get_user(id) # type: ignore
ensure_user = lambda id: self.guild.get_member(id) or client.get_user(id) # type: ignore
else:
ensure_user = client.get_user
@ -1292,7 +1292,7 @@ class BotBase(GroupMixin):
# Make our fake message so we can pass it to ext.commands
message: discord.Message = _FakeSlashMessage.from_interaction(interaction, channel) # type: ignore
message.content = f"/{command_name} "
message.content = f"/{command_name}"
# Add arguments to fake message content, in the right order
ignore_params: List[inspect.Parameter] = []
@ -1307,7 +1307,7 @@ class BotBase(GroupMixin):
else:
prefix = param.annotation.__commands_flag_prefix__
delimiter = param.annotation.__commands_flag_delimiter__
message.content += f"{prefix}{name} {option['value']}{delimiter}" # type: ignore
message.content += f" {prefix}{name}{delimiter}{option['value']}" # type: ignore
continue
option = next((o for o in command_options if o["name"] == name), None)
@ -1323,9 +1323,9 @@ class BotBase(GroupMixin):
):
# String with space in without "consume rest"
option = cast(_ApplicationCommandInteractionDataOptionString, option)
message.content += f"{_quote_string_safe(option['value'])} "
message.content += f" {_quote_string_safe(option['value'])}"
else:
message.content += f'{option.get("value", "")} '
message.content += f' {option.get("value", "")}'
ctx = await self.get_context(message)
ctx._ignored_params = ignore_params

View File

@ -1694,7 +1694,9 @@ class Group(GroupMixin[CogT], Command[CogT, P, T]):
"name": self.name,
"type": int(not (nested - 1)) + 1,
"description": self.short_doc or "no description",
"options": [cmd.to_application_command(nested=nested + 1) for cmd in sorted(self.commands, key=lambda x: x.name)],
"options": [
cmd.to_application_command(nested=nested + 1) for cmd in sorted(self.commands, key=lambda x: x.name)
],
}

View File

@ -455,7 +455,7 @@ class BadInviteArgument(BadArgument):
This inherits from :exc:`BadArgument`
.. versionadded:: 1.5
Attributes
-----------
argument: :class:`str`

View File

@ -188,8 +188,8 @@ class HTTPClient:
self.proxy_auth: Optional[aiohttp.BasicAuth] = proxy_auth
self.use_clock: bool = not unsync_clock
user_agent = "DiscordBot (https://github.com/Rapptz/discord.py {0}) Python/{1[0]}.{1[1]} aiohttp/{2}"
self.user_agent: str = user_agent.format(__version__, sys.version_info, aiohttp.__version__)
u_agent = "DiscordBot (https://github.com/iDevision/enhanced-discord.py {0}) Python/{1[0]}.{1[1]} aiohttp/{2}"
self.user_agent: str = u_agent.format(__version__, sys.version_info, aiohttp.__version__)
def recreate(self) -> None:
if self.__session.closed:

View File

@ -84,7 +84,6 @@ __all__ = (
"escape_mentions",
"as_chunks",
"format_dt",
"generate_snowflake",
)
DISCORD_EPOCH = 1420070400000
@ -1021,23 +1020,3 @@ def format_dt(dt: datetime.datetime, /, style: Optional[TimestampStyle] = None)
if style is None:
return f"<t:{int(dt.timestamp())}>"
return f"<t:{int(dt.timestamp())}:{style}>"
def generate_snowflake(dt: Optional[datetime.datetime] = None) -> int:
"""Returns a numeric snowflake pretending to be created at the given date but more accurate and random than time_snowflake.
If No dt is not passed, it makes one from the current time using utcnow.
Parameters
-----------
dt: :class:`datetime.datetime`
A datetime object to convert to a snowflake.
If naive, the timezone is assumed to be local time.
Returns
--------
:class:`int`
The snowflake representing the time given.
"""
dt = dt or utcnow()
return int(dt.timestamp() * 1000 - DISCORD_EPOCH) << 22 | 0x3fffff

File diff suppressed because it is too large Load Diff

View File

@ -49,7 +49,7 @@ autodoc_typehints = "none"
# napoleon_attr_annotations = False
extlinks = {
"issue": ("https://github.com/Rapptz/discord.py/issues/%s", "GH-"),
"issue": ("https://github.com/iDevision/enhanced-discord.py/issues/%s", "GH-"),
}
# Links used for cross-referencing stuff in other documentation
@ -168,9 +168,8 @@ html_context = {
resource_links = {
"discord": "https://discord.gg/TvqYBrGXEm",
"issues": "https://github.com/Rapptz/discord.py/issues",
"discussions": "https://github.com/Rapptz/discord.py/discussions",
"examples": f"https://github.com/Rapptz/discord.py/tree/{branch}/examples",
"issues": "https://github.com/iDevision/enhanced-discord.py/issues",
"examples": f"https://github.com/iDevision/enhanced-discord.py/tree/{branch}/examples",
}
# Theme options are theme-specific and customize the look and feel of a theme

View File

@ -38,7 +38,6 @@ If you're having trouble with something, these resources might help.
- Ask us and hang out with us in our :resource:`Discord <discord>` server.
- If you're looking for something specific, try the :ref:`index <genindex>` or :ref:`searching <search>`.
- Report bugs in the :resource:`issue tracker <issues>`.
- Ask in our :resource:`GitHub discussions page <discussions>`.
Extensions
------------

210
examples/views/paginator.py Normal file
View File

@ -0,0 +1,210 @@
import discord
from discord.ext import commands
from discord import ButtonStyle, Embed, Interaction
from discord.ui import Button, View
class Bot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=commands.when_mentioned_or("$"), intents=discord.Intents(guilds=True, messages=True)
)
async def on_ready(self):
print(f"Logged in as {self.user} (ID: {self.user.id})")
print("------")
# Define 3 View subclasses that we will switch between depending on if we are viewing the first page, a page in the middle, or the last page.
# The first page has the "left" button disabled, because there is no left page to go to
class FirstPageComps(View):
def __init__(
self,
author_id: int,
):
super().__init__()
self.value = None
self.author_id = author_id
async def interaction_check(
self,
interaction: Interaction,
):
return interaction.user.id == self.author_id
@discord.ui.button(
style=ButtonStyle.primary,
disabled=True,
label="Left",
)
async def left(
self,
button: discord.ui.Button,
interaction: Interaction,
):
self.value = "left"
self.stop()
@discord.ui.button(
style=ButtonStyle.primary,
label="Right",
)
async def right(
self,
button: discord.ui.Button,
interaction: Interaction,
):
self.value = "right"
self.stop()
# The middle pages have both left and right buttons available
class MiddlePageComps(View):
def __init__(
self,
author_id: int,
):
super().__init__()
self.value = None
self.author_id = author_id
async def interaction_check(
self,
interaction: Interaction,
):
return interaction.user.id == self.author_id
@discord.ui.button(
style=ButtonStyle.primary,
label="Left",
)
async def left(
self,
button: discord.ui.Button,
interaction: Interaction,
):
self.value = "left"
self.stop()
@discord.ui.button(
style=ButtonStyle.primary,
label="Right",
)
async def right(
self,
button: discord.ui.Button,
interaction: Interaction,
):
self.value = "right"
self.stop()
# The last page has the right button disabled, because there's no right page to go to
class LastPageComps(View):
def __init__(
self,
author_id: int,
):
super().__init__()
self.value = None
self.author_id = author_id
async def interaction_check(
self,
interaction: Interaction,
):
return interaction.user.id == self.author_id
@discord.ui.button(
style=ButtonStyle.primary,
label="Left",
)
async def left(
self,
button: discord.ui.Button,
interaction: Interaction,
):
self.value = "left"
self.stop()
@discord.ui.button(
style=ButtonStyle.primary,
label="Right",
disabled=True,
)
async def right(
self,
button: discord.ui.Button,
interaction: Interaction,
):
self.value = "right"
self.stop()
# Now we define the function that will take care of the pagination for us. It will take a list of Embeds and allow the user to cycle between them using left/right buttons
# There is also an optional title parameter in case you want to give your paginator a title, it will display in the embed title, for example if the title is Book
# then the title will look like "Book | Page 1/2". This is very optional and can be removed
async def paginate(
ctx,
pages: list,
title: str = None,
):
total_pages = len(pages)
first_page = pages[0]
last_page = pages[-1]
current_page = first_page
index = 0
embed = first_page
if title:
embed.title = f"{title} | Page {index+1}/{total_pages}"
view = FirstPageComps(ctx.author.id)
# Here we send the message with the view of the first page and the FirstPageComps buttons
msg = await ctx.send(
embed=embed,
view=view,
)
# The default timeout for Views is 3 minutes, but if a user selects to scroll between pages the timer will be reset.
# If the timer reaches 0, though, the loop will just silently stop.
while True:
wait = await view.wait()
if wait:
return
if view.value == "right":
index += 1
current_page = pages[index]
view = MiddlePageComps(ctx.author.id) if current_page != last_page else LastPageComps(ctx.author.id)
embed = current_page
if title:
embed.title = f"{title} | Page {index+1}/{total_pages}"
elif view.value == "left":
index -= 1
current_page = pages[index]
view = MiddlePageComps(ctx.author.id) if current_page != first_page else FirstPageComps(ctx.author.id)
embed = current_page
if title:
embed.title = f"{title} | Page {index+1}/{total_pages}"
await msg.edit(
embed=embed,
view=view,
)
bot = Bot()
# To test our new function, let's create a list of a couple Embeds and let our paginator deal with the sending and buttons
@bot.command()
async def sendpages(ctx):
page1 = Embed(description="This is page 1")
page2 = Embed(description="This is page 2")
page3 = Embed(description="This is page 3")
await paginate(ctx, [page1, page2, page3])
bot.run("token")