Skip to content

Commit

Permalink
Update requirements slightly. Add wavelink inactivity listener to dc …
Browse files Browse the repository at this point in the history
…after a certain period of time. Bump version.
  • Loading branch information
Sachaa-Thanasius committed Jun 22, 2024
1 parent f976ae8 commit 003380e
Show file tree
Hide file tree
Showing 8 changed files with 45 additions and 31 deletions.
2 changes: 1 addition & 1 deletion core/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ async def setup_hook(self) -> None:
await self._load_extensions()

# Connect to lavalink node(s).
node = wavelink.Node(uri=CONFIG.lavalink.uri, password=CONFIG.lavalink.password)
node = wavelink.Node(uri=CONFIG.lavalink.uri, password=CONFIG.lavalink.password, inactive_player_timeout=600)
await wavelink.Pool.connect(client=self, nodes=[node])

# Get information about owner.
Expand Down
3 changes: 2 additions & 1 deletion core/utils/embeds.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,8 @@ def add_leaderboard_fields(
"""

# Add the leaderboard fields - the emojis will be cycled over.
for rank, (content, emoji) in enumerate(zip(ldbd_content, itertools.cycle(ldbd_emojis), strict=False)):
# For the pyright: ignore below: Regresion in enumerate's typing?
for rank, (content, emoji) in enumerate(zip(ldbd_content, itertools.cycle(ldbd_emojis), strict=False)): # pyright: ignore [reportUnknownVariableType]
field_prefix = f"{emoji} {rank + 1} " if is_ranked else f"{emoji} "
field_name = field_prefix + name_format.format(str(content[0]))
field_value = value_format.format(*content[1:])
Expand Down
2 changes: 1 addition & 1 deletion core/utils/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def html_to_markdown(node: lxml.html.HtmlElement, *, include_spans: bool = False

if child.tag in {"i", "em"}:
text.append(f"{before_ws}{italics_marker}{child_text}{italics_marker}{after_ws}")
if italics_marker == "*": # type: ignore
if italics_marker == "*": # type: ignore # Pyright bug?
italics_marker = "_"
elif child.tag in {"b", "strong"}:
if text and text[-1].endswith("*"):
Expand Down
6 changes: 3 additions & 3 deletions exts/dice.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def roll_custom_dice_expression(expression: str) -> tuple[str, int]:
components.append(sum(rolls))
else:
return f"(Invalid expression; expected number or dice expression, not {part!r})", 0
else:
else: # noqa: PLR5501
if part == "-":
operations.append(operator.sub)
elif part == "+":
Expand Down Expand Up @@ -625,7 +625,7 @@ async def roll(ctx: core.Context, expression: str | None = None) -> None:
await ctx.send(embed=embed, view=view)


@roll.error
@roll.error # pyright: ignore [reportUnknownMemberType] # discord.py bug: see https://github.com/Rapptz/discord.py/issues/9788.
async def roll_error(ctx: core.Context, error: commands.CommandError) -> None:
# Extract the original error.
error = getattr(error, "original", error)
Expand All @@ -639,4 +639,4 @@ async def setup(bot: core.Beira) -> None:
"""Add roll command and persistent dice view to bot."""

bot.add_view(DiceView())
bot.add_command(roll)
bot.add_command(roll) # pyright: ignore [reportUnknownArgumentType] # See roll_error link.
2 changes: 1 addition & 1 deletion exts/fandom_wiki.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ async def process_fandom_page(session: aiohttp.ClientSession, url: str) -> tuple
to_look_for = [".//aside[contains(@class, 'portable-infobox')]", ".//div[@id='toc']", ".//h2"]

for index, node in enumerate(content.xpath(" | ".join(to_look_for))):
if (node.tag == "div" or node.tag == "h2") and summary_end_index == 0 and index > summary_end_index:
if (node.tag in {"div", "h2"}) and summary_end_index == 0 and index > summary_end_index:
summary_end_index = index

node.getparent().remove(node)
Expand Down
14 changes: 12 additions & 2 deletions exts/music.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,13 @@ async def on_wavelink_track_start(self, payload: wavelink.TrackStartEventPayload
current_embed = create_track_embed("Now Playing", payload.original or payload.track)
await player.channel.send(embed=current_embed)

@commands.Cog.listener()
async def on_wavelink_inactive_player(self, player: wavelink.Player) -> None:
await player.channel.send(
f"The player has been inactive for `{player.inactive_timeout}` seconds. Disconnecting now. Goodbye!"
)
await player.disconnect()

@commands.hybrid_group()
@commands.guild_only()
async def music(self, ctx: core.GuildContext) -> None:
Expand Down Expand Up @@ -254,12 +261,15 @@ async def play(self, ctx: core.GuildContext, query: str, _channel: discord.Voice
await ctx.send(f"Could not find any tracks based on the given query: `{query}`.")

if isinstance(tracks, wavelink.Playlist):
tracks.extras = {"requester": ctx.author.mention}
try:
tracks.extras.requester = ctx.author.mention
except AttributeError:
tracks.extras = {"requester": ctx.author.mention}
added = await vc.queue.put_wait(tracks)
await ctx.send(f"Added {added} tracks from the `{tracks.name}` playlist to the queue.")
else:
track = tracks[0]
track.extras = {"requester": ctx.author.mention}
track.extras.requester = ctx.author.mention
await vc.queue.put_wait(track)
await ctx.send(f"Added `{track.title}` to the queue.")

Expand Down
43 changes: 23 additions & 20 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "Beira"
version = "2024.04.15"
version = "2024.06.22"
description = "An personal Discord bot made in Python."
readme = "README.md"
license = { file = "LICENSE" }
Expand Down Expand Up @@ -39,44 +39,47 @@ select = [
"PIE",
"T20",
"PYI",
"PT",
"RSE",
"RET",
"SIM",
"TID",
"PTH",
"ERA",
"PD",
"PL",
"TRY",
"NPY",
"RUF",
]
extend-ignore = [
"S101", # Use of assert here is a known quantity. Blame typing memes.
# "PLR2004", # Magic value comparison. May remove later.
"SIM105", # Suppressable exception. I'm not paying the overhead of contextlib.suppress for stylistic choices.
"C90", # McCabe complexity memes.
"PD011", # Erroneous issue that triggers for any .values attribute access at all.
"S311", # No need for cryptographically secure random number generation in this use case.
"ANN101", # Type of self is implicit.
"ANN102", # Type of cls is implicit.
"ANN204", # Special method return types are known by type checker.
"ANN401", # Not sure how else to type *args and **kwargs when they could be anything.
"PLR", # Complexity things.
"PYI036", # Bug with annotations for __exit__.
# Recommended by Ruff when using Ruff format.
ignore = [
"S101", # Allow use of assert for typing reasons.
"PLR2004", # Magic value comparison.
"SIM105", # Suppressable exception. contextlib.suppress is a stylistic choice with overhead.
"ANN101", # Type of Self for self is usually implicit.
"ANN102", # Type of type[Self] for cls is usually implicit.
"ANN204", # Special method return types are usually implicit or known by type checkers.
"ANN401", # Any is necessary sometimes.
"PT001", # pytest recommends against empty parentheses on pytest.fixture.
"UP038", # isinstance performs better with tuples than unions.
# == Recommended ignores by ruff when using ruff format.
"E111",
"E114",
"E117",
"Q003",
"D206",
"D300",
"COM812",
"COM819",
# "E501",
"ISC001",
"ISC002",
# == Project-specific ignores.
"S311", # No need for cryptographically secure number generation in this use case; it's just dice rolls.
"PLR0911", # Unlimited returns.
"PLR0912", # Unlimited branches.
"PLR0913", # Unlimited arguments.
"PYI036", # Bug with annotations for __(a)exit__ if a placeholder for a needed type exists in the else clause of an `if TYPE_CHECKING` block.
]
unfixable = [
"ERA", # Disallow erroneous detection into deletion.
"ERA", # Don't want erroneous deletion of comments.
]

[tool.ruff.lint.per-file-ignores]
Expand All @@ -98,4 +101,4 @@ typeCheckingMode = "strict"
# reportImportCycles = "warning"
reportPropertyTypeMismatch = "warning"
reportUnnecessaryTypeIgnoreComment = "warning"
enableExperimentalFeatures = true
enableExperimentalFeatures = true
4 changes: 2 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ async-lru
asyncpg==0.29.0
asyncpg-stubs==0.29.1
atlas-api @ https://github.com/Sachaa-Thanasius/atlas-api-wrapper/releases/download/v0.2.2/atlas_api-0.2.2-py3-none-any.whl
discord.py[speed,voice]>=2.3.2
discord.py[speed,voice]>=2.4.0
fichub-api @ https://github.com/Sachaa-Thanasius/fichub-api/releases/download/v0.2.2/fichub_api-0.2.2-py3-none-any.whl
importlib_resources; python_version < "3.12"
jishaku @ git+https://github.com/Gorialis/jishaku@a6661e2813124fbfe53326913e54f7c91e5d0dec
Expand All @@ -15,7 +15,7 @@ msgspec[toml]
openpyxl
Pillow>=10.0.0
types-lxml
wavelink>=3.2.0
wavelink>=3.4.0

# To be used later:
# parsedatetime
Expand Down

0 comments on commit 003380e

Please sign in to comment.