Compare commits

..

No commits in common. "main" and "1.1.1" have entirely different histories.
main ... 1.1.1

58 changed files with 852 additions and 6306 deletions

12
.gitignore vendored
View File

@ -3,15 +3,3 @@
__pycache/ __pycache/
dist/ dist/
pomice.egg-info/ pomice.egg-info/
docs/_build/
build/
.gitpod.yml
.python-version
Pipfile.lock
.mypy_cache/
.vscode/
.idea/
.venv/
*.code-workspace
*.ini
.pypirc

View File

@ -1,33 +0,0 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: check-ast
- id: check-builtin-literals
- id: debug-statements
- id: end-of-file-fixer
- id: requirements-txt-fixer
- id: trailing-whitespace
- repo: https://github.com/psf/black
rev: 23.10.1
hooks:
- id: black
language_version: python3.13
- repo: https://github.com/asottile/pyupgrade
rev: v3.15.0
hooks:
- id: pyupgrade
args: [--py37-plus, --keep-runtime-typing]
- repo: https://github.com/asottile/reorder-python-imports
rev: v3.12.0
hooks:
- id: reorder-python-imports
- repo: https://github.com/asottile/add-trailing-comma
rev: v3.1.0
hooks:
- id: add-trailing-comma
default_language_version:
python: python3.13

View File

@ -1,15 +0,0 @@
version: 2
build:
os: ubuntu-22.04
tools:
python: "3.8"
sphinx:
configuration: docs/conf.py
python:
install:
- requirements: docs/requirements_rtd.txt

View File

@ -1,18 +0,0 @@
prepare:
pipenv install --dev
pipenv run pre-commit install
shell:
pipenv shell
lint:
pipenv run pre-commit run --all-files
test:
pipenv run mypy
serve-docs:
@cd docs;\
make html;\
cd _build/html;\
python -m http.server;\

21
Pipfile
View File

@ -1,21 +0,0 @@
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[packages]
orjson = "*"
"discord.py" = {extras = ["voice"], version = "*"}
websockets = "*"
[dev-packages]
mypy = "*"
pre-commit = "*"
furo = "*"
sphinx = "*"
myst-parser = "*"
black = "*"
typing-extensions = "*"
[requires]
python_version = "3.8"

View File

@ -2,17 +2,14 @@
![](https://raw.githubusercontent.com/cloudwithax/pomice/main/banner.jpg) ![](https://raw.githubusercontent.com/cloudwithax/pomice/main/banner.jpg)
The modern [Lavalink](https://github.com/freyacodes/Lavalink) wrapper designed for [discord.py](https://github.com/Rapptz/discord.py)
[![GPL](https://img.shields.io/github/license/cloudwithax/pomice?color=2f2f2f)](https://github.com/cloudwithax/pomice/blob/main/LICENSE) ![](https://img.shields.io/pypi/pyversions/pomice?color=2f2f2f) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) ![](https://img.shields.io/badge/license-GPL-2f2f2f) ![](https://img.shields.io/badge/python-3.8-2f2f2f) ![](https://img.shields.io/discord/899324069235810315)
[![Discord](https://img.shields.io/discord/899324069235810315?color=%237289DA&label=Pomice%20Support&logo=discord&logoColor=white)](https://discord.gg/r64qjTSHG8) [![Read the Docs](https://readthedocs.org/projects/pomice/badge/?version=latest)](https://pomice.readthedocs.io/en/latest/)
This library is heavily based off of/uses code from the following libraries:
Pomice is a fully asynchronous Python library designed for communicating with [Lavalink](https://github.com/freyacodes/Lavalink) seamlessly within the [discord.py](https://github.com/Rapptz/discord.py) library. It features 100% coverage of the [Lavalink](https://github.com/freyacodes/Lavalink) spec that can be accessed with easy-to-understand functions along with Spotify and Apple Music querying capabilities using built-in custom clients, making it easier to develop your next big music bot. - [Wavelink](https://github.com/PythonistaGuild/Wavelink)
- [Slate](https://github.com/Axelancerr/slate)
## Quick Links - [Granitepy](https://github.com/twitch0001/granitepy)
- [Discord Server](https://discord.gg/r64qjTSHG8)
- [Read the Docs](https://pomice.readthedocs.io/en/latest/)
- [PyPI Homepage](https://pypi.org/project/pomice/)
# Install # Install
@ -28,15 +25,12 @@ pip install pomice
pip install git+https://github.com/cloudwithax/pomice pip install git+https://github.com/cloudwithax/pomice
``` ```
# Support And Documentation # Support
The official documentation is [here](https://pomice.readthedocs.io/en/latest/)
You can join our support server [here](https://discord.gg/r64qjTSHG8) You can join our support server [here](https://discord.gg/r64qjTSHG8)
# Examples # Examples
In-depth examples are located in the [examples folder](https://github.com/cloudwithax/pomice/tree/main/examples) In-depth examples are located in the examples folder
Here's a quick example: Here's a quick example:
@ -114,7 +108,7 @@ bot.run("token here")
# FAQ # FAQ
Why is it saying "Cannot connect to host"? Why is it saying "Cannot connect to host"?
- You need to have a Lavalink node setup before you can use this library. Download it [here](https://github.com/freyacodes/Lavalink/releases/latest) - You need to have a Lavalink node setup before you can use this library. Download it [here](https://github.com/freyacodes/Lavalink/releases/tag/3.3.2.5)
What experience do I need? What experience do I need?

View File

@ -1,20 +0,0 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

View File

@ -1,9 +0,0 @@
```{eval-rst}
Enums
-------------------
.. automodule:: pomice.enums
:members:
:undoc-members:
:show-inheritance:
```

View File

@ -1,9 +0,0 @@
```{eval-rst}
Events
--------------------
.. automodule:: pomice.events
:members:
:undoc-members:
:show-inheritance:
```

View File

@ -1,9 +0,0 @@
```{eval-rst}
Exceptions
------------------------
.. automodule:: pomice.exceptions
:members:
:undoc-members:
:show-inheritance:
```

View File

@ -1,9 +0,0 @@
```{eval-rst}
Filters
---------------------
.. automodule:: pomice.filters
:members:
:undoc-members:
:show-inheritance:
```

View File

@ -1,18 +0,0 @@
# API Reference
Here, you will find the different classes and methods used within Pomice.
```{toctree}
:maxdepth: 1
enums.md
events.md
exceptions.md
filters.md
objects.md
player.md
pool.md
queue.md
utils.md
```

View File

@ -1,9 +0,0 @@
```{eval-rst}
Objects
---------------------
.. automodule:: pomice.objects
:members:
:undoc-members:
:show-inheritance:
```

View File

@ -1,9 +0,0 @@
```{eval-rst}
Player
--------------------
.. automodule:: pomice.player
:members:
:undoc-members:
:show-inheritance:
```

View File

@ -1,9 +0,0 @@
```{eval-rst}
Pool
------------------
.. automodule:: pomice.pool
:members:
:undoc-members:
:show-inheritance:
```

View File

@ -1,9 +0,0 @@
```{eval-rst}
Queue
------------------
.. automodule:: pomice.queue
:members:
:undoc-members:
:show-inheritance:
```

View File

@ -1,9 +0,0 @@
```{eval-rst}
Utils
-------------------
.. automodule:: pomice.utils
:members:
:undoc-members:
:show-inheritance:
```

View File

@ -1,121 +0,0 @@
# type: ignore
import importlib
import inspect
import os
import sys
from typing import Any
from typing import Dict
sys.path.insert(0, os.path.abspath("."))
sys.path.insert(0, os.path.abspath(".."))
project = "Pomice"
copyright = "2023, cloudwithax"
author = "cloudwithax"
release = "2.2"
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"sphinx.ext.linkcode",
"myst_parser",
]
myst_enable_extensions = [
"amsmath",
"colon_fence",
"deflist",
"dollarmath",
"fieldlist",
"html_admonition",
"html_image",
"replacements",
"smartquotes",
"strikethrough",
"substitution",
"tasklist",
]
myst_heading_anchors = 3
templates_path = ["_templates"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# We need to include this because discord.py has special tags
# they inlcude within their docstrings that dont parse
# right within our docs
rst_prolog = """
.. |coro| replace:: This function is a |coroutine_link|_.
.. |maybecoro| replace:: This function *could be a* |coroutine_link|_.
.. |coroutine_link| replace:: *coroutine*
.. _coroutine_link: https://docs.python.org/3/library/asyncio-task.html#coroutine
"""
html_theme = "furo"
html_static_path = ["_static"]
html_title = "Pomice"
language = "en"
html_theme_options: Dict[str, Any] = {
"footer_icons": [
{
"name": "GitHub",
"url": "https://github.com/cloudwithax/pomice",
"html": """
<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"></path>
</svg>
""",
"class": "",
},
],
"source_repository": "https://github.com/cloudwithax/pomice",
"source_branch": "main",
"source_directory": "docs/",
}
# Grab lines from source files and embed into the docs
# so theres a point of reference
def linkcode_resolve(domain, info):
# i absolutely MUST add this here or else
# the docs will not build. fuck sphinx
try:
if domain != "py":
return None
if not info["module"]:
return None
mod = importlib.import_module(info["module"])
if "." in info["fullname"]:
objname, attrname = info["fullname"].split(".")
obj = getattr(mod, objname)
try:
obj = getattr(obj, attrname)
except AttributeError:
return None
else:
obj = getattr(mod, info["fullname"])
try:
file = inspect.getsourcefile(obj)
lines = inspect.getsourcelines(obj)
except TypeError:
# e.g. object is a typing.Union
return None
file = os.path.relpath(file, os.path.abspath(".."))
start, end = lines[1], lines[1] + len(lines[0]) - 1
return f"https://github.com/cloudwithax/pomice/blob/main/{file}#L{start}-L{end}"
except:
pass

View File

@ -1,27 +0,0 @@
# Frequently Asked Questions
> Why is it saying "Cannot connect to host"?
Here are some common issues:
- You don't have a Lavalink node installed
- You have a Lavalink node, but it's not configured properly
- You have a Lavalink node and it's configured properly, but is unreachable due to firewall rules or a malformed network configuration.
If you are experiencing the first issue, you can download Lavalink [here.](https://github.com/freyacodes/Lavalink/releases/latest)
As for the other listed issues, either consult the Lavalink docs or go through the proper support channels for your specfic issue at hand.
For any other issues not listed here, please consult your preferred resource for more information.
> What experience do I need?
This library assumes that you have some experience with Python, asynchronous programming and the discord.py library.
> How do I install Pomice?
Refer to the [Installation](installation.md) section.
> How do I use Pomice?
If you are interested in learning how Pomice works, refer to the [API Reference](api/index.md) section.
If you want a quick example, refer to the [Quickstart](quickstart.md) section.

View File

@ -1,47 +0,0 @@
# Use the Events class
Pomice has different events that are triggered depending on events that Lavalink emits:
- `Event.TrackEndEvent()`
- `Event.TrackExceptionEvent()`
- `Event.TrackStartEvent()`
- `Event.TrackStuckEvent()`
- `Event.WebsoocketClosedEvent()`
- `Event.WebsocketOpenEvent()`
The classes listed here are as they appear in Pomice. When you use them within your application,
the way you use them will be different. Here's an example on how you would use the `TrackStartEvent` within an event listener in a cog:
```py
@commands.Cog.listener
async def on_pomice_track_start(self, player: Player, track: Track):
...
```
## Event definitions
Each event within Pomice has an event definition you can use to listen for said event within
your application. Here are all the definitions:
- `Event.TrackEndEvent()` -> `on_pomice_track_end`
- `Event.TrackExceptionEvent()` -> `on_pomice_track_exception`
- `Event.TrackStartEvent()` -> `on_pomice_track_start`
- `Event.TrackStuckEvent()` -> `on_pomice_track_stuck`
- `Event.WebsocketClosedEvent()` -> `on_pomice_websocket_closed`
- `Event.WebsocketOpenEvent()` -> `on_pomice_websocket_open`
All events related to tracks carry a `Player` object so you can access player-specific functions
and properties for further evaluation. They also carry a `Track` object so you can access track-specific functions and properties for further evaluation as well.
`Event.TrackEndEvent()` carries the reason for the track ending. If the track ends suddenly, you can use the reason provided to determine a solution.
`Event.TrackExceptionEvent()` carries the exception, or reason why the track failed to play. The format for the exception is `REASON: [SEVERITY]`.
`Event.TrackStuckEvent()` carries the threshold, or amount of time Lavalink will wait before it discards the stuck track and stops it from playing.
`Event.WebsocketClosedEvent()` carries a payload object that contains a `Guild` object, the code number, the reason for disconnect and whether or not it was by the
remote, or the node.
`Event.WebsocketOpenEvent()` carries a target, which is usually the node IP, and the SSRC, a 32-bit integer uniquely identifying the source of the RTP packets sent from
Lavalink.

View File

@ -1,186 +0,0 @@
# Use the Filter class
Pomice takes full advantage of the Lavalink filter system by using a unique system to apply filters on top of one another. We call this system "filter stacking". With this system, we can stack any filter on top of one another to produce one-of-a-kind audio effects on playback while still being able to easily manage each filters.
## Types of filters
Lavalink, and by extension, Pomice, has different types of filters you can use.
Here are the different types and what they do:
:::{list-table}
:header-rows: 1
* - Type
- Class
- Description
* - Channel Mix
- `pomice.ChannelMix()`
- Adjusts stereo panning of a track.
* - Distortion
- `pomice.Distortion()`
- Generates a distortion effect on a track.
* - Equalizer
- `pomice.Equalizer()`
- Represents a 15 band equalizer. You can adjust the dynamic of the sound using this filter.
* - Karaoke
- `pomice.Karaoke()`
- Filters the vocals from the track.
* - Low Pass
- `pomice.LowPass()`
- Filters out high frequencies and only lets low frequencies pass through.
* - Rotation
- `pomice.Rotation()`
- Produces a stereo-like panning effect, which sounds like the audio is being rotated around the listeners head
* - Timescale
- `pomice.Timescale()`
- Adjusts the speed and pitch of a track.
* - Tremolo
- `pomice.Tremolo()`
- Rapidly changes the volume of the track, producing a wavering tone.
* - Vibrato
- `pomice.Vibrato()`
- Rapidly changes the pitch of the track.
:::
Each filter has individual values you can adjust to fine-tune the sound of the filter. If you want to see what values each filter has, refer to [](../api/filters.md).
If you are stuck on what values adjust what, some filters include presets that you can apply to get a certain sound, i.e: `pomice.Timescale` has the `vaporwave()` and `nightcore()` and so on. You can also play around with the values and generate your own unique sound if you'd like.
## Adding a filter
:::{important}
You must have the `Player` class initialized first before using this. Refer to [](player.md)
:::
To add a filter, we need to use `Player.add_filter()`
```py
await Player.add_filter(...)
```
After you have initialized your function, we need to fill in the proper parameters:
:::{list-table}
:header-rows: 1
* - Name
- Type
- Description
* - `filter`
- `Filter`
- The filter to apply
* - `fast_apply`
- `bool`
- If set to `True`, the specified filter will apply (almost) instantly if a song is playing. Default value is `False`.
:::
After you set those parameters, your function should look something like this:
```py
await Player.add_filter(
filter=<your filter object here>,
fast_apply=<True/False>
)
```
After running this function, you should see your currently playing track sound different depending on the filter you chose.
## Removing a filter
:::{important}
You must have the `Player` class initialized first before using this. Refer to [](player.md)
:::
To remove a filter, we need to use `Player.remove_filter()`
```py
await Player.remove_filter(...)
```
After you have initialized your function, we need to fill in the proper parameters:
:::{list-table}
:header-rows: 1
* - Name
- Type
- Description
* - `filter`
- `Filter`
- The filter to remove
* - `fast_apply`
- `bool`
- If set to `True`, the specified filter will be removed (almost) instantly if a song is playing. Default value is `False`.
:::
After you set those parameters, your function should look something like this:
```py
await Player.remove_filter(
filter=<your filter object here>,
fast_apply=<True/False>
)
```
After running this function, you should see your currently playing track sound different depending on the filter you chose to remove.
## Resetting all filters
:::{important}
You must have the `Player` class initialized first before using this. Refer to [](player.md)
:::
To reset all filters, we need to use `Player.reset_filters()`
```py
await Player.reset_filters()
```
After you have initialized your function, you can optionally include the `fast_apply` parameter, which is a boolean. If this is set to `True`, it'll remove all filters (almost) instantly if theres a track playing.
```py
await Player.reset_filters(fast_apply=<True/False>)
```

View File

@ -1,16 +0,0 @@
# How Do I?
This section covers all the basic functions of Pomice and how to use them.
If you find the [API Reference](../api/index.md) section too confusing or would
rather have a straightforward explanation as to how to use a certain function,
this is for you.
```{toctree}
pool.md
node.md
player.md
filters.md
queue.md
events.md
```

View File

@ -1,182 +0,0 @@
# Use the Node class
The `Node` class is one of the main classes you will be interacting with when using Pomice.
The `Node` class has a couple functions you will be using frequently:
- `Node.get_player()`
- `Node.get_tracks()`
- `Node.get_recommendations()`
There are also properties the `Node` class has to access certain values:
:::{list-table}
:header-rows: 1
* - Property
- Type
- Description
* - `Node.bot`
- `Client`
- Returns the discord.py client linked to this node.
* - `Node.is_connected`
- `bool`
- Returns whether this node is connected or not.
* - `Node.latency` `Node.ping`
- `float`
- Returns the latency of the node.
* - `Node.player_count`
- `int`
- Returns how many players are connected to this node.
* - `Node.players`
- `Dict[int, Player]`
- Returns a dict containing the guild ID and the player object.
* - `Node.pool`
- `NodePool`
- Returns the pool this node is apart of.
* - `Node.stats`
- `NodeStats`
- Returns the nodes stats.
:::
## Getting a player
To get a player from the nodes list of players, we need to use `Node.get_player()`
```py
await Node.get_player(...)
```
After you have initialized your function, you need to specify the `guild_id` of the player.
```py
await Node.get_player(guild_id=<your guild ID here>)
```
If the node finds a player with the guild ID you provided, it'll return the [](../api/player.md) object associated with the guild ID.
## Getting tracks
To get tracks using Lavalink, we need to use `Node.get_tracks()`
You can also use `Player.get_tracks()` to do the same thing, but this can be used to fetch tracks regardless if a player exists.
```py
await Node.get_tracks(...)
```
After you have initialized your function, we need to fill in the proper parameters:
:::{list-table}
:header-rows: 1
* - Name
- Type
- Description
* - `query`
- `str`
- The string you want to search up
* - `ctx`
- `Optional[commands.Context]`
- Optional value which sets a `Context` object on the tracks you search.
* - `search_type`
- `SearchType`
- Enum which sets the provider to search from. Default value is `SearchType.ytsearch`
* - `filters`
- `Optional[List[Filter]]`
- Optional value which sets the filters that should apply when the track is played on the tracks you search.
:::
After you set those parameters, your function should look something like this:
```py
await Node.get_tracks(
query="<your query here>",
ctx=<optional ctx object here>,
search_type=<optional search type here>,
filters=[<optional filters here>]
)
```
:::{important}
All querying of Spotify and Apple Music tracks or playlists is handled in this function if you enabled that functionality when creating your node.
If you want to enable it, refer to [](pool.md#adding-a-node)
:::
You should get a list of `Track` in return after running this function for you to then do whatever you want with it.
Ideally, you should be putting all tracks into some sort of a queue. If you would like to learn about how to use
our queue implementation, you can refer to [](queue.md)
## Getting recommendations
To get recommadations using Lavalink, we need to use `Node.get_recommendations()`
You can also use `Player.get_recommendations()` to do the same thing, but this can be used to fetch recommendations regardless if a player exists.
```py
await Node.get_recommendations(...)
```
After you have initialized your function, we need to fill in the proper parameters:
:::{list-table}
:header-rows: 1
* - Name
- Type
- Description
* - `track`
- `Track`
- The track to fetch recommendations for
* - `ctx`
- `Optional[commands.Context]`
- Optional value which sets a `Context` object on the recommendations you fetch.
:::
After you set those parameters, your function should look something like this:
```py
await Node.get_recommendations(
track=<your track object here>,
ctx=<optional ctx object here>,
)
```
You should get a list of `Track` in return after running this function for you to then do whatever you want with it.
Ideally, you should be putting all tracks into some sort of a queue. If you would like to learn about how to use
our queue implementation, you can refer to [](queue.md)

View File

@ -1,501 +0,0 @@
# Use the Player class
The `Player` class is the class you will be interacting with the most within Pomice.
The `Player` class has a couple functions you will be using frequently:
- `Player.add_filter()`
- `Player.destroy()`
- `Player.get_recommendations()`
- `Player.get_tracks()`
- `Player.play()`
- `Player.remove_filter()`
- `Player.reset_filters()`
- `Player.seek()`
- `Player.set_pause()`
- `Player.set_volume()`
- `Player.stop()`
There are also properties the `Player` class has to access certain values:
:::{list-table}
:header-rows: 1
* - Property
- Type
- Description
* - `Player.bot`
- `Client`
- Returns the bot associated with this player instance.
* - `Player.current`
- `Track`
- Returns the currently playing track.
* - `Player.filters`
- `Filters`
- Returns the helper class for interacting with filters.
* - `Player.guild`
- `Guild`
- Returns the guild associated with the player.
* - `Player.is_connected`
- `bool`
- Returns whether or not the player is connected.
* - `Player.is_dead`
- `bool`
- Returns whether the player is dead or not. A player is considered dead if it has been destroyed and removed from stored players.
* - `Player.is_paused`
- `bool`
- Returns whether or not the player has a track which is paused or not.
* - `Player.is_playing`
- `bool`
- Returns whether or not the player is actively playing a track.
* - `Player.node`
- `Node`
- Returns the node the player is connected to.
* - `Player.position`
- `float`
- Returns the players position in a track in milliseconds.
* - `Player.adjusted_position`
- `float`
- Returns the players position in a track in milliseconds, adjusted for rate if affected.
* - `Player.adjusted_length`
- `float`
- Returns the current track length in milliseconds, adjusted for rate if affected.
* - `Player.rate`
- `float`
- Returns the players current rate, which represents the speed of the currently playing track. This rate is affected by the `Timescale` filter.
* - `Player.volume`
- `int`
- Returns the players current volume.
:::
## Getting tracks
To get tracks using Lavalink, we need to use `Player.get_tracks()`
You can also use `Node.get_tracks()` to do the same thing but without having a player.
```py
await Player.get_tracks(...)
```
After you have initialized your function, we need to fill in the proper parameters:
:::{list-table}
:header-rows: 1
* - Name
- Type
- Description
* - `query`
- `str`
- The string you want to search up
* - `ctx`
- `Optional[commands.Context]`
- Optional value which sets a `Context` object on the tracks you search.
* - `search_type`
- `SearchType`
- Enum which sets the provider to search from. Default value is `SearchType.ytsearch`
* - `filters`
- `Optional[List[Filter]]`
- Optional value which sets the filters that should apply when the track is played on the tracks you search.
:::
After you set those parameters, your function should look something like this:
```py
await Player.get_tracks(
query="<your query here>",
ctx=<optional ctx object here>,
search_type=<optional search type here>,
filters=[<optional filters here>]
)
```
:::{important}
All querying of Spotify and Apple Music tracks or playlists is handled in this function if you enabled that functionality when creating your node.
If you want to enable it, refer to [](pool.md#adding-a-node)
:::
You should get a list of `Track` in return after running this function for you to then do whatever you want with it.
Ideally, you should be putting all tracks into some sort of a queue. If you would like to learn about how to use
our queue implementation, you can refer to [](queue.md)
## Getting recommendations
To get recommendations using Lavalink, we need to use `Player.get_recommendations()`
You can also use `Node.get_recommendations()` to do the same thing without having a player.
```py
await Player.get_recommendations(...)
```
After you have initialized your function, we need to fill in the proper parameters:
:::{list-table}
:header-rows: 1
* - Name
- Type
- Description
* - `track`
- `Track`
- The track to fetch recommendations for
* - `ctx`
- `Optional[commands.Context]`
- Optional value which sets a `Context` object on the recommendations you fetch.
:::
After you set those parameters, your function should look something like this:
```py
await Player.get_recommendations(
track=<your track object here>,
ctx=<optional ctx object here>,
)
```
You should get a list of `Track` in return after running this function for you to then do whatever you want with it.
Ideally, you should be putting all tracks into some sort of a queue. If you would like to learn about how to use
our queue implementation, you can refer to [](queue.md)
## Connecting a player
To connect a player to a channel you need to pass the `Player` class into your `channel.connect()` function:
```py
await voice_channel.connect(cls=Player)
```
This will instance the player and make it available to your guild. If you want to access your player after instancing it,
you must use either `Guild.voice_client` or `Context.voice_client`.
## Controlling the player
There are a few functions to control the player:
- `Player.destroy()`
- `Player.play()`
- `Player.seek()`
- `Player.set_pause()`
- `Player.set_volume()`
- `Player.stop()`
### Destroying a player
To destroy a player, we need to use `Player.destroy()`
```py
await Player.destroy()
```
### Playing a track
To play a track, we need to use `Player.play()`
```py
await Player.play(...)
```
After you have initialized your function, we need to fill in the proper parameters:
:::{list-table}
:header-rows: 1
* - Name
- Type
- Description
* - `track`
- `Track`
- The track to play
* - `start`
- `int`
- The time (in milliseconds) to start the track at. Default value is `0`
* - `end`
- `int`
- The time (in milliseconds) to end the track at. Default value is `0`
* - `ignore_if_playing`
- `bool`
- If set, ignores the current track playing and replaces it with this track. Default value is `False`
:::
After you set those parameters, your function should look something like this:
```py
await Player.play(
track=<your track object here>,
start=<your optional start time here>,
end=<your optional end time here>,
ignore_if_playing=<your optional boolean here>
)
```
After running this function, it should return the `Track` you specified when running the function. This means the track is now playing.
### Seeking to a position
To seek to a position, we need to use `Player.seek()`
```py
await Player.seek(...)
```
After you have initialized your function, we need to include the `position` parameter, which is an amount in milliseconds:
```py
await Player.seek(position=<your pos here>)
```
After running this function, your currently playing track should seek to your specified position
### Pausing/unpausing the player
To pause/unpause the player, we need to use `Player.set_pause()`
```py
await Player.set_pause(...)
```
After you have initialized your function, we need to include the `pause` parameter, which is a boolean:
```py
await Player.set_pause(pause=<True/False>)
```
After running this function, your currently playing track should either pause or unpause depending on what you set.
### Setting the player volume
To set the volume the player, we need to use `Player.set_volume()`
```py
await Player.set_volume(...)
```
:::{important}
Lavalink accept ranges from 0 to 500 for this parameter. Inputting a value either higher or lower
than this amount will **not work.**
:::
After you have initialized your function, we need to include the `amount` parameter, which is an integer:
```py
await Player.set_volume(amount=<int>)
```
After running this function, your currently playing track should adjust in volume depending on the amount you set.
### Stopping the player
To stop the player, we need to use `Player.stop()`
```py
await Player.stop()
```
### Moving the player to another channel
To move the player to another channel, we need to use `Player.move_to()`
```py
await Player.move_to(...)
```
After you have initialized your function, we need to include the `channel` parameter, which is a `VoiceChannel`:
```py
await Player.move_to(channel)
```
After running this function, your player should be in the new voice channel. All voice state updates should also be handled.
## Controlling filters
Pomice has an extensive suite of filter management tools to help you make the most of Lavalink and it's filters.
Here are some of the functions you will be using to control filters:
- `Player.add_filter()`
- `Player.remove_filter()`
- `Player.reset_filters()`
### Adding a filter
To add a filter, we need to use `Player.add_filter()`
```py
await Player.add_filter(...)
```
After you have initialized your function, we need to fill in the proper parameters:
:::{list-table}
:header-rows: 1
* - Name
- Type
- Description
* - `filter`
- `Filter`
- The filter to apply
* - `fast_apply`
- `bool`
- If set to `True`, the specified filter will apply (almost) instantly if a song is playing. Default value is `False`.
:::
After you set those parameters, your function should look something like this:
```py
await Player.add_filter(
filter=<your filter object here>,
fast_apply=<True/False>
)
```
After running this function, you should see your currently playing track sound different depending on the filter you chose.
### Removing a filter
To remove a filter, we need to use `Player.remove_filter()`
```py
await Player.remove_filter(...)
```
After you have initialized your function, we need to fill in the proper parameters:
:::{list-table}
:header-rows: 1
* - Name
- Type
- Description
* - `filter`
- `Filter`
- The filter to remove
* - `fast_apply`
- `bool`
- If set to `True`, the specified filter will be removed (almost) instantly if a song is playing. Default value is `False`.
:::
After you set those parameters, your function should look something like this:
```py
await Player.remove_filter(
filter=<your filter object here>,
fast_apply=<True/False>
)
```
After running this function, you should see your currently playing track sound different depending on the filter you chose to remove.
### Resetting all filters
To reset all filters, we need to use `Player.reset_filters()`
```py
await Player.reset_filters()
```
After you have initialized your function, you can optionally include the `fast_apply` parameter, which is a boolean. If this is set to `True`, it'll remove all filters (almost) instantly if theres a track playing.
```py
await Player.reset_filters(fast_apply=<True/False>)
```

View File

@ -1,156 +0,0 @@
# Use the NodePool class
The `NodePool` class is the first class you will use when using Pomice.
The `NodePool` Class has three main functions you can use:
- `NodePool.create_node()`
- `NodePool.get_node()`
- `NodePool.get_best_node()`
## Adding a node
To add a node to our `NodePool`, we need to run `NodePool.create_node()`.
```py
await NodePool.create_node(...)
```
After you have initialized your function, we need to fill in the proper parameters:
:::{list-table}
:header-rows: 1
* - Name
- Type
- Description
* - `bot`
- `Client`
- A discord.py `Client` object (can be either a `Client` or a `commands.Bot`)
* - `host`
- `str`
- The IP/URL of your Lavalink node. Remember not to include the port in this field
* - `port`
- `int`
- The port your Lavalink node uses. By default, Lavalink uses `2333`.
* - `identifier`
- `str`
- The identifier your `Node` object uses to distinguish itself.
* - `password`
- `str`
- The password used to connect to your node.
* - `spotify_client_id`
- `Optional[str]`
- Your Spotify client ID goes here. You need this along with the client secret if you want to use Spotify functionality within Pomice.
* - `spotify_client_secret`
- `Optional[str]`
- Your Spotify client secret goes here. You need this along with the client ID if you want to use Spotify functionality within Pomice.
* - `apple_music`
- `bool`
- Set this value to `True` if you want to use Apple Music functionality within Pomice. Apple Music will **not work** if you don't enable this.
* - `fallback`
- `bool`
- Set this value to `True` if you want Pomice to automatically switch all players to another available node if one disconnects.
You must have two or more nodes to be able to do this.
* - `logger`
- `Optional[logging.Logger]`
- If you would like to receive logging information from Pomice, set this to your logger class
:::
All the other parameters not listed here have default values that are either set within the function or set later in the initialization of the node. If you would like to set these parameters to a different value, you are free to do so.
After you set those parameters, your function should look something like this:
```py
await NodePool.create_node(
bot=bot,
host="<your ip here>",
port=<your port here>,
identifier="<your id here>",
password="<your password here>",
spotify_client_id="<your spotify client id here>",
spotify_client_secret="<your spotify client secret here>"
apple_music=<True/False>,
fallback=<True/False>,
logger=<your logger here>
)
```
:::{important}
For features like Spotify and Apple Music, you are **not required** to fill in anything for them if you do not want to use them. If you do end up queuing a Spotify or Apple Music track, it is **up to you** on how you decide to handle it, whether it be through your own methods or a Lavalink plugin.
:::
Now that you have your Node object created, move on to [Using a node](node.md) to see what you can do with your `Node` object.
## Getting a node
To get a node from the node pool, we need to use `NodePool.get_node()`
```py
await NodePool.get_node(...)
```
After you have initialized your function, you can specify a identifier if you want to grab a specified node:
```py
await NodePool.get_node(identifier="<your id here>")
```
If you do not set a identifier, it'll return a random node from the pool.
## Getting the best node
To get a node from the node pool based on certain requirements, we need to use `NodePool.get_best_node()`
```py
await NodePool.get_best_node(...)
```
After you have initialized your function, you need to specify a `NodeAlgorithm` to use to grab your node from the pool.
The available algorithms are `by_ping` and `by_players`.
If you want to view what they do, refer to the `NodeAlgorithm` enum in the [](../api/enums.md) section.
```py
await NodePool.get_best_node(algorithm=NodeAlgorithm.xyz)
```
## Disconnecting all nodes from the pool
To disconnect all nodes from the pool, we need to use `NodePool.disconnect()`
```py
await NodePool.disconnect()
```
After running this function, all nodes in the pool should disconnect and no longer be available to use.

View File

@ -1,224 +0,0 @@
# Use the Queue class
Pomice has an optional queue system that works seamlessly with the library. This queue system introduce quality-of-life features that every music application should ideally have like queue shuffling, queue jumping, and looping.
To use the queue system with Pomice, you must first subclass the `Player` class within your application like so:
```py
from pomice import Player
class CustomPlayer(Player):
...
```
After you have initialized your subclass, you can add a `queue` variable to your class so you can access your queue when you initialize your player:
```py
from pomice import Player, Queue
class CustomPlayer(Player):
...
self.queue = Queue()
```
## Adding a song to the queue
To add a song to the queue, we must use `Queue.put()`
```py
Queue.put()
```
After you have initialized your function, we need to include the `item` parameter, which is a `Track`:
```py
Queue.put(item=<your Track here>)
```
After running the function, your track should be in the queue.
## Getting a track from the queue
To get a track from the queue, we need to do a few things.
To get a track using its position within the queue, you first need to get the position as a number, also known as its index. If you dont have the index and instead want to search for its index using keywords, you have to implement a fuzzy searching algorithm to find said track using a search query as an input and have it compare that query against the titles of the tracks in the queue. After that, you can get the `Track` object by [getting it with its index](queue.md#getting-track-with-its-index)
### Getting index of track
If you have the `Track` object and want to get its index within the queue, we can use `Queue.find_position()`
```py
Queue.find_position()
```
After you have initialized your function, we need to include the `item` parameter, which is a `Track`:
```py
Queue.find_position(item=<your Track here>)
```
After running the function, it should return the position of the track as an integer.
### Getting track with its index
If you have the index of the track and want to get the `Track` object, you first need to get the raw queue list:
```py
queue = Queue.get_queue()
```
After you have your queue, you can use basic list splicing to get the track object:
```py
track = queue[<index>]
```
## Getting the next track in the queue
To get the next track in the queue, we need to use `Queue.get()`
```py
Queue.get()
```
After running this function, it'll return the first track from the queue and remove it.
:::{note}
If you have a queue loop mode set, this behavior will be overridden since the queue is not allowed to remove tracks from the queue if its looping.
:::
## Removing a track from the queue
To remove a track from the queue, we must use `Queue.remove()`
```py
Queue.remove()
```
After you have initialized your function, we need to include the `item` parameter, which is a `Track`:
```py
Queue.remove(item=<your Track here>)
```
:::{important}
Your `Track` object must be in the queue if you want to remove it. Make sure you follow [](queue.md#getting-a-track-from-the-queue) before running this function.
:::
After running this function, your track should be removed from the queue.
## Shuffling the queue
To shuffle the queue, we must use `Queue.shuffle()`
```py
Queue.shuffle()
```
After running this function, your queue should be in a different order than it was originally.
:::{tip}
This function works best if theres atleast **3** tracks in the queue. The more tracks, the more variation the shuffle has.
:::
## Looping the queue
To loop the queue, we must use `Queue.set_loop_mode()`
```py
Queue.set_loop_mode(...)
```
After you have initialized your function, we need to include the `mode` parameter, which is a `LoopMode` enum:
```py
Queue.set_loop_mode(mode=LoopMode.<mode>)
```
The two types of `LoopMode` enums are `LoopMode.QUEUE` and `LoopMode.TRACK`. `QUEUE` loops the entire queue and `TRACK` loops the current track.
After running the function, your queue will now loop using the mode you specify.
### Resetting the loop mode
To reset the loop mode, we must use `Queue.disable_loop()`
```py
Queue.disable_loop()
```
:::{important}
You must have a loop mode set before using this function. It will **not work** if you do not a loop mode set
:::
After running the function, your queue should return to its normal functionality.
## Jumping to a track in the queue
To jump to a track in the queue, we must use `Queue.jump()`
```py
Queue.jump(...)
```
After you have initialized your function, we need to include the `item` parameter, which is a `Track`:
```py
Queue.jump(item=<your Track here>)
```
:::{important}
Your `Track` object must be in the queue if you want to jump to it. Make sure you follow [](queue.md#getting-a-track-from-the-queue) before running this function.
:::
After running this function, any items before the specified item will be removed, effectively "jumping" to the specified item in the queue. The next item obtained using `Queue.get()` will be your specified track.

View File

@ -1,40 +0,0 @@
---
hide-toc: true
---
# Pomice
![](https://raw.githubusercontent.com/cloudwithax/pomice/main/banner.jpg)
Pomice is a fully asynchronous Python library designed for communicating with [Lavalink](https://github.com/freyacodes/Lavalink) seamlessly within the [discord.py](https://github.com/Rapptz/discord.py) library. It features 100% API coverage of the entire [Lavalink](https://github.com/freyacodes/Lavalink) spec that can be accessed with easy-to-understand functions. We also include Spotify and Apple Music querying capabilites using built-in custom clients, making it easier to develop your next big music bot.
## Quick Links:
- [Installation](installation.md)
- [Quickstart](quickstart.md)
- [Frequently Asked Questions](faq.md)
- [How Do I?](hdi/index.md)
- [API Reference](api/index.md)
```{toctree}
:caption: Before You Start
:hidden:
installation
quickstart
faq
```
```{toctree}
:caption: How Do I?
:hidden:
hdi/index.md
```
```{toctree}
:caption: API Reference
:hidden:
api/index.md
```

View File

@ -1,30 +0,0 @@
# Installation
This library is designed to work with the Lavalink audio delivery system,
which directly interfaces with Discord to provide buttery smooth audio without
wasting your precious system resources.
Pomice is made with convenience to the user, in that everything is easy to use
and is out of your way, while also being customizable.
In order to start using this library, please download a Lavalink node to start,
you can get it [here](https://github.com/freyacodes/Lavalink/releases/latest)
After you have your Lavalink node set up, you can install Pomice:
```
pip install pomice
```
Pomice will handle installing all required dependencies for you so you can
start coding with it without a hitch.
After you installed Pomice, get familiar with how it works by starting out with [an example.](quickstart.md)
If you need more than just a quick example, get our drop-in [advanced cog](https://github.com/cloudwithax/pomice/blob/main/examples/advanced.py)
to take advantage of all of Pomice's features.
You are free to use this as a base to add on to for any music features you want to implement within your application.
If you want to jump into the library and learn how to do everything you need, refer to the [How Do I?](hdi/index.md) section.
If you want a deeper look into how the library works beyond the [How Do I?](hdi/index.md) guide, refer to the [API Reference](api/index.md) section.

View File

@ -1,35 +0,0 @@
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=.
set BUILDDIR=_build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.https://www.sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd

View File

@ -1,83 +0,0 @@
# Quick Jumpstart
If you want a quick example as to how to start with Pomice, look below:
```py
import pomice
import discord
import re
from discord.ext import commands
URL_REG = re.compile(r"https?://(?:www\.)?.+")
class MyBot(commands.Bot):
def __init__(self) -> None:
super().__init__(
command_prefix="!",
activity=discord.Activity(
type=discord.ActivityType.listening, name="to music!"
),
)
self.add_cog(Music(self))
async def on_ready(self) -> None:
print("I'm online!")
await self.cogs["Music"].start_nodes()
class Music(commands.Cog):
def __init__(self, bot) -> None:
self.bot = bot
self.pomice = pomice.NodePool()
async def start_nodes(self):
await self.pomice.create_node(
bot=self.bot,
host="127.0.0.1",
port="3030",
password="youshallnotpass",
identifier="MAIN",
)
print(f"Node is ready!")
@commands.command(name="join", aliases=["connect"])
async def join(
self, ctx: commands.Context, *, channel: discord.TextChannel = None
) -> None:
if not channel:
channel = getattr(ctx.author.voice, "channel", None)
if not channel:
raise commands.CheckFailure(
"You must be in a voice channel to use this command"
"without specifying the channel argument."
)
await ctx.author.voice.channel.connect(cls=pomice.Player)
await ctx.send(f"Joined the voice channel `{channel}`")
@commands.command(name="play")
async def play(self, ctx, *, search: str) -> None:
if not ctx.voice_client:
await ctx.invoke(self.join)
player = ctx.voice_client
results = await player.get_tracks(query=f"{search}")
if not results:
raise commands.CommandError("No results were found for that search term.")
if isinstance(results, pomice.Playlist):
await player.play(track=results.tracks[0])
else:
await player.play(track=results[0])
bot = MyBot()
bot.run("token here")
```

View File

@ -1,6 +0,0 @@
aiohttp
discord.py[voice]
furo
myst_parser
orjson
websockets

View File

@ -1,391 +0,0 @@
# type: ignore
"""
This example aims to show the full capabilities of the library.
This is in the form of a drop-in cog you can use and modify to your liking.
This example aims to include everything you would need to make a fully functioning music bot,
from a queue system, advanced queue control and more.
"""
import math
from contextlib import suppress
import discord
from discord.ext import commands
import pomice
class Player(pomice.Player):
"""Custom pomice Player class."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.queue = pomice.Queue()
self.controller: discord.Message = None
# Set context here so we can send a now playing embed
self.context: commands.Context = None
self.dj: discord.Member = None
self.pause_votes = set()
self.resume_votes = set()
self.skip_votes = set()
self.shuffle_votes = set()
self.stop_votes = set()
async def do_next(self) -> None:
# Clear the votes for a new song
self.pause_votes.clear()
self.resume_votes.clear()
self.skip_votes.clear()
self.shuffle_votes.clear()
self.stop_votes.clear()
# Check if theres a controller still active and deletes it
if self.controller:
with suppress(discord.HTTPException):
await self.controller.delete()
# Queue up the next track, else teardown the player
try:
track: pomice.Track = self.queue.get()
except pomice.QueueEmpty:
return await self.teardown()
await self.play(track)
# Call the controller (a.k.a: The "Now Playing" embed) and check if one exists
if track.is_stream:
embed = discord.Embed(
title="Now playing",
description=f":red_circle: **LIVE** [{track.title}]({track.uri}) [{track.requester.mention}]",
)
self.controller = await self.context.send(embed=embed)
else:
embed = discord.Embed(
title=f"Now playing",
description=f"[{track.title}]({track.uri}) [{track.requester.mention}]",
)
self.controller = await self.context.send(embed=embed)
async def teardown(self):
"""Clear internal states, remove player controller and disconnect."""
with suppress((discord.HTTPException), (KeyError)):
await self.destroy()
if self.controller:
await self.controller.delete()
async def set_context(self, ctx: commands.Context):
"""Set context for the player"""
self.context = ctx
self.dj = ctx.author
class Music(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
# In order to initialize a node, or really do anything in this library,
# you need to make a node pool
self.pomice = pomice.NodePool()
# Start the node
bot.loop.create_task(self.start_nodes())
async def start_nodes(self):
# Waiting for the bot to get ready before connecting to nodes.
await self.bot.wait_until_ready()
# You can pass in Spotify credentials to enable Spotify querying.
# If you do not pass in valid Spotify credentials, Spotify querying will not work
await self.pomice.create_node(
bot=self.bot,
host="127.0.0.1",
port=3030,
password="youshallnotpass",
identifier="MAIN",
)
print(f"Node is ready!")
def required(self, ctx: commands.Context):
"""Method which returns required votes based on amount of members in a channel."""
player: Player = ctx.voice_client
channel = self.bot.get_channel(int(player.channel.id))
required = math.ceil((len(channel.members) - 1) / 2.5)
if ctx.command.name == "stop":
if len(channel.members) == 3:
required = 2
return required
def is_privileged(self, ctx: commands.Context):
"""Check whether the user is an Admin or DJ."""
player: Player = ctx.voice_client
return player.dj == ctx.author or ctx.author.guild_permissions.kick_members
# The following are events from pomice.events
# We are using these so that if the track either stops or errors,
# we can just skip to the next track
# Of course, you can modify this to do whatever you like
@commands.Cog.listener()
async def on_pomice_track_end(self, player: Player, track, _):
await player.do_next()
@commands.Cog.listener()
async def on_pomice_track_stuck(self, player: Player, track, _):
await player.do_next()
@commands.Cog.listener()
async def on_pomice_track_exception(self, player: Player, track, _):
await player.do_next()
@commands.command(aliases=["joi", "j", "summon", "su", "con", "connect"])
async def join(self, ctx: commands.Context, *, channel: discord.VoiceChannel = None) -> None:
if not channel:
channel = getattr(ctx.author.voice, "channel", None)
if not channel:
return await ctx.send(
"You must be in a voice channel in order to use this command!",
)
# With the release of discord.py 1.7, you can now add a compatible
# VoiceProtocol class as an argument in VoiceChannel.connect().
# This library takes advantage of that and is how you initialize a player.
await ctx.author.voice.channel.connect(cls=Player)
player: Player = ctx.voice_client
# Set the player context so we can use it so send messages
await player.set_context(ctx=ctx)
await ctx.send(f"Joined the voice channel `{channel.name}`")
@commands.command(aliases=["disconnect", "dc", "disc", "lv", "fuckoff"])
async def leave(self, ctx: commands.Context):
if not (player := ctx.voice_client):
return await ctx.send(
"You must have the bot in a channel in order to use this command",
delete_after=7,
)
await player.destroy()
await ctx.send("Player has left the channel.")
@commands.command(aliases=["pla", "p"])
async def play(self, ctx: commands.Context, *, search: str) -> None:
# Checks if the player is in the channel before we play anything
if not (player := ctx.voice_client):
await ctx.author.voice.channel.connect(cls=Player)
player: Player = ctx.voice_client
await player.set_context(ctx=ctx)
# If you search a keyword, Pomice will automagically search the result using YouTube
# You can pass in "search_type=" as an argument to change the search type
# i.e: player.get_tracks("query", search_type=SearchType.ytmsearch)
# will search up any keyword results on YouTube Music
# We will also set the context here to get special features, like a track.requester object
results = await player.get_tracks(search, ctx=ctx)
if not results:
return await ctx.send("No results were found for that search term", delete_after=7)
if isinstance(results, pomice.Playlist):
for track in results.tracks:
player.queue.put(track)
else:
track = results[0]
player.queue.put(track)
if not player.is_playing:
await player.do_next()
@commands.command(aliases=["pau", "pa"])
async def pause(self, ctx: commands.Context):
"""Pause the currently playing song."""
if not (player := ctx.voice_client):
return await ctx.send(
"You must have the bot in a channel in order to use this command",
delete_after=7,
)
if player.is_paused or not player.is_connected:
return
if self.is_privileged(ctx):
await ctx.send("An admin or DJ has paused the player.", delete_after=10)
player.pause_votes.clear()
return await player.set_pause(True)
required = self.required(ctx)
player.pause_votes.add(ctx.author)
if len(player.pause_votes) >= required:
await ctx.send("Vote to pause passed. Pausing player.", delete_after=10)
player.pause_votes.clear()
await player.set_pause(True)
else:
await ctx.send(
f"{ctx.author.mention} has voted to pause the player. Votes: {len(player.pause_votes)}/{required}",
delete_after=15,
)
@commands.command(aliases=["res", "r"])
async def resume(self, ctx: commands.Context):
"""Resume a currently paused player."""
if not (player := ctx.voice_client):
return await ctx.send(
"You must have the bot in a channel in order to use this command",
delete_after=7,
)
if not player.is_paused or not player.is_connected:
return
if self.is_privileged(ctx):
await ctx.send("An admin or DJ has resumed the player.", delete_after=10)
player.resume_votes.clear()
return await player.set_pause(False)
required = self.required(ctx)
player.resume_votes.add(ctx.author)
if len(player.resume_votes) >= required:
await ctx.send("Vote to resume passed. Resuming player.", delete_after=10)
player.resume_votes.clear()
await player.set_pause(False)
else:
await ctx.send(
f"{ctx.author.mention} has voted to resume the player. Votes: {len(player.resume_votes)}/{required}",
delete_after=15,
)
@commands.command(aliases=["n", "nex", "next", "sk"])
async def skip(self, ctx: commands.Context):
"""Skip the currently playing song."""
if not (player := ctx.voice_client):
return await ctx.send(
"You must have the bot in a channel in order to use this command",
delete_after=7,
)
if not player.is_connected:
return
if self.is_privileged(ctx):
await ctx.send("An admin or DJ has skipped the song.", delete_after=10)
player.skip_votes.clear()
return await player.stop()
if ctx.author == player.current.requester:
await ctx.send("The song requester has skipped the song.", delete_after=10)
player.skip_votes.clear()
return await player.stop()
required = self.required(ctx)
player.skip_votes.add(ctx.author)
if len(player.skip_votes) >= required:
await ctx.send("Vote to skip passed. Skipping song.", delete_after=10)
player.skip_votes.clear()
await player.stop()
else:
await ctx.send(
f"{ctx.author.mention} has voted to skip the song. Votes: {len(player.skip_votes)}/{required} ",
delete_after=15,
)
@commands.command()
async def stop(self, ctx: commands.Context):
"""Stop the player and clear all internal states."""
if not (player := ctx.voice_client):
return await ctx.send(
"You must have the bot in a channel in order to use this command",
delete_after=7,
)
if not player.is_connected:
return
if self.is_privileged(ctx):
await ctx.send("An admin or DJ has stopped the player.", delete_after=10)
return await player.teardown()
required = self.required(ctx)
player.stop_votes.add(ctx.author)
if len(player.stop_votes) >= required:
await ctx.send("Vote to stop passed. Stopping the player.", delete_after=10)
await player.teardown()
else:
await ctx.send(
f"{ctx.author.mention} has voted to stop the player. Votes: {len(player.stop_votes)}/{required}",
delete_after=15,
)
@commands.command(aliases=["mix", "shuf"])
async def shuffle(self, ctx: commands.Context):
"""Shuffle the players queue."""
if not (player := ctx.voice_client):
return await ctx.send(
"You must have the bot in a channel in order to use this command",
delete_after=7,
)
if not player.is_connected:
return
if player.queue.qsize() < 3:
return await ctx.send(
"The queue is empty. Add some songs to shuffle the queue.",
delete_after=15,
)
if self.is_privileged(ctx):
await ctx.send("An admin or DJ has shuffled the queue.", delete_after=10)
player.shuffle_votes.clear()
return player.queue.shuffle()
required = self.required(ctx)
player.shuffle_votes.add(ctx.author)
if len(player.shuffle_votes) >= required:
await ctx.send("Vote to shuffle passed. Shuffling the queue.", delete_after=10)
player.shuffle_votes.clear()
player.queue.shuffle()
else:
await ctx.send(
f"{ctx.author.mention} has voted to shuffle the queue. Votes: {len(player.shuffle_votes)}/{required}",
delete_after=15,
)
@commands.command(aliases=["v", "vol"])
async def volume(self, ctx: commands.Context, *, vol: int):
"""Change the players volume, between 1 and 100."""
if not (player := ctx.voice_client):
return await ctx.send(
"You must have the bot in a channel in order to use this command",
delete_after=7,
)
if not player.is_connected:
return
if not self.is_privileged(ctx):
return await ctx.send("Only the DJ or admins may change the volume.")
if not 0 < vol < 101:
return await ctx.send("Please enter a value between 1 and 100.")
await player.set_volume(vol)
await ctx.send(f"Set the volume to **{vol}**%", delete_after=7)
async def setup(bot: commands.Bot):
await bot.add_cog(Music(bot))

View File

@ -1,91 +1,84 @@
# type: ignore import pomice
import discord import discord
from discord.ext import commands from discord.ext import commands
import pomice
class MyBot(commands.Bot): class MyBot(commands.Bot):
def __init__(self) -> None: def __init__(self) -> None:
super().__init__( super().__init__(command_prefix='!', activity=discord.Activity(type=discord.ActivityType.listening, name='to music!'))
command_prefix="!",
activity=discord.Activity(
type=discord.ActivityType.listening,
name="to music!",
),
)
self.add_cog(Music(self)) self.add_cog(Music(self))
self.loop.create_task(self.cogs["Music"].start_nodes())
async def on_ready(self) -> None: async def on_ready(self) -> None:
print("I'm online!") print("I'm online!")
await self.cogs["Music"].start_nodes()
class Music(commands.Cog): class Music(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
def __init__(self, bot) -> None:
self.bot = bot self.bot = bot
# In order to initialize a node, or really do anything in this library, # In order to initialize a node, or really do anything in this library, you need to make a node pool
# you need to make a node pool
self.pomice = pomice.NodePool() self.pomice = pomice.NodePool()
async def start_nodes(self): async def start_nodes(self):
# You can pass in Spotify credentials to enable Spotify querying. # You can pass in Spotify credentials to enable Spotify querying.
# If you do not pass in valid Spotify credentials, Spotify querying will not work # If you do not pass in valid Spotify credentials, Spotify querying will not work
await self.pomice.create_node(
bot=self.bot, await self.pomice.create_node(bot=self.bot, host='127.0.0.1', port='3030', password='youshallnotpass', identifier='MAIN')
host="127.0.0.1",
port=3030,
password="youshallnotpass",
identifier="MAIN",
)
print(f"Node is ready!") print(f"Node is ready!")
@commands.command(aliases=["connect"])
async def join(self, ctx: commands.Context, *, channel: discord.VoiceChannel = None) -> None:
@commands.command(aliases=['connect'])
async def join(self, ctx: commands.Context, *, channel: discord.TextChannel = None) -> None:
if not channel: if not channel:
channel = getattr(ctx.author.voice, "channel", None) channel = getattr(ctx.author.voice, 'channel', None)
if not channel: if not channel:
raise commands.CheckFailure( raise commands.CheckFailure('You must be in a voice channel to use this command'
"You must be in a voice channel to use this command " 'without specifying the channel argument.')
"without specifying the channel argument.",
)
# With the release of discord.py 1.7, you can now add a compatible VoiceProtocol class as a argument
# in channel.connect(). This library takes advantage of that and is how you initialize a player.
# With the release of discord.py 1.7, you can now add a compatible
# VoiceProtocol class as an argument in VoiceChannel.connect().
# This library takes advantage of that and is how you initialize a player.
await ctx.author.voice.channel.connect(cls=pomice.Player) await ctx.author.voice.channel.connect(cls=pomice.Player)
await ctx.send(f"Joined the voice channel `{channel}`") await ctx.send(f'Joined the voice channel `{channel}`')
@commands.command(aliases=["dc", "disconnect"]) @commands.command(aliases=['dc', 'disconnect'])
async def leave(self, ctx: commands.Context): async def leave(self, ctx: commands.Context):
if not ctx.voice_client: if not ctx.voice_client:
raise commands.CommandError("No player detected") raise commands.CommandError('No player detected')
player: pomice.Player = ctx.voice_client player: pomice.Player = ctx.voice_client
await player.destroy() player.destroy()
await ctx.send("Player has left the channel.") await ctx.send("Player has left the channel.")
@commands.command(aliases=["p"]) @commands.command(aliases=['p'])
async def play(self, ctx: commands.Context, *, search: str) -> None: async def play(self, ctx, *, search: str) -> None:
# Checks if the player is in the channel before we play anything
# Checks if the players in the channel before we play anything
if not ctx.voice_client: if not ctx.voice_client:
await ctx.invoke(self.join) await ctx.invoke(self.join)
player: pomice.Player = ctx.voice_client player: pomice.Player = ctx.voice_client
# If you search a keyword, Pomice will automagically search the result using YouTube # If you search a keyword, Pomice will automagically search the result using Youtube
# You can pass in "search_type=" as an argument to change the search type # You can pass in "search_type=" as an argument to change the search type
# i.e: player.get_tracks("query", search_type=SearchType.ytmsearch) # i.e: player.get_tracks("query", search_type=SearchType.ytmsearch)
# will search up any keyword results on YouTube Music # will search up any keyword results on Youtube Music
results = await player.get_tracks(search)
results = player.get_tracks(f"{search}")
if not results: if not results:
raise commands.CommandError( raise commands.CommandError('No results were found for that search term.')
"No results were found for that search term.",
)
if isinstance(results, pomice.Playlist): if isinstance(results, pomice.Playlist):
await player.play(track=results.tracks[0]) await player.play(track=results.tracks[0])
@ -93,44 +86,50 @@ class Music(commands.Cog):
await player.play(track=results[0]) await player.play(track=results[0])
@commands.command() @commands.command()
async def pause(self, ctx: commands.Context): async def pause(self, ctx):
if not ctx.voice_client: if not ctx.voice_client:
raise commands.CommandError("No player detected") raise commands.CommandError('No player detected')
player: pomice.Player = ctx.voice_client player: pomice.Player = ctx.voice_client
if player.is_paused: if player.is_paused:
return await ctx.send("Player is already paused!") await ctx.send("Player is already paused!")
player.set_pause(pause=True)
await player.set_pause(pause=True)
await ctx.send("Player has been paused") await ctx.send("Player has been paused")
@commands.command() @commands.command()
async def resume(self, ctx: commands.Context): async def resume(self, ctx):
if not ctx.voice_client: if not ctx.voice_client:
raise commands.CommandError("No player detected") raise commands.CommandError('No player detected')
player: pomice.Player = ctx.voice_client player: pomice.Player = ctx.voice_client
if not player.is_paused: if not player.is_paused:
return await ctx.send("Player is already playing!") await ctx.send("Player is already playing!")
player.set_pause(pause=False)
await player.set_pause(pause=False)
await ctx.send("Player has been resumed") await ctx.send("Player has been resumed")
@commands.command() @commands.command()
async def stop(self, ctx: commands.Context): async def stop(self, ctx):
if not ctx.voice_client: if not ctx.voice_client:
raise commands.CommandError("No player detected") raise commands.CommandError('No player detected')
player: pomice.Player = ctx.voice_client player: pomice.Player = ctx.voice_client
if not player.is_playing: if not player.is_playing:
return await ctx.send("Player is already stopped!") await ctx.send("Player is already stopped!")
player.stop()
await player.stop()
await ctx.send("Player has been stopped") await ctx.send("Player has been stopped")
bot = MyBot() bot = MyBot()
bot.run("token") bot.run("token here")

View File

@ -1,37 +1,24 @@
""" """Pomice wrapper for Lavalink, made possible by cloudwithax 2021"""
Pomice
~~~~~~
The modern Lavalink wrapper designed for discord.py.
Copyright (c) 2024, cloudwithax
Licensed under GPL-3.0
"""
import discord import discord
if not discord.version_info.major >= 2: if discord.__version__ != "2.0.0a":
class DiscordPyOutdated(Exception): class DiscordPyOutdated(Exception):
pass pass
raise DiscordPyOutdated( raise DiscordPyOutdated(
"You must have discord.py (v2.0 or greater) to use this library. " "You must have discord.py 2.0 to use this library. "
"Uninstall your current version and install discord.py 2.0 " "Uninstall your current version and install discord.py 2.0 "
"using 'pip install discord.py'", "using 'pip install git+https://github.com/Rapptz/discord.py@master'"
) )
__version__ = "2.10.0" __version__ = "1.1.1"
__title__ = "pomice" __title__ = "pomice"
__author__ = "cloudwithax" __author__ = "cloudwithax"
__license__ = "GPL-3.0"
__copyright__ = "Copyright (c) 2023, cloudwithax"
from .enums import * from .enums import SearchType
from .events import * from .events import *
from .exceptions import * from .exceptions import *
from .filters import * from .filters import *
from .objects import * from .objects import *
from .queue import * from .player import Player
from .player import *
from .pool import * from .pool import *
from .routeplanner import *

View File

@ -1,4 +0,0 @@
"""Apple Music module for Pomice, made possible by cloudwithax 2023"""
from .client import *
from .exceptions import *
from .objects import *

View File

@ -1,298 +0,0 @@
from __future__ import annotations
import asyncio
import base64
import logging
import re
from datetime import datetime
from typing import AsyncGenerator
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
import aiohttp
import orjson as json
from .exceptions import *
from .objects import *
__all__ = ("Client",)
AM_URL_REGEX = re.compile(
r"https?://music\.apple\.com/(?P<country>[a-zA-Z]{2})/(?P<type>album|playlist|song|artist)/(?P<name>.+?)/(?P<id>[^/?]+?)(?:/)?(?:\?.*)?$",
)
AM_SINGLE_IN_ALBUM_REGEX = re.compile(
r"https?://music\.apple\.com/(?P<country>[a-zA-Z]{2})/(?P<type>album|playlist|song|artist)/(?P<name>.+)/(?P<id>[^/?]+)(\?i=)(?P<id2>[^&]+)(?:&.*)?$",
)
AM_SCRIPT_REGEX = re.compile(r'<script.*?src="(/assets/index-.*?)"')
AM_REQ_URL = "https://api.music.apple.com/v1/catalog/{country}/{type}s/{id}"
AM_BASE_URL = "https://api.music.apple.com"
class Client:
"""The base Apple Music client for Pomice.
This will do all the heavy lifting of getting tracks from Apple Music
and translating it to a valid Lavalink track. No client auth is required here.
"""
def __init__(self, *, playlist_concurrency: int = 6) -> None:
self.expiry: datetime = datetime(1970, 1, 1)
self.token: str = ""
self.headers: Dict[str, str] = {}
self.session: aiohttp.ClientSession = None # type: ignore
self._log = logging.getLogger(__name__)
# Concurrency knob for parallel playlist page retrieval
self._playlist_concurrency = max(1, playlist_concurrency)
async def _set_session(self, session: aiohttp.ClientSession) -> None:
self.session = session
async def request_token(self) -> None:
# First lets get the raw response from the main page
resp = await self.session.get("https://music.apple.com")
if resp.status != 200:
raise AppleMusicRequestException(
f"Error while fetching results: {resp.status} {resp.reason}",
)
# Looking for script tag that fits criteria
text = await resp.text()
match = re.search(AM_SCRIPT_REGEX, text)
if not match:
raise AppleMusicRequestException(
"Could not find valid script URL in response.",
)
# Found the script file, lets grab our token
result = match.group(1)
asset_url = result
resp = await self.session.get("https://music.apple.com" + asset_url)
if resp.status != 200:
raise AppleMusicRequestException(
f"Error while fetching results: {resp.status} {resp.reason}",
)
text = await resp.text()
match = re.search('"(eyJ.+?)"', text)
if not match:
raise AppleMusicRequestException(
"Could not find token in response.",
)
result = match.group(1)
self.token = result
self.headers = {
"Authorization": f"Bearer {result}",
"Origin": "https://apple.com",
}
token_split = self.token.split(".")[1]
token_json = base64.b64decode(
token_split + "=" * (-len(token_split) % 4),
).decode()
token_data = json.loads(token_json)
self.expiry = datetime.fromtimestamp(token_data["exp"])
if self._log:
self._log.debug(f"Fetched Apple Music bearer token successfully")
async def search(self, query: str) -> Union[Album, Playlist, Song, Artist]:
if not self.token or datetime.utcnow() > self.expiry:
await self.request_token()
result = AM_URL_REGEX.match(query)
if not result:
raise InvalidAppleMusicURL(
"The Apple Music link provided is not valid.",
)
country = result.group("country")
type = result.group("type")
id = result.group("id")
if type == "album" and (sia_result := AM_SINGLE_IN_ALBUM_REGEX.match(query)):
# apple music likes to generate links for singles off an album
# by adding a param at the end of the url
# so we're gonna scan for that and correct it
id = sia_result.group("id2")
type = "song"
request_url = AM_REQ_URL.format(country=country, type=type, id=id)
else:
request_url = AM_REQ_URL.format(country=country, type=type, id=id)
resp = await self.session.get(request_url, headers=self.headers)
if resp.status != 200:
raise AppleMusicRequestException(
f"Error while fetching results: {resp.status} {resp.reason}",
)
data: dict = await resp.json(loads=json.loads)
if self._log:
self._log.debug(
f"Made request to Apple Music API with status {resp.status} and response {data}",
)
data = data["data"][0]
if type == "song":
return Song(data)
elif type == "album":
return Album(data)
elif type == "artist":
resp = await self.session.get(
f"{request_url}/view/top-songs",
headers=self.headers,
)
if resp.status != 200:
raise AppleMusicRequestException(
f"Error while fetching results: {resp.status} {resp.reason}",
)
top_tracks: dict = await resp.json(loads=json.loads)
artist_tracks: dict = top_tracks["data"]
return Artist(data, tracks=artist_tracks)
else:
track_data: dict = data["relationships"]["tracks"]
album_tracks: List[Song] = [Song(track) for track in track_data["data"]]
if not len(album_tracks):
raise AppleMusicRequestException(
"This playlist is empty and therefore cannot be queued.",
)
# Apple Music uses cursor pagination with 'next'. We'll fetch subsequent pages
# concurrently by first collecting cursors in rolling waves.
next_cursor = track_data.get("next")
semaphore = asyncio.Semaphore(self._playlist_concurrency)
async def fetch_page(url: str) -> List[Song]:
async with semaphore:
resp = await self.session.get(url, headers=self.headers)
if resp.status != 200:
if self._log:
self._log.warning(
f"Apple Music page fetch failed {resp.status} {resp.reason} for {url}",
)
return []
pj: dict = await resp.json(loads=json.loads)
songs = [Song(track) for track in pj.get("data", [])]
# Return songs; we will look for pj.get('next') in streaming iterator variant
return songs, pj.get("next") # type: ignore
# We'll implement a wave-based approach similar to Spotify but need to follow cursors.
# Because we cannot know all cursors upfront, we'll iteratively fetch waves.
waves: List[List[Song]] = []
cursors: List[str] = []
if next_cursor:
cursors.append(next_cursor)
# Limit total waves to avoid infinite loops in malformed responses
max_waves = 50
wave_size = self._playlist_concurrency * 2
wave_counter = 0
while cursors and wave_counter < max_waves:
current = cursors[:wave_size]
cursors = cursors[wave_size:]
tasks = [
fetch_page(AM_BASE_URL + cursor) for cursor in current # type: ignore[arg-type]
]
results = await asyncio.gather(*tasks, return_exceptions=True)
for res in results:
if isinstance(res, tuple): # (songs, next)
songs, nxt = res
if songs:
waves.append(songs)
if nxt:
cursors.append(nxt)
wave_counter += 1
for w in waves:
album_tracks.extend(w)
return Playlist(data, album_tracks)
async def iter_playlist_tracks(
self,
*,
query: str,
batch_size: int = 100,
) -> AsyncGenerator[List[Song], None]:
"""Stream Apple Music playlist tracks in batches.
Parameters
----------
query: str
Apple Music playlist URL.
batch_size: int
Logical grouping size for yielded batches.
"""
if not self.token or datetime.utcnow() > self.expiry:
await self.request_token()
result = AM_URL_REGEX.match(query)
if not result or result.group("type") != "playlist":
raise InvalidAppleMusicURL("Provided query is not a valid Apple Music playlist URL.")
country = result.group("country")
playlist_id = result.group("id")
request_url = AM_REQ_URL.format(country=country, type="playlist", id=playlist_id)
resp = await self.session.get(request_url, headers=self.headers)
if resp.status != 200:
raise AppleMusicRequestException(
f"Error while fetching results: {resp.status} {resp.reason}",
)
data: dict = await resp.json(loads=json.loads)
playlist_data = data["data"][0]
track_data: dict = playlist_data["relationships"]["tracks"]
first_page_tracks = [Song(track) for track in track_data["data"]]
for i in range(0, len(first_page_tracks), batch_size):
yield first_page_tracks[i : i + batch_size]
next_cursor = track_data.get("next")
semaphore = asyncio.Semaphore(self._playlist_concurrency)
async def fetch(cursor: str) -> tuple[List[Song], Optional[str]]:
url = AM_BASE_URL + cursor
async with semaphore:
r = await self.session.get(url, headers=self.headers)
if r.status != 200:
if self._log:
self._log.warning(
f"Skipping Apple Music page due to {r.status} {r.reason}",
)
return [], None
pj: dict = await r.json(loads=json.loads)
songs = [Song(track) for track in pj.get("data", [])]
return songs, pj.get("next")
# Rolling waves of fetches following cursor chain
max_waves = 50
wave_size = self._playlist_concurrency * 2
waves = 0
cursors: List[str] = []
if next_cursor:
cursors.append(next_cursor)
while cursors and waves < max_waves:
current = cursors[:wave_size]
cursors = cursors[wave_size:]
results = await asyncio.gather(*[fetch(c) for c in current])
for songs, nxt in results:
if songs:
for j in range(0, len(songs), batch_size):
yield songs[j : j + batch_size]
if nxt:
cursors.append(nxt)
waves += 1

View File

@ -1,16 +0,0 @@
__all__ = (
"AppleMusicRequestException",
"InvalidAppleMusicURL",
)
class AppleMusicRequestException(Exception):
"""An error occurred when making a request to the Apple Music API"""
pass
class InvalidAppleMusicURL(Exception):
"""An invalid Apple Music URL was passed"""
pass

View File

@ -1,92 +0,0 @@
"""Module for managing Apple Music objects"""
from typing import List
__all__ = (
"Song",
"Playlist",
"Album",
"Artist",
)
class Song:
"""The base class for an Apple Music song"""
def __init__(self, data: dict) -> None:
self.name: str = data["attributes"]["name"]
self.url: str = data["attributes"]["url"]
self.isrc: str = data["attributes"]["isrc"]
self.length: float = data["attributes"]["durationInMillis"]
self.id: str = data["id"]
self.artists: str = data["attributes"]["artistName"]
self.image: str = data["attributes"]["artwork"]["url"].replace(
"{w}x{h}",
f'{data["attributes"]["artwork"]["width"]}x{data["attributes"]["artwork"]["height"]}',
)
def __repr__(self) -> str:
return (
f"<Pomice.applemusic.Song name={self.name} artists={self.artists} "
f"length={self.length} id={self.id} isrc={self.isrc}>"
)
class Playlist:
"""The base class for an Apple Music playlist"""
def __init__(self, data: dict, tracks: List[Song]) -> None:
self.name: str = data["attributes"]["name"]
self.owner: str = data["attributes"]["curatorName"]
self.id: str = data["id"]
self.tracks: List[Song] = tracks
self.total_tracks: int = len(tracks)
self.url: str = data["attributes"]["url"]
# we'll use the first song's image as the image for the playlist
# because apple dynamically generates playlist covers client-side
self.image = self.tracks[0].image
def __repr__(self) -> str:
return (
f"<Pomice.applemusic.Playlist name={self.name} owner={self.owner} id={self.id} "
f"total_tracks={self.total_tracks} tracks={self.tracks}>"
)
class Album:
"""The base class for an Apple Music album"""
def __init__(self, data: dict) -> None:
self.name: str = data["attributes"]["name"]
self.url: str = data["attributes"]["url"]
self.id: str = data["id"]
self.artists: str = data["attributes"]["artistName"]
self.total_tracks: int = data["attributes"]["trackCount"]
self.tracks: List[Song] = [Song(track) for track in data["relationships"]["tracks"]["data"]]
self.image: str = data["attributes"]["artwork"]["url"].replace(
"{w}x{h}",
f'{data["attributes"]["artwork"]["width"]}x{data["attributes"]["artwork"]["height"]}',
)
def __repr__(self) -> str:
return (
f"<Pomice.applemusic.Album name={self.name} artists={self.artists} id={self.id} "
f"total_tracks={self.total_tracks} tracks={self.tracks}>"
)
class Artist:
"""The base class for an Apple Music artist"""
def __init__(self, data: dict, tracks: dict) -> None:
self.name: str = f'Top tracks for {data["attributes"]["name"]}'
self.url: str = data["attributes"]["url"]
self.id: str = data["id"]
self.genres: str = ", ".join(genre for genre in data["attributes"]["genreNames"])
self.tracks: List[Song] = [Song(track) for track in tracks]
self.image: str = data["attributes"]["artwork"]["url"].replace(
"{w}x{h}",
f'{data["attributes"]["artwork"]["width"]}x{data["attributes"]["artwork"]["height"]}',
)
def __repr__(self) -> str:
return f"<Pomice.applemusic.Artist name={self.name} id={self.id} " f"tracks={self.tracks}>"

View File

@ -1,308 +1,23 @@
import re
from enum import Enum from enum import Enum
from enum import IntEnum
__all__ = (
"SearchType",
"TrackType",
"PlaylistType",
"NodeAlgorithm",
"LoopMode",
"RouteStrategy",
"RouteIPType",
"URLRegex",
"LogLevel",
)
class SearchType(Enum): class SearchType(Enum):
"""The enum for the different search types for Pomice.
This feature is exclusively for the Spotify search feature of Pomice.
If you are not using this feature, this class is not necessary.
SearchType.ytsearch searches using regular Youtube,
which is best for all scenarios.
SearchType.ytmsearch searches using YouTube Music,
which is best for getting audio-only results.
SearchType.scsearch searches using SoundCloud,
which is an alternative to YouTube or YouTube Music.
""" """
The enum for the different search types for Pomice.
This feature is exclusively for the Spotify search feature of Pomice.
If you are not using this feature, this class is not necessary.
SearchType.ytsearch searches using regular Youtube,
which is best for all scenarios.
SearchType.ytmsearch searches using YouTube Music,
which is best for getting audio-only results.
SearchType.scsearch searches using SoundCloud,
which is an alternative to YouTube or YouTube Music.
"""
ytsearch = "ytsearch" ytsearch = "ytsearch"
ytmsearch = "ytmsearch" ytmsearch = "ytmsearch"
scsearch = "scsearch" scsearch = "scsearch"
other = "other"
@classmethod
def _missing_(cls, value: object) -> "SearchType": # type: ignore[override]
return cls.other
def __str__(self) -> str: def __str__(self) -> str:
return self.value return self.value
class TrackType(Enum):
"""
The enum for the different track types for Pomice.
TrackType.YOUTUBE defines that the track is from YouTube
TrackType.SOUNDCLOUD defines that the track is from SoundCloud.
TrackType.SPOTIFY defines that the track is from Spotify
TrackType.APPLE_MUSIC defines that the track is from Apple Music.
TrackType.HTTP defines that the track is from an HTTP source.
TrackType.LOCAL defines that the track is from a local source.
TrackType.OTHER defines that the track is from an unknown source (possible from 3rd-party plugins).
"""
# We don't have to define anything special for these, since these just serve as flags
YOUTUBE = "youtube"
SOUNDCLOUD = "soundcloud"
SPOTIFY = "spotify"
APPLE_MUSIC = "apple_music"
HTTP = "http"
LOCAL = "local"
OTHER = "other"
@classmethod
def _missing_(cls, value: object) -> "TrackType": # type: ignore[override]
return cls.OTHER
def __str__(self) -> str:
return self.value
class PlaylistType(Enum):
"""
The enum for the different playlist types for Pomice.
PlaylistType.YOUTUBE defines that the playlist is from YouTube
PlaylistType.SOUNDCLOUD defines that the playlist is from SoundCloud.
PlaylistType.SPOTIFY defines that the playlist is from Spotify
PlaylistType.APPLE_MUSIC defines that the playlist is from Apple Music.
PlaylistType.OTHER defines that the playlist is from an unknown source (possible from 3rd-party plugins).
"""
# We don't have to define anything special for these, since these just serve as flags
YOUTUBE = "youtube"
SOUNDCLOUD = "soundcloud"
SPOTIFY = "spotify"
APPLE_MUSIC = "apple_music"
OTHER = "other"
@classmethod
def _missing_(cls, value: object) -> "PlaylistType": # type: ignore[override]
return cls.OTHER
def __str__(self) -> str:
return self.value
class NodeAlgorithm(Enum):
"""
The enum for the different node algorithms in Pomice.
The enums in this class are to only differentiate different
methods, since the actual method is handled in the
get_best_node() method.
NodeAlgorithm.by_ping returns a node based on it's latency,
preferring a node with the lowest response time
NodeAlgorithm.by_players return a nodes based on how many players it has.
This algorithm prefers nodes with the least amount of players.
"""
# We don't have to define anything special for these, since these just serve as flags
by_ping = "BY_PING"
by_players = "BY_PLAYERS"
def __str__(self) -> str:
return self.value
class LoopMode(Enum):
"""
The enum for the different loop modes.
This feature is exclusively for the queue utility of pomice.
If you are not using this feature, this class is not necessary.
LoopMode.TRACK sets the queue loop to the current track.
LoopMode.QUEUE sets the queue loop to the whole queue.
"""
# We don't have to define anything special for these, since these just serve as flags
TRACK = "track"
QUEUE = "queue"
def __str__(self) -> str:
return self.value
class RouteStrategy(Enum):
"""
The enum for specifying the route planner strategy for Lavalink.
This feature is exclusively for the RoutePlanner class.
If you are not using this feature, this class is not necessary.
RouteStrategy.ROTATE_ON_BAN specifies that the node is rotating IPs
whenever they get banned by Youtube.
RouteStrategy.LOAD_BALANCE specifies that the node is selecting
random IPs to balance out requests between them.
RouteStrategy.NANO_SWITCH specifies that the node is switching
between IPs every CPU clock cycle.
RouteStrategy.ROTATING_NANO_SWITCH specifies that the node is switching
between IPs every CPU clock cycle and is rotating between IP blocks on
ban.
"""
ROTATE_ON_BAN = "RotatingIpRoutePlanner"
LOAD_BALANCE = "BalancingIpRoutePlanner"
NANO_SWITCH = "NanoIpRoutePlanner"
ROTATING_NANO_SWITCH = "RotatingNanoIpRoutePlanner"
class RouteIPType(Enum):
"""
The enum for specifying the route planner IP block type for Lavalink.
This feature is exclusively for the RoutePlanner class.
If you are not using this feature, this class is not necessary.
RouteIPType.IPV4 specifies that the IP block type is IPV4
RouteIPType.IPV6 specifies that the IP block type is IPV6
"""
IPV4 = "Inet4Address"
IPV6 = "Inet6Address"
class URLRegex:
"""
The enum for all the URL Regexes in use by Pomice.
URLRegex.SPOTIFY_URL returns the Spotify URL Regex.
URLRegex.DISCORD_MP3_URL returns the Discord MP3 URL Regex.
URLRegex.YOUTUBE_URL returns the Youtube URL Regex.
URLRegex.YOUTUBE_PLAYLIST returns the Youtube Playlist Regex.
URLRegex.YOUTUBE_TIMESTAMP returns the Youtube Timestamp Regex.
URLRegex.AM_URL returns the Apple Music URL Regex.
URLRegex.SOUNDCLOUD_URL returns the SoundCloud URL Regex.
URLRegex.BASE_URL returns the standard URL Regex.
"""
# Spotify share links can include query parameters like ?si=XXXX, a trailing slash,
# or an intl locale segment (e.g. /intl-en/). Broaden the regex so we still capture
# the type and id while ignoring extra parameters. This prevents the URL from being
# treated as a generic Lavalink identifier and ensures internal Spotify handling runs.
SPOTIFY_URL = re.compile(
r"https?://open\.spotify\.com/(?:intl-[a-zA-Z-]+/)?(?P<type>album|playlist|track|artist)/(?P<id>[a-zA-Z0-9]+)(?:/)?(?:\?.*)?$",
)
DISCORD_MP3_URL = re.compile(
r"https?://cdn.discordapp.com/attachments/(?P<channel_id>[0-9]+)/"
r"(?P<message_id>[0-9]+)/(?P<file>[a-zA-Z0-9_.]+)+",
)
YOUTUBE_URL = re.compile(
r"^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))"
r"(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$",
)
YOUTUBE_PLAYLIST_URL = re.compile(
r"^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))/playlist\?list=.*",
)
YOUTUBE_TIMESTAMP = re.compile(
r"(?P<video>^.*?)(\?t|&start)=(?P<time>\d+)?.*",
)
# Apple Music links sometimes append additional query parameters (e.g. &l=en, &uo=4).
# Allow arbitrary query parameters so valid links are captured and parsed.
AM_URL = re.compile(
r"https?://music\.apple\.com/(?P<country>[a-zA-Z]{2})/"
r"(?P<type>album|playlist|song|artist)/(?P<name>.+?)/(?P<id>[^/?]+?)(?:/)?(?:\?.*)?$",
)
# Single-in-album links may also carry extra query params beyond the ?i=<trackid> token.
AM_SINGLE_IN_ALBUM_REGEX = re.compile(
r"https?://music\.apple\.com/(?P<country>[a-zA-Z]{2})/(?P<type>album|playlist|song|artist)/"
r"(?P<name>.+)/(?P<id>[^/?]+)(\?i=)(?P<id2>[^&]+)(?:&.*)?$",
)
SOUNDCLOUD_URL = re.compile(
r"((?:https?:)?\/\/)?((?:www|m)\.)?soundcloud.com\/.*/.*",
)
SOUNDCLOUD_PLAYLIST_URL = re.compile(
r"^(https?:\/\/)?(www.)?(m\.)?soundcloud\.com\/.*/sets/.*",
)
SOUNDCLOUD_TRACK_IN_SET_URL = re.compile(
r"^(https?:\/\/)?(www.)?(m\.)?soundcloud\.com/[a-zA-Z0-9-._]+/[a-zA-Z0-9-._]+(\?in)",
)
LAVALINK_SEARCH = re.compile(r"(?P<type>ytm?|sc)search:")
BASE_URL = re.compile(r"https?://(?:www\.)?.+")
class LogLevel(IntEnum):
"""
The enum for specifying the logging level within Pomice.
This class serves as shorthand for logging.<level>
This enum is exclusively for the logging feature in Pomice.
If you are not using this feature, this class is not necessary.
LogLevel.DEBUG sets the logging level to "debug".
LogLevel.INFO sets the logging level to "info".
LogLevel.WARN sets the logging level to "warn".
LogLevel.ERROR sets the logging level to "error".
LogLevel.CRITICAL sets the logging level to "CRITICAL".
"""
DEBUG = 10
INFO = 20
WARN = 30
ERROR = 40
CRITICAL = 50
@classmethod
def from_str(cls, level_str):
try:
return cls[level_str.upper()]
except KeyError:
raise ValueError(f"No such log level: {level_str}")

View File

@ -1,85 +1,49 @@
from __future__ import annotations
from abc import ABC
from typing import Any
from typing import Optional
from typing import Tuple
from typing import TYPE_CHECKING
from discord import Client
from discord import Guild
from discord.ext import commands
from .objects import Track
from .pool import NodePool from .pool import NodePool
from .utils import ClientType
if TYPE_CHECKING:
from .player import Player
__all__ = (
"PomiceEvent",
"TrackStartEvent",
"TrackEndEvent",
"TrackStuckEvent",
"TrackExceptionEvent",
"WebSocketClosedPayload",
"WebSocketClosedEvent",
"WebSocketOpenEvent",
)
class PomiceEvent(ABC): class PomiceEvent:
"""The base class for all events dispatched by a node. """The base class for all events dispatched by a node.
Every event must be formatted within your bot's code as a listener. Every event must be formatted within your bot's code as a listener.
i.e: If you want to listen for when a track starts, the event would be: i.e: If you want to listen for when a track starts, the event would be:
```py ```py
@bot.listen @bot.listen
async def on_pomice_track_start(self, event): async def on_pomice_track_start(self, event):
``` ```
""" """
name = "event" name = "event"
handler_args: Tuple handler_args = ()
def dispatch(self, bot: Client) -> None: def dispatch(self, bot: ClientType):
bot.dispatch(f"pomice_{self.name}", *self.handler_args) bot.dispatch(f"pomice_{self.name}", *self.handler_args)
class TrackStartEvent(PomiceEvent): class TrackStartEvent(PomiceEvent):
"""Fired when a track has successfully started. """Fired when a track has successfully started.
Returns the player associated with the event and the pomice.Track object. Returns the player associated with the event and the pomice.Track object.
""" """
name = "track_start" name = "track_start"
__slots__ = ( def __init__(self, data: dict):
"player", self.player = NodePool.get_node().get_player(int(data["guildId"]))
"track", self.track = self.player._current
)
def __init__(self, data: dict, player: Player):
self.player: Player = player
self.track: Optional[Track] = self.player._current
# on_pomice_track_start(player, track) # on_pomice_track_start(player, track)
self.handler_args = self.player, self.track self.handler_args = self.player, self.track
def __repr__(self) -> str: def __repr__(self) -> str:
return f"<Pomice.TrackStartEvent player={self.player!r} track={self.track!r}>" return f"<Pomice.TrackStartEvent player={self.player} track_id={self.track.track_id}>"
class TrackEndEvent(PomiceEvent): class TrackEndEvent(PomiceEvent):
"""Fired when a track has successfully ended. """Fired when a track has successfully ended.
Returns the player associated with the event along with the pomice.Track object and reason. Returns the player associated with the event along with the pomice.Track object and reason.
""" """
name = "track_end" name = "track_end"
__slots__ = ("player", "track", "reason") def __init__(self, data: dict):
self.player = NodePool.get_node().get_player(int(data["guildId"]))
def __init__(self, data: dict, player: Player): self.track = self.player._ending_track
self.player: Player = player
self.track: Optional[Track] = self.player._ending_track
self.reason: str = data["reason"] self.reason: str = data["reason"]
# on_pomice_track_end(player, track, reason) # on_pomice_track_end(player, track, reason)
@ -87,53 +51,46 @@ class TrackEndEvent(PomiceEvent):
def __repr__(self) -> str: def __repr__(self) -> str:
return ( return (
f"<Pomice.TrackEndEvent player={self.player!r} track_id={self.track!r} " f"<Pomice.TrackEndEvent player={self.player} track_id={self.track.track_id} "
f"reason={self.reason!r}>" f"reason={self.reason}>"
) )
class TrackStuckEvent(PomiceEvent): class TrackStuckEvent(PomiceEvent):
"""Fired when a track is stuck and cannot be played. Returns the player """Fired when a track is stuck and cannot be played. Returns the player
associated with the event along with the pomice.Track object associated with the event along with the pomice.Track object
to be further parsed by the end user. to be further parsed by the end user.
""" """
name = "track_stuck" name = "track_stuck"
__slots__ = ("player", "track", "threshold") def __init__(self, data: dict):
self.player = NodePool.get_node().get_player(int(data["guildId"]))
def __init__(self, data: dict, player: Player): self.track = self.player._ending_track
self.player: Player = player
self.track: Optional[Track] = self.player._ending_track
self.threshold: float = data["thresholdMs"] self.threshold: float = data["thresholdMs"]
# on_pomice_track_stuck(player, track, threshold) # on_pomice_track_stuck(player, track, threshold)
self.handler_args = self.player, self.track, self.threshold self.handler_args = self.player, self.track, self.threshold
def __repr__(self) -> str: def __repr__(self) -> str:
return ( return f"<Pomice.TrackStuckEvent player={self.player!r} track={self.track!r} " \
f"<Pomice.TrackStuckEvent player={self.player!r} track={self.track!r} " f"threshold={self.threshold!r}>"
f"threshold={self.threshold!r}>"
)
class TrackExceptionEvent(PomiceEvent): class TrackExceptionEvent(PomiceEvent):
"""Fired when a track error has occured. """Fired when a track error has occured.
Returns the player associated with the event along with the error code and exception. Returns the player associated with the event along with the error code and exception.
""" """
name = "track_exception" name = "track_exception"
__slots__ = ("player", "track", "exception") def __init__(self, data: dict):
self.player = NodePool.get_node().get_player(int(data["guildId"]))
def __init__(self, data: dict, player: Player): self.track = self.player._ending_track
self.player: Player = player if data.get('error'):
self.track: Optional[Track] = self.player._ending_track # User is running Lavalink <= 3.3
# Error is for Lavalink <= 3.3 self.exception: str = data["error"]
self.exception: str = data.get( else:
"error", # User is running Lavalink >=3.4
"", self.exception: str = data["exception"]
) or data.get("exception", "")
# on_pomice_track_exception(player, track, error) # on_pomice_track_exception(player, track, error)
self.handler_args = self.player, self.track, self.exception self.handler_args = self.player, self.track, self.exception
@ -143,35 +100,28 @@ class TrackExceptionEvent(PomiceEvent):
class WebSocketClosedPayload: class WebSocketClosedPayload:
__slots__ = ("guild", "code", "reason", "by_remote")
def __init__(self, data: dict): def __init__(self, data: dict):
self.guild: Optional[Guild] = NodePool.get_node().bot.get_guild(int(data["guildId"])) self.guild = NodePool.get_node().get_player(int(data["guildId"]))._guild
self.code: int = data["code"] self.code: int = data["code"]
self.reason: str = data["code"] self.reason: str = data["code"]
self.by_remote: bool = data["byRemote"] self.by_remote: bool = data["byRemote"]
def __repr__(self) -> str: def __repr__(self) -> str:
return ( return f"<Pomice.WebSocketClosedPayload guild={self.guild!r} code={self.code!r} " \
f"<Pomice.WebSocketClosedPayload guild={self.guild!r} code={self.code!r} " f"reason={self.reason!r} by_remote={self.by_remote!r}>"
f"reason={self.reason!r} by_remote={self.by_remote!r}>"
)
class WebSocketClosedEvent(PomiceEvent): class WebSocketClosedEvent(PomiceEvent):
"""Fired when a websocket connection to a node has been closed. """Fired when a websocket connection to a node has been closed.
Returns the reason and the error code. Returns the reason and the error code.
""" """
name = "websocket_closed" name = "websocket_closed"
__slots__ = ("payload",) def __init__(self, data: dict):
self.payload = WebSocketClosedPayload(data)
def __init__(self, data: dict, _: Any) -> None:
self.payload: WebSocketClosedPayload = WebSocketClosedPayload(data)
# on_pomice_websocket_closed(payload) # on_pomice_websocket_closed(payload)
self.handler_args = (self.payload,) self.handler_args = self.payload,
def __repr__(self) -> str: def __repr__(self) -> str:
return f"<Pomice.WebsocketClosedEvent payload={self.payload!r}>" return f"<Pomice.WebsocketClosedEvent payload={self.payload!r}>"
@ -179,14 +129,11 @@ class WebSocketClosedEvent(PomiceEvent):
class WebSocketOpenEvent(PomiceEvent): class WebSocketOpenEvent(PomiceEvent):
"""Fired when a websocket connection to a node has been initiated. """Fired when a websocket connection to a node has been initiated.
Returns the target and the session SSRC. Returns the target and the session SSRC.
""" """
name = "websocket_open" name = "websocket_open"
__slots__ = ("target", "ssrc") def __init__(self, data: dict):
def __init__(self, data: dict, _: Any) -> None:
self.target: str = data["target"] self.target: str = data["target"]
self.ssrc: int = data["ssrc"] self.ssrc: int = data["ssrc"]

View File

@ -1,26 +1,3 @@
__all__ = (
"PomiceException",
"NodeException",
"NodeCreationError",
"NodeConnectionFailure",
"NodeConnectionClosed",
"NodeRestException",
"NodeNotAvailable",
"NoNodesAvailable",
"TrackInvalidPosition",
"TrackLoadError",
"FilterInvalidArgument",
"FilterTagInvalid",
"FilterTagAlreadyInUse",
"InvalidSpotifyClientAuthorization",
"AppleMusicNotEnabled",
"QueueException",
"QueueFull",
"QueueEmpty",
"LavalinkVersionIncompatible",
)
class PomiceException(Exception): class PomiceException(Exception):
"""Base of all Pomice exceptions.""" """Base of all Pomice exceptions."""
@ -39,89 +16,50 @@ class NodeConnectionFailure(NodeException):
class NodeConnectionClosed(NodeException): class NodeConnectionClosed(NodeException):
"""The node's connection is closed.""" """The node's connection is closed."""
pass
class NodeRestException(NodeException):
"""A request made using the node's REST uri failed"""
pass pass
class NodeNotAvailable(PomiceException): class NodeNotAvailable(PomiceException):
"""The node is currently unavailable.""" """The node is currently unavailable."""
pass pass
class NoNodesAvailable(PomiceException): class NoNodesAvailable(PomiceException):
"""There are no nodes currently available.""" """There are no nodes currently available."""
pass pass
class TrackInvalidPosition(PomiceException): class TrackInvalidPosition(PomiceException):
"""An invalid position was chosen for a track.""" """An invalid position was chosen for a track."""
pass pass
class TrackLoadError(PomiceException): class TrackLoadError(PomiceException):
"""There was an error while loading a track.""" """There was an error while loading a track."""
pass pass
class FilterInvalidArgument(PomiceException): class FilterInvalidArgument(PomiceException):
"""An invalid argument was passed to a filter.""" """An invalid argument was passed to a filter."""
pass pass
class FilterTagInvalid(PomiceException): class SpotifyAlbumLoadFailed(PomiceException):
"""An invalid tag was passed or Pomice was unable to find a filter tag""" """The pomice Spotify client was unable to load an album."""
pass pass
class FilterTagAlreadyInUse(PomiceException): class SpotifyTrackLoadFailed(PomiceException):
"""A filter with a tag is already in use by another filter""" """The pomice Spotify client was unable to load a track."""
pass
class SpotifyPlaylistLoadFailed(PomiceException):
"""The pomice Spotify client was unable to load a playlist."""
pass pass
class InvalidSpotifyClientAuthorization(PomiceException): class InvalidSpotifyClientAuthorization(PomiceException):
"""No Spotify client authorization was provided for track searching.""" """No Spotify client authorization was provided for track searching."""
pass pass
class AppleMusicNotEnabled(PomiceException):
"""An Apple Music Link was passed in when Apple Music functionality was not enabled."""
pass
class QueueException(Exception):
"""Base Pomice queue exception."""
pass
class QueueFull(QueueException):
"""Exception raised when attempting to add to a full Queue."""
pass
class QueueEmpty(QueueException):
"""Exception raised when attempting to retrieve from an empty Queue."""
pass
class LavalinkVersionIncompatible(PomiceException):
"""Lavalink version is incompatible. Must be using Lavalink > 3.7.0 to avoid this error."""
pass

View File

@ -1,51 +1,13 @@
import collections import collections
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
from .exceptions import FilterInvalidArgument from .exceptions import FilterInvalidArgument
__all__ = (
"Filter",
"Equalizer",
"Timescale",
"Karaoke",
"Tremolo",
"Vibrato",
"Rotation",
"Distortion",
"ChannelMix",
"LowPass",
)
class Filter: class Filter:
""" def __init__(self):
The base class for all filters. self.payload = None
You can use these filters if you have the latest Lavalink version
installed. If you do not have the latest Lavalink version,
these filters will not work.
You must specify a tag for each filter you put on.
This is necessary for the removal of filters.
"""
__slots__ = ("payload", "tag", "preload")
def __init__(self, *, tag: str):
self.payload: Optional[Dict] = None
self.tag: str = tag
self.preload: bool = False
def set_preload(self) -> bool:
"""Internal method to set whether or not the filter was preloaded."""
self.preload = True
return self.preload
class Equalizer(Filter): class Equalizer:
""" """
Filter which represents a 15 band equalizer. Filter which represents a 15 band equalizer.
You can adjust the dynamic of the sound using this filter. You can adjust the dynamic of the sound using this filter.
@ -53,151 +15,43 @@ class Equalizer(Filter):
The format for the levels is: List[Tuple[int, float]] The format for the levels is: List[Tuple[int, float]]
""" """
__slots__ = ( def __init__(self, *, levels: list):
"eq", super().__init__()
"raw",
)
def __init__(self, *, tag: str, levels: list): self.eq = self._factory(self, levels)
super().__init__(tag=tag)
self.eq = self._factory(levels)
self.raw = levels self.raw = levels
self.payload = {"equalizer": self.eq} self.payload = {"equalizer": {"bands": self.eq}}
def _factory(self, levels: List[Tuple[Any, Any]]) -> List[Dict]: def _factory(self, levels: list):
_dict: Dict = collections.defaultdict(int) _dict = collections.defaultdict(int)
_dict.update(levels) _dict.update(levels)
data = [{"band": i, "gain": _dict[i]} for i in range(15)] _dict = [{"band": i, "gain": _dict[i]} for i in range(15)]
return data return _dict
def __repr__(self) -> str: def __repr__(self) -> str:
return f"<Pomice.EqualizerFilter tag={self.tag} eq={self.eq} raw={self.raw}>" return f"<Pomice.EqualizerFilter eq={self.eq} raw={self.raw}>"
def __eq__(self, __value: object) -> bool:
if not isinstance(__value, Equalizer):
return False
return self.raw == __value.raw
@classmethod
def flat(cls) -> "Equalizer":
"""Equalizer preset which represents a flat EQ board,
with all levels set to their default values.
"""
levels = [
(0, 0.0),
(1, 0.0),
(2, 0.0),
(3, 0.0),
(4, 0.0),
(5, 0.0),
(6, 0.0),
(7, 0.0),
(8, 0.0),
(9, 0.0),
(10, 0.0),
(11, 0.0),
(12, 0.0),
(13, 0.0),
(14, 0.0),
]
return cls(tag="flat", levels=levels)
@classmethod
def boost(cls) -> "Equalizer":
"""Equalizer preset which boosts the sound of a track,
making it sound fun and energetic by increasing the bass
and the highs.
"""
levels = [
(0, -0.075),
(1, 0.125),
(2, 0.125),
(3, 0.1),
(4, 0.1),
(5, 0.05),
(6, 0.075),
(7, 0.0),
(8, 0.0),
(9, 0.0),
(10, 0.0),
(11, 0.0),
(12, 0.125),
(13, 0.15),
(14, 0.05),
]
return cls(tag="boost", levels=levels)
@classmethod
def metal(cls) -> "Equalizer":
"""Equalizer preset which increases the mids of a track,
preferably one of the metal genre, to make it sound
more full and concert-like.
"""
levels = [
(0, 0.0),
(1, 0.1),
(2, 0.1),
(3, 0.15),
(4, 0.13),
(5, 0.1),
(6, 0.0),
(7, 0.125),
(8, 0.175),
(9, 0.175),
(10, 0.125),
(11, 0.125),
(12, 0.1),
(13, 0.075),
(14, 0.0),
]
return cls(tag="metal", levels=levels)
@classmethod
def piano(cls) -> "Equalizer":
"""Equalizer preset which increases the mids and highs
of a track, preferably a piano based one, to make it
stand out.
"""
levels = [
(0, -0.25),
(1, -0.25),
(2, -0.125),
(3, 0.0),
(4, 0.25),
(5, 0.25),
(6, 0.0),
(7, -0.25),
(8, -0.25),
(9, 0.0),
(10, 0.0),
(11, 0.5),
(12, 0.25),
(13, -0.025),
]
return cls(tag="piano", levels=levels)
class Timescale(Filter): class Timescale(Filter):
"""Filter which changes the speed and pitch of a track. """Filter which changes the speed and pitch of a track.
You can make some very nice effects with this filter, Do be warned that this filter is bugged as of the lastest Lavalink dev version
i.e: a vaporwave-esque filter which slows the track down due to the filter patch not corresponding with the track time.
a certain amount to produce said effect.
In short this means that your track will either end prematurely or end later due to this.
This is not the library's fault.
""" """
__slots__ = ("speed", "pitch", "rate") def __init__(
self,
def __init__(self, *, tag: str, speed: float = 1.0, pitch: float = 1.0, rate: float = 1.0): *,
super().__init__(tag=tag) speed: float = 1.0,
pitch: float = 1.0,
rate: float = 1.0
):
super().__init__()
if speed < 0: if speed < 0:
raise FilterInvalidArgument("Timescale speed must be more than 0.") raise FilterInvalidArgument("Timescale speed must be more than 0.")
@ -206,178 +60,108 @@ class Timescale(Filter):
if rate < 0: if rate < 0:
raise FilterInvalidArgument("Timescale rate must be more than 0.") raise FilterInvalidArgument("Timescale rate must be more than 0.")
self.speed: float = speed self.speed = speed
self.pitch: float = pitch self.pitch = pitch
self.rate: float = rate self.rate = rate
self.payload: dict = { self.payload = {"timescale": {"speed": self.speed,
"timescale": {"speed": self.speed, "pitch": self.pitch, "rate": self.rate}, "pitch": self.pitch,
} "rate": self.rate}}
@classmethod def __repr__(self):
def vaporwave(cls) -> "Timescale": return f"<Pomice.TimescaleFilter speed={self.speed} pitch={self.pitch} rate={self.rate}>"
"""Timescale preset which slows down the currently playing track,
giving it the effect of a half-speed record/casette playing.
This preset will assign the tag 'vaporwave'.
"""
return cls(tag="vaporwave", speed=0.8, pitch=0.8)
@classmethod
def nightcore(cls) -> "Timescale":
"""Timescale preset which speeds up the currently playing track,
which matches up to nightcore, a genre of sped-up music
This preset will assign the tag 'nightcore'.
"""
return cls(tag="nightcore", speed=1.25, pitch=1.3)
def __repr__(self) -> str:
return f"<Pomice.TimescaleFilter tag={self.tag} speed={self.speed} pitch={self.pitch} rate={self.rate}>"
def __eq__(self, __value: object) -> bool:
if not isinstance(__value, Timescale):
return False
return (
self.speed == __value.speed
and self.pitch == __value.pitch
and self.rate == __value.rate
)
class Karaoke(Filter): class Karaoke(Filter):
"""Filter which filters the vocal track from any song and leaves the instrumental. """Filter which filters the vocal track from any song and leaves the instrumental.
Best for karaoke as the filter implies. Best for karaoke as the filter implies.
""" """
__slots__ = ("level", "mono_level", "filter_band", "filter_width")
def __init__( def __init__(
self, self,
*, *,
tag: str,
level: float = 1.0, level: float = 1.0,
mono_level: float = 1.0, mono_level: float = 1.0,
filter_band: float = 220.0, filter_band: float = 220.0,
filter_width: float = 100.0, filter_width: float = 100.0
): ):
super().__init__(tag=tag) super().__init__()
self.level: float = level self.level = level
self.mono_level: float = mono_level self.mono_level = mono_level
self.filter_band: float = filter_band self.filter_band = filter_band
self.filter_width: float = filter_width self.filter_width = filter_width
self.payload: dict = { self.payload = {"karaoke": {"level": self.level,
"karaoke": { "monoLevel": self.mono_level,
"level": self.level, "filterBand": self.filter_band,
"monoLevel": self.mono_level, "filterWidth": self.filter_width}}
"filterBand": self.filter_band,
"filterWidth": self.filter_width,
},
}
def __repr__(self) -> str: def __repr__(self):
return ( return (
f"<Pomice.KaraokeFilter tag={self.tag} level={self.level} mono_level={self.mono_level} " f"<Pomice.KaraokeFilter level={self.level} mono_level={self.mono_level} "
f"filter_band={self.filter_band} filter_width={self.filter_width}>" f"filter_band={self.filter_band} filter_width={self.filter_width}>"
) )
def __eq__(self, __value: object) -> bool:
if not isinstance(__value, Karaoke):
return False
return (
self.level == __value.level
and self.mono_level == __value.mono_level
and self.filter_band == __value.filter_band
and self.filter_width == __value.filter_width
)
class Tremolo(Filter): class Tremolo(Filter):
"""Filter which produces a wavering tone in the music, """Filter which produces a wavering tone in the music,
causing it to sound like the music is changing in volume rapidly. causing it to sound like the music is changing in volume rapidly.
""" """
__slots__ = ("frequency", "depth") def __init__(
self,
def __init__(self, *, tag: str, frequency: float = 2.0, depth: float = 0.5): *,
super().__init__(tag=tag) frequency: float = 2.0,
depth: float = 0.5
):
super().__init__()
if frequency < 0: if frequency < 0:
raise FilterInvalidArgument( raise FilterInvalidArgument(
"Tremolo frequency must be more than 0.", "Tremolo frequency must be more than 0.")
)
if depth < 0 or depth > 1: if depth < 0 or depth > 1:
raise FilterInvalidArgument( raise FilterInvalidArgument(
"Tremolo depth must be between 0 and 1.", "Tremolo depth must be between 0 and 1.")
)
self.frequency: float = frequency self.frequency = frequency
self.depth: float = depth self.depth = depth
self.payload: dict = { self.payload = {"tremolo": {"frequency": self.frequency,
"tremolo": { "depth": self.depth}}
"frequency": self.frequency,
"depth": self.depth,
},
}
def __repr__(self) -> str: def __repr__(self):
return ( return f"<Pomice.TremoloFilter frequency={self.frequency} depth={self.depth}>"
f"<Pomice.TremoloFilter tag={self.tag} frequency={self.frequency} depth={self.depth}>"
)
def __eq__(self, __value: object) -> bool:
if not isinstance(__value, Tremolo):
return False
return self.frequency == __value.frequency and self.depth == __value.depth
class Vibrato(Filter): class Vibrato(Filter):
"""Filter which produces a wavering tone in the music, similar to the Tremolo filter, """Filter which produces a wavering tone in the music, similar to the Tremolo filter,
but changes in pitch rather than volume. but changes in pitch rather than volume.
""" """
__slots__ = ("frequency", "depth") def __init__(
self,
def __init__(self, *, tag: str, frequency: float = 2.0, depth: float = 0.5): *,
super().__init__(tag=tag) frequency: float = 2.0,
depth: float = 0.5
):
super().__init__()
if frequency < 0 or frequency > 14: if frequency < 0 or frequency > 14:
raise FilterInvalidArgument( raise FilterInvalidArgument(
"Vibrato frequency must be between 0 and 14.", "Vibrato frequency must be between 0 and 14.")
)
if depth < 0 or depth > 1: if depth < 0 or depth > 1:
raise FilterInvalidArgument( raise FilterInvalidArgument(
"Vibrato depth must be between 0 and 1.", "Vibrato depth must be between 0 and 1.")
)
self.frequency: float = frequency self.frequency = frequency
self.depth: float = depth self.depth = depth
self.payload: dict = { self.payload = {"vibrato": {"frequency": self.frequency,
"vibrato": { "depth": self.depth}}
"frequency": self.frequency,
"depth": self.depth,
},
}
def __repr__(self) -> str: def __repr__(self):
return ( return f"<Pomice.VibratoFilter frequency={self.frequency} depth={self.depth}>"
f"<Pomice.VibratoFilter tag={self.tag} frequency={self.frequency} depth={self.depth}>"
)
def __eq__(self, __value: object) -> bool:
if not isinstance(__value, Vibrato):
return False
return self.frequency == __value.frequency and self.depth == __value.depth
class Rotation(Filter): class Rotation(Filter):
@ -385,22 +169,14 @@ class Rotation(Filter):
the audio is being rotated around the listener's head the audio is being rotated around the listener's head
""" """
__slots__ = ("rotation_hertz",) def __init__(self, *, rotation_hertz: float = 5):
super().__init__()
def __init__(self, *, tag: str, rotation_hertz: float = 5): self.rotation_hertz = rotation_hertz
super().__init__(tag=tag) self.payload = {"rotation": {"rotationHz": self.rotation_hertz}}
self.rotation_hertz: float = rotation_hertz
self.payload: dict = {"rotation": {"rotationHz": self.rotation_hertz}}
def __repr__(self) -> str: def __repr__(self) -> str:
return f"<Pomice.RotationFilter tag={self.tag} rotation_hertz={self.rotation_hertz}>" return f"<Pomice.RotationFilter rotation_hertz={self.rotation_hertz}>"
def __eq__(self, __value: object) -> bool:
if not isinstance(__value, Rotation):
return False
return self.rotation_hertz == __value.rotation_hertz
class ChannelMix(Filter): class ChannelMix(Filter):
@ -408,146 +184,90 @@ class ChannelMix(Filter):
for some cool effects when done correctly. for some cool effects when done correctly.
""" """
__slots__ = (
"left_to_left",
"right_to_right",
"left_to_right",
"right_to_left",
)
def __init__( def __init__(
self, self,
*, *,
tag: str,
left_to_left: float = 1, left_to_left: float = 1,
right_to_right: float = 1, right_to_right: float = 1,
left_to_right: float = 0, left_to_right: float = 0,
right_to_left: float = 0, right_to_left: float = 0
): ):
super().__init__(tag=tag) super().__init__()
if 0 > left_to_left > 1: if 0 > left_to_left > 1:
raise ValueError( raise ValueError(
"'left_to_left' value must be more than or equal to 0 or less than or equal to 1.", "'left_to_left' value must be more than or equal to 0 or less than or equal to 1.")
)
if 0 > right_to_right > 1: if 0 > right_to_right > 1:
raise ValueError( raise ValueError(
"'right_to_right' value must be more than or equal to 0 or less than or equal to 1.", "'right_to_right' value must be more than or equal to 0 or less than or equal to 1.")
)
if 0 > left_to_right > 1: if 0 > left_to_right > 1:
raise ValueError( raise ValueError(
"'left_to_right' value must be more than or equal to 0 or less than or equal to 1.", "'left_to_right' value must be more than or equal to 0 or less than or equal to 1.")
)
if 0 > right_to_left > 1: if 0 > right_to_left > 1:
raise ValueError( raise ValueError(
"'right_to_left' value must be more than or equal to 0 or less than or equal to 1.", "'right_to_left' value must be more than or equal to 0 or less than or equal to 1.")
)
self.left_to_left: float = left_to_left self.left_to_left = left_to_left
self.left_to_right: float = left_to_right self.left_to_right = left_to_right
self.right_to_left: float = right_to_left self.right_to_left = right_to_left
self.right_to_right: float = right_to_right self.right_to_right = right_to_right
self.payload: dict = { self.payload = {"channelMix": {"leftToLeft": self.left_to_left,
"channelMix": { "leftToRight": self.left_to_right,
"leftToLeft": self.left_to_left, "rightToLeft": self.right_to_left,
"leftToRight": self.left_to_right, "rightToRight": self.right_to_right}
"rightToLeft": self.right_to_left, }
"rightToRight": self.right_to_right,
},
}
def __repr__(self) -> str: def __repr__(self) -> str:
return ( return (
f"<Pomice.ChannelMix tag={self.tag} left_to_left={self.left_to_left} left_to_right={self.left_to_right} " f"<Pomice.ChannelMix left_to_left={self.left_to_left} left_to_right={self.left_to_right} "
f"right_to_left={self.right_to_left} right_to_right={self.right_to_right}>" f"right_to_left={self.right_to_left} right_to_right={self.right_to_right}>"
) )
def __eq__(self, __value: object) -> bool:
if not isinstance(__value, ChannelMix):
return False
return (
self.left_to_left == __value.left_to_left
and self.left_to_right == __value.left_to_right
and self.right_to_left == __value.right_to_left
and self.right_to_right == __value.right_to_right
)
class Distortion(Filter): class Distortion(Filter):
"""Filter which generates a distortion effect. Useful for certain filter implementations where """Filter which generates a distortion effect. Useful for certain filter implementations where
distortion is needed. distortion is needed.
""" """
__slots__ = (
"sin_offset",
"sin_scale",
"cos_offset",
"cos_scale",
"tan_offset",
"tan_scale",
"offset",
"scale",
)
def __init__( def __init__(
self, self,
*, *,
tag: str, sin_offset: float = 0,
sin_offset: float = 0,
sin_scale: float = 1, sin_scale: float = 1,
cos_offset: float = 0, cos_offset: float = 0,
cos_scale: float = 1, cos_scale: float = 1,
tan_offset: float = 0, tan_offset: float = 0,
tan_scale: float = 1, tan_scale: float = 1,
offset: float = 0, offset: float = 0,
scale: float = 1, scale: float = 1
): ):
super().__init__(tag=tag) super().__init__()
self.sin_offset: float = sin_offset self.sin_offset = sin_offset
self.sin_scale: float = sin_scale self.sin_scale = sin_scale
self.cos_offset: float = cos_offset self.cos_offset = cos_offset
self.cos_scale: float = cos_scale self.cos_scale = cos_scale
self.tan_offset: float = tan_offset self.tan_offset = tan_offset
self.tan_scale: float = tan_scale self.tan_scale = tan_scale
self.offset: float = offset self.offset = offset
self.scale: float = scale self.scale = scale
self.payload: dict = { self.payload = {"distortion": {
"distortion": { "sinOffset": self.sin_offset,
"sinOffset": self.sin_offset, "sinScale": self.sin_scale,
"sinScale": self.sin_scale, "cosOffset": self.cos_offset,
"cosOffset": self.cos_offset, "cosScale": self.cos_scale,
"cosScale": self.cos_scale, "tanOffset": self.tan_offset,
"tanOffset": self.tan_offset, "tanScale": self.tan_scale,
"tanScale": self.tan_scale, "offset": self.offset,
"offset": self.offset, "scale": self.scale
"scale": self.scale, }}
},
}
def __repr__(self) -> str: def __repr__(self) -> str:
return ( return (
f"<Pomice.Distortion tag={self.tag} sin_offset={self.sin_offset} sin_scale={self.sin_scale}> " f"<Pomice.Distortion sin_offset={self.sin_offset} sin_scale={self.sin_scale}> "
f"cos_offset={self.cos_offset} cos_scale={self.cos_scale} tan_offset={self.tan_offset} " f"cos_offset={self.cos_offset} cos_scale={self.cos_scale} tan_offset={self.tan_offset} "
f"tan_scale={self.tan_scale} offset={self.offset} scale={self.scale}" f"tan_scale={self.tan_scale} offset={self.offset} scale={self.scale}"
)
def __eq__(self, __value: object) -> bool:
if not isinstance(__value, Distortion):
return False
return (
self.sin_offset == __value.sin_offset
and self.sin_scale == __value.sin_scale
and self.cos_offset == __value.cos_offset
and self.cos_scale == __value.cos_scale
and self.tan_offset == __value.tan_offset
and self.tan_scale == __value.tan_scale
and self.offset == __value.offset
and self.scale == __value.scale
) )
@ -556,19 +276,13 @@ class LowPass(Filter):
You can also do this with the Equalizer filter, but this is an easier way to do it. You can also do this with the Equalizer filter, but this is an easier way to do it.
""" """
__slots__ = ("smoothing", "payload") def __init__(self, *, smoothing: float = 20):
super().__init__()
def __init__(self, *, tag: str, smoothing: float = 20): self.smoothing = smoothing
super().__init__(tag=tag) self.payload = {"lowPass": {"smoothing": self.smoothing}}
self.smoothing: float = smoothing
self.payload: dict = {"lowPass": {"smoothing": self.smoothing}}
def __repr__(self) -> str: def __repr__(self) -> str:
return f"<Pomice.LowPass tag={self.tag} smoothing={self.smoothing}>" return f"<Pomice.LowPass smoothing={self.smoothing}>"
def __eq__(self, __value: object) -> bool:
if not isinstance(__value, LowPass):
return False
return self.smoothing == __value.smoothing

View File

@ -1,167 +1,106 @@
from __future__ import annotations
from typing import List
from typing import Optional from typing import Optional
from typing import Union
from discord import ClientUser
from discord import Member
from discord import User
from discord.ext import commands from discord.ext import commands
from .enums import PlaylistType
from .enums import SearchType from .enums import SearchType
from .enums import TrackType
from .filters import Filter
__all__ = (
"Track",
"Playlist",
)
class Track: class Track:
"""The base track object. Returns critical track information needed for parsing by Lavalink. """The base track object. Returns critical track information needed for parsing by Lavalink.
You can also pass in commands.Context to get a discord.py Context object in your track. You can also pass in commands.Context to get a discord.py Context object in your track.
""" """
__slots__ = (
"track_id",
"info",
"track_type",
"filters",
"timestamp",
"original",
"_search_type",
"playlist",
"title",
"author",
"uri",
"identifier",
"isrc",
"thumbnail",
"length",
"ctx",
"requester",
"is_stream",
"is_seekable",
"position",
)
def __init__( def __init__(
self, self,
*, *,
track_id: str, track_id: str,
info: dict, info: dict,
ctx: Optional[commands.Context] = None, ctx: Optional[commands.Context] = None,
track_type: TrackType, spotify: bool = False,
search_type: SearchType = SearchType.ytsearch, search_type: SearchType = SearchType.ytsearch
filters: Optional[List[Filter]] = None,
timestamp: Optional[float] = None,
requester: Optional[Union[Member, User, ClientUser]] = None,
): ):
self.track_id: str = track_id self.track_id = track_id
self.info: dict = info self.info = info
self.track_type: TrackType = track_type self.spotify = spotify
self.filters: Optional[List[Filter]] = filters
self.timestamp: Optional[float] = timestamp
if self.track_type == TrackType.SPOTIFY or self.track_type == TrackType.APPLE_MUSIC: self.original: Optional[Track] = None if self.spotify else self
self.original: Optional[Track] = None self._search_type = search_type
else:
self.original = self
self._search_type: SearchType = search_type
self.playlist: Optional[Playlist] = None self.title = info.get("title")
self.author = info.get("author")
self.length = info.get("length")
self.ctx = ctx
self.requester = self.ctx.author if ctx else None
self.identifier = info.get("identifier")
self.uri = info.get("uri")
self.is_stream = info.get("isStream")
self.is_seekable = info.get("isSeekable")
self.position = info.get("position")
self.title: str = info.get("title", "Unknown Title") def __eq__(self, other):
self.author: str = info.get("author", "Unknown Author")
self.uri: str = info.get("uri", "")
self.identifier: str = info.get("identifier", "")
self.isrc: Optional[str] = info.get("isrc", None)
self.thumbnail: Optional[str] = info.get("thumbnail")
if self.uri and self.track_type is TrackType.YOUTUBE:
self.thumbnail = f"https://img.youtube.com/vi/{self.identifier}/mqdefault.jpg"
self.length: int = info.get("length", 0)
self.is_stream: bool = info.get("isStream", False)
self.is_seekable: bool = info.get("isSeekable", False)
self.position: int = info.get("position", 0)
self.ctx: Optional[commands.Context] = ctx
self.requester: Optional[Union[Member, User, ClientUser]] = requester
if not self.requester and self.ctx:
self.requester = self.ctx.author
def __eq__(self, other: object) -> bool:
if not isinstance(other, Track): if not isinstance(other, Track):
return False return False
if self.ctx and other.ctx:
return other.track_id == self.track_id and other.ctx.message.id == self.ctx.message.id
return other.track_id == self.track_id return other.track_id == self.track_id
def __str__(self) -> str: def __str__(self):
return self.title return self.title
def __repr__(self) -> str: def __repr__(self):
return f"<Pomice.track title={self.title!r} uri=<{self.uri!r}> length={self.length}>" return f"<Pomice.track title={self.title!r} uri=<{self.uri!r}> length={self.length}>"
class Playlist: class Playlist:
"""The base playlist object. """The base playlist object.
Returns critical playlist information needed for parsing by Lavalink. Returns critical playlist information needed for parsing by Lavalink.
You can also pass in commands.Context to get a discord.py Context object in your tracks. You can also pass in commands.Context to get a discord.py Context object in your tracks.
""" """
__slots__ = (
"playlist_info",
"tracks",
"name",
"playlist_type",
"_thumbnail",
"_uri",
"selected_track",
"track_count",
)
def __init__( def __init__(
self, self,
*, *,
playlist_info: dict, playlist_info: dict,
tracks: list, tracks: list,
playlist_type: PlaylistType, ctx: Optional[commands.Context] = None,
spotify: bool = False,
thumbnail: Optional[str] = None, thumbnail: Optional[str] = None,
uri: Optional[str] = None, uri: Optional[str] = None,
): ):
self.playlist_info: dict = playlist_info self.playlist_info = playlist_info
self.tracks: List[Track] = tracks self.tracks_raw = tracks
self.name: str = playlist_info.get("name", "Unknown Playlist") self.spotify = spotify
self.playlist_type: PlaylistType = playlist_type
self._thumbnail: Optional[str] = thumbnail self.name = playlist_info.get("name")
self._uri: Optional[str] = uri self.selected_track = playlist_info.get("selectedTrack")
for track in self.tracks: self._thumbnail = thumbnail
track.playlist = self self._uri = uri
self.selected_track: Optional[Track] = None if self.spotify:
if (index := playlist_info.get("selectedTrack", -1)) != -1: self.tracks = tracks
self.selected_track = self.tracks[index] else:
self.tracks = [
Track(track_id=track["track"], info=track["info"], ctx=ctx)
for track in self.tracks_raw
]
self.track_count: int = len(self.tracks) self.track_count = len(self.tracks)
def __str__(self) -> str: def __str__(self):
return self.name return self.name
def __repr__(self) -> str: def __repr__(self):
return f"<Pomice.playlist name={self.name!r} track_count={len(self.tracks)}>" return f"<Pomice.playlist name={self.name!r} track_count={len(self.tracks)}>"
@property @property
def uri(self) -> Optional[str]: def uri(self) -> Optional[str]:
"""Returns either an Apple Music/Spotify URL/URI, or None if its neither of those.""" """Spotify album/playlist URI, or None if not a Spotify object."""
return self._uri return self._uri
@property @property
def thumbnail(self) -> Optional[str]: def thumbnail(self) -> Optional[str]:
"""Returns either an Apple Music/Spotify album/playlist thumbnail, or None if its neither of those.""" """Spotify album/playlist thumbnail, or None if not a Spotify object."""
return self._thumbnail return self._thumbnail

View File

@ -1,197 +1,63 @@
from __future__ import annotations
import time import time
from typing import Any from typing import (
from typing import Dict Any,
from typing import List Dict,
from typing import Optional Optional
from typing import TYPE_CHECKING )
from typing import Union
from discord import Client from discord import (
from discord import Guild Guild,
from discord import VoiceChannel VoiceChannel,
from discord import VoiceProtocol VoiceProtocol
)
from discord.ext import commands from discord.ext import commands
from . import events from . import events
from .enums import SearchType from .enums import SearchType
from .events import PomiceEvent from .events import PomiceEvent, TrackEndEvent, TrackStartEvent
from .events import TrackEndEvent
from .events import TrackStartEvent
from .exceptions import FilterInvalidArgument
from .exceptions import FilterTagAlreadyInUse
from .exceptions import FilterTagInvalid
from .exceptions import TrackInvalidPosition from .exceptions import TrackInvalidPosition
from .exceptions import TrackLoadError
from .filters import Filter from .filters import Filter
from .filters import Timescale
from .objects import Playlist
from .objects import Track from .objects import Track
from .pool import Node from .pool import Node, NodePool
from .pool import NodePool from .utils import ClientType
from pomice.utils import LavalinkVersion
if TYPE_CHECKING:
from discord.types.voice import VoiceServerUpdate
from discord.types.voice import GuildVoiceState
__all__ = ("Filters", "Player")
class Filters:
"""Helper class for filters"""
__slots__ = ("_filters",)
def __init__(self) -> None:
self._filters: List[Filter] = []
@property
def has_preload(self) -> bool:
"""Property which checks if any applied filters were preloaded"""
return any(f for f in self._filters if f.preload == True)
@property
def has_global(self) -> bool:
"""Property which checks if any applied filters are global"""
return any(f for f in self._filters if f.preload == False)
@property
def empty(self) -> bool:
"""Property which checks if the filter list is empty"""
return len(self._filters) == 0
def add_filter(self, *, filter: Filter) -> None:
"""Adds a filter to the list of filters applied"""
if any(f for f in self._filters if f.tag == filter.tag):
raise FilterTagAlreadyInUse(
"A filter with that tag is already in use.",
)
self._filters.append(filter)
def remove_filter(self, *, filter_tag: str) -> None:
"""Removes a filter from the list of filters applied using its filter tag"""
if not any(f for f in self._filters if f.tag == filter_tag):
raise FilterTagInvalid("A filter with that tag was not found.")
for index, filter in enumerate(self._filters):
if filter.tag == filter_tag:
del self._filters[index]
def edit_filter(self, *, filter_tag: str, to_apply: Filter) -> None:
"""Edits a filter in the list of filters applied using its filter tag and replaces it with the new filter."""
if not any(f for f in self._filters if f.tag == filter_tag):
raise FilterTagInvalid("A filter with that tag was not found.")
for index, filter in enumerate(self._filters):
if filter.tag == filter_tag:
if not type(filter) == type(to_apply):
raise FilterInvalidArgument(
"Edited filter is not the same type as the current filter.",
)
if self._filters[index] == to_apply:
raise FilterInvalidArgument("Edited filter is the same as the current filter.")
if to_apply.tag != filter_tag:
raise FilterInvalidArgument(
"Edited filter tag is not the same as the current filter tag.",
)
self._filters[index] = to_apply
def has_filter(self, *, filter_tag: str) -> bool:
"""Checks if a filter exists in the list of filters using its filter tag"""
return any(f for f in self._filters if f.tag == filter_tag)
def has_filter_type(self, *, filter_type: Filter) -> bool:
"""Checks if any filters applied match the specified filter type."""
return any(f for f in self._filters if type(f) == type(filter_type))
def reset_filters(self) -> None:
"""Removes all filters from the list"""
self._filters = []
def get_preload_filters(self) -> List[Filter]:
"""Get all preloaded filters"""
return [f for f in self._filters if f.preload == True]
def get_all_payloads(self) -> Dict[str, Any]:
"""Returns a formatted dict of all the filter payloads"""
payload: Dict[str, Any] = {}
for _filter in self._filters:
if _filter.payload:
payload.update(_filter.payload)
return payload
def get_filters(self) -> List[Filter]:
"""Returns the current list of applied filters"""
return self._filters
class Player(VoiceProtocol): class Player(VoiceProtocol):
"""The base player class for Pomice. """The base player class for Pomice.
In order to initiate a player, you must pass it in as a cls when you connect to a channel. In order to initiate a player, you must pass it in as a cls when you connect to a channel.
i.e: ```py i.e: ```py
await ctx.author.voice.channel.connect(cls=pomice.Player) await ctx.author.voice.channel.connect(cls=pomice.Player)
``` ```
""" """
__slots__ = ( def __call__(self, client: ClientType, channel: VoiceChannel):
"client", self.client: ClientType = client
"channel", self.channel: VoiceChannel = channel
"_bot",
"_guild",
"_node",
"_current",
"_filters",
"_volume",
"_paused",
"_is_connected",
"_last_position",
"_last_update",
"_ending_track",
"_log",
"_voice_state",
"_player_endpoint_uri",
)
def __call__(self, client: Client, channel: VoiceChannel) -> Player:
self.client = client
self.channel = channel
self._guild = channel.guild
return self return self
def __init__( def __init__(self, client: ClientType = None, channel: VoiceChannel = None, **kwargs):
self, self.client = client
client: Client, self._bot = client
channel: VoiceChannel, self.channel = channel
*, self._guild: Guild = self.channel.guild
node: Optional[Node] = None,
) -> None:
self.client: Client = client
self.channel: VoiceChannel = channel
self._guild = channel.guild
self._bot: Client = client self._node = NodePool.get_node()
self._node: Node = node if node else NodePool.get_node() self._current: Track = None
self._current: Optional[Track] = None self._filter: Filter = None
self._filters: Filters = Filters() self._volume = 100
self._volume: int = 100 self._paused = False
self._paused: bool = False self._is_connected = False
self._is_connected: bool = False
self._last_position: int = 0 self._position = 0
self._last_update: float = 0 self._last_position = 0
self._last_update = 0
self._ending_track: Optional[Track] = None self._ending_track: Optional[Track] = None
self._log = self._node._log
self._voice_state: dict = {} self._voice_state = {}
self._extra = kwargs or {}
self._player_endpoint_uri: str = f"sessions/{self._node._session_id}/players" def __repr__(self):
def __repr__(self) -> str:
return ( return (
f"<Pomice.player bot={self.bot} guildId={self.guild.id} " f"<Pomice.player bot={self.bot} guildId={self.guild.id} "
f"is_connected={self.is_connected} is_playing={self.is_playing}>" f"is_connected={self.is_connected} is_playing={self.is_playing}>"
@ -200,45 +66,25 @@ class Player(VoiceProtocol):
@property @property
def position(self) -> float: def position(self) -> float:
"""Property which returns the player's position in a track in milliseconds""" """Property which returns the player's position in a track in milliseconds"""
if not self.is_playing:
if not self.is_playing or not self.current:
return 0 return 0
current: Track = self._current # type: ignore
if current.original:
current = current.original
if self.is_paused: if self.is_paused:
return min(self._last_position, current.length) return min(self._last_position, self.current.length)
difference = (time.time() * 1000) - self._last_update difference = (time.time() * 1000) - self._last_update
position = self._last_position + difference position = self._last_position + difference
return round(min(position, current.length)) if position > self.current.length:
@property
def rate(self) -> float:
"""Property which returns the player's current rate"""
if _filter := next((f for f in self._filters._filters if isinstance(f, Timescale)), None):
return _filter.speed or _filter.rate
return 1.0
@property
def adjusted_position(self) -> float:
"""Property which returns the player's position in a track in milliseconds adjusted for rate"""
return self.position / self.rate
@property
def adjusted_length(self) -> float:
"""Property which returns the player's track length in milliseconds adjusted for rate"""
if not self.is_playing:
return 0 return 0
return self.current.length / self.rate # type: ignore return min(position, self.current.length)
@property @property
def is_playing(self) -> bool: def is_playing(self) -> bool:
"""Property which returns whether or not the player is actively playing a track.""" """Property which returns whether or not the player is actively playing a track."""
return self._is_connected and self._current is not None return self._is_connected and self.current is not None
@property @property
def is_connected(self) -> bool: def is_connected(self) -> bool:
@ -251,7 +97,7 @@ class Player(VoiceProtocol):
return self._is_connected and self._paused return self._is_connected and self._paused
@property @property
def current(self) -> Optional[Track]: def current(self) -> Track:
"""Property which returns the currently playing track""" """Property which returns the currently playing track"""
return self._current return self._current
@ -271,93 +117,62 @@ class Player(VoiceProtocol):
return self._volume return self._volume
@property @property
def filters(self) -> Filters: def filter(self) -> Filter:
"""Property which returns the helper class for interacting with filters""" """Property which returns the currently applied filter, if one is applied"""
return self._filters return self._filter
@property @property
def bot(self) -> Client: def bot(self) -> ClientType:
"""Property which returns the bot associated with this player instance""" """Property which returns the bot associated with this player instance"""
return self._bot return self._bot
@property @property
def is_dead(self) -> bool: def is_dead(self) -> bool:
"""Returns a bool representing whether the player is dead or not. """Returns a bool representing whether the player is dead or not.
A player is considered dead if it has been destroyed and removed from stored players. A player is considered dead if it has been destroyed and removed from stored players.
""" """
return self.guild.id not in self._node._players return self._guild.id not in self._node._players
def _adjust_end_time(self) -> Optional[str]: async def _update_state(self, data: dict):
if self._node._version >= LavalinkVersion(3, 7, 5): state: dict = data.get("state")
return None self._last_update = time.time() * 1000
self._is_connected = state.get("connected")
self._last_position = state.get("position")
return "0" async def _dispatch_voice_update(self, voice_data: Dict[str, Any]):
async def _update_state(self, data: dict) -> None:
state: dict = data.get("state", {})
self._last_update = int(state.get("time", 0))
self._is_connected = bool(state.get("connected"))
self._last_position = int(state.get("position", 0))
if self._log:
self._log.debug(f"Got player update state with data {state}")
async def _dispatch_voice_update(self, voice_data: Optional[Dict[str, Any]] = None) -> None:
if {"sessionId", "event"} != self._voice_state.keys(): if {"sessionId", "event"} != self._voice_state.keys():
return return
state = voice_data or self._voice_state
data = {
"token": state["event"]["token"],
"endpoint": state["event"]["endpoint"],
"sessionId": state["sessionId"],
}
await self._node.send( await self._node.send(
method="PATCH", op="voiceUpdate",
path=self._player_endpoint_uri, guildId=str(self.guild.id),
guild_id=self._guild.id, **voice_data
data={"voice": data},
) )
if self._log: async def on_voice_server_update(self, data: dict):
self._log.debug(
f"Dispatched voice update to {state['event']['endpoint']} with data {data}",
)
async def on_voice_server_update(self, data: VoiceServerUpdate) -> None:
self._voice_state.update({"event": data}) self._voice_state.update({"event": data})
await self._dispatch_voice_update(self._voice_state) await self._dispatch_voice_update(self._voice_state)
async def on_voice_state_update(self, data: GuildVoiceState) -> None: async def on_voice_state_update(self, data: dict):
self._voice_state.update({"sessionId": data.get("session_id")}) self._voice_state.update({"sessionId": data.get("session_id")})
channel_id = data.get("channel_id") if not (channel_id := data.get("channel_id")):
if not channel_id:
await self.disconnect() await self.disconnect()
self._voice_state.clear() self._voice_state.clear()
return return
channel = self.guild.get_channel(int(channel_id)) self.channel = self.guild.get_channel(int(channel_id))
if self.channel != channel:
self.channel = channel
if not channel:
await self.disconnect()
self._voice_state.clear()
return
if not data.get("token"): if not data.get("token"):
return return
await self._dispatch_voice_update({**self._voice_state, "event": data}) await self._dispatch_voice_update({**self._voice_state, "event": data})
async def _dispatch_event(self, data: dict) -> None: async def _dispatch_event(self, data: dict):
event_type: str = data["type"] event_type = data.get("type")
event: PomiceEvent = getattr(events, event_type)(data, self) event: PomiceEvent = getattr(events, event_type)(data)
if isinstance(event, TrackEndEvent) and event.reason not in ("REPLACED", "replaced"): if isinstance(event, TrackEndEvent):
self._current = None self._current = None
event.dispatch(self._bot) event.dispatch(self._bot)
@ -365,116 +180,44 @@ class Player(VoiceProtocol):
if isinstance(event, TrackStartEvent): if isinstance(event, TrackStartEvent):
self._ending_track = self._current self._ending_track = self._current
if self._log:
self._log.debug(f"Dispatched event {data['type']} to player.")
async def _refresh_endpoint_uri(self, session_id: Optional[str]) -> None:
self._player_endpoint_uri = f"sessions/{session_id}/players"
async def _swap_node(self, *, new_node: Node) -> None:
if self.current:
data: dict = {"position": self.position, "encodedTrack": self.current.track_id}
del self._node._players[self._guild.id]
self._node = new_node
self._node._players[self._guild.id] = self
# reassign uri to update session id
await self._refresh_endpoint_uri(new_node._session_id)
await self._dispatch_voice_update()
await self._node.send(
method="PATCH",
path=self._player_endpoint_uri,
guild_id=self._guild.id,
data=data or None,
)
if self._log:
self._log.debug(f"Swapped all players to new node {new_node._identifier}.")
async def get_tracks( async def get_tracks(
self, self,
query: str, query: str,
*, *,
ctx: Optional[commands.Context] = None, ctx: Optional[commands.Context] = None,
search_type: SearchType | None = SearchType.ytsearch, search_type: SearchType = SearchType.ytsearch
filters: Optional[List[Filter]] = None, ):
) -> Optional[Union[List[Track], Playlist]]:
"""Fetches tracks from the node's REST api to parse into Lavalink. """Fetches tracks from the node's REST api to parse into Lavalink.
If you passed in Spotify API credentials when you created the node, If you passed in Spotify API credentials when you created the node,
you can also pass in a Spotify URL of a playlist, album or track and it will be parsed you can also pass in a Spotify URL of a playlist, album or track and it will be parsed
accordingly. accordingly.
You can pass in a discord.py Context object to get a
Context object on any track you search.
You may also pass in a List of filters
to be applied to your track once it plays.
"""
return await self._node.get_tracks(query, ctx=ctx, search_type=search_type, filters=filters)
async def build_track(self, identifier: str, ctx: Optional[commands.Context] = None) -> Track:
"""
Builds a track using a valid track identifier
You can also pass in a discord.py Context object to get a You can also pass in a discord.py Context object to get a
Context object on the track it builds. Context object on any track you search.
""" """
return await self._node.get_tracks(query, ctx=ctx, search_type=search_type)
return await self._node.build_track(identifier, ctx=ctx) async def connect(self, *, timeout: float, reconnect: bool):
await self.guild.change_voice_state(channel=self.channel)
async def get_recommendations(
self,
*,
track: Track,
ctx: Optional[commands.Context] = None,
) -> Optional[Union[List[Track], Playlist]]:
"""
Gets recommendations from either YouTube or Spotify.
You can pass in a discord.py Context object to get a
Context object on all tracks that get recommended.
"""
return await self._node.get_recommendations(track=track, ctx=ctx)
async def connect(
self,
*,
timeout: float,
reconnect: bool,
self_deaf: bool = False,
self_mute: bool = False,
) -> None:
await self.guild.change_voice_state(
channel=self.channel,
self_deaf=self_deaf,
self_mute=self_mute,
)
self._node._players[self.guild.id] = self self._node._players[self.guild.id] = self
self._is_connected = True self._is_connected = True
async def stop(self) -> None: async def stop(self):
"""Stops the currently playing track.""" """Stops the currently playing track."""
self._current = None self._current = None
await self._node.send( await self._node.send(op="stop", guildId=str(self.guild.id))
method="PATCH",
path=self._player_endpoint_uri,
guild_id=self._guild.id,
data={"encodedTrack": None},
)
if self._log: async def disconnect(self, *, force: bool = False):
self._log.debug(f"Player has been stopped.")
async def disconnect(self, *, force: bool = False) -> None:
"""Disconnects the player from voice.""" """Disconnects the player from voice."""
try: try:
await self.guild.change_voice_state(channel=None) await self.guild.change_voice_state(channel=None)
finally: finally:
self.cleanup() self.cleanup()
self._is_connected = False self._is_connected = False
self.channel = None # type: ignore self.channel = None
async def destroy(self) -> None: async def destroy(self):
"""Disconnects and destroys the player, and runs internal cleanup.""" """Disconnects and destroys the player, and runs internal cleanup."""
try: try:
await self.disconnect() await self.disconnect()
@ -483,16 +226,8 @@ class Player(VoiceProtocol):
# assume we're already disconnected and cleaned up # assume we're already disconnected and cleaned up
assert self.channel is None and not self.is_connected assert self.channel is None and not self.is_connected
self._node._players.pop(self.guild.id) self._node._players.pop(self._guild.id)
if self.node.is_connected: await self._node.send(op="destroy", guildId=str(self._guild.id))
await self._node.send(
method="DELETE",
path=self._player_endpoint_uri,
guild_id=self._guild.id,
)
if self._log:
self._log.debug("Player has been destroyed.")
async def play( async def play(
self, self,
@ -500,266 +235,67 @@ class Player(VoiceProtocol):
*, *,
start: int = 0, start: int = 0,
end: int = 0, end: int = 0,
ignore_if_playing: bool = False, ignore_if_playing: bool = False
) -> Track: ) -> Track:
"""Plays a track. If a Spotify track is passed in, it will be handled accordingly.""" """Plays a track. If a Spotify track is passed in, it will be handled accordingly."""
if track.spotify:
if not track._search_type: search: Track = (await self._node.get_tracks(
track.original = track f"{track._search_type}:{track.author} - {track.title}",
ctx=track.ctx
# Make sure we've never searched the track before ))[0]
if track._search_type and track.original is None:
# First lets try using the tracks ISRC, every track has one (hopefully)
try:
if not track.isrc:
# We have to bare raise here because theres no other way to skip this block feasibly
raise
search = (
await self._node.get_tracks(f"{track._search_type}:{track.isrc}", ctx=track.ctx)
)[
0
] # type: ignore
except Exception:
# First method didn't work, lets try just searching it up
try:
search = (
await self._node.get_tracks(
f"{track._search_type}:{track.title} - {track.author}",
ctx=track.ctx,
)
)[
0
] # type: ignore
except:
# The song wasn't able to be found, raise error
raise TrackLoadError(
"No equivalent track was able to be found.",
)
data = {
"encodedTrack": search.track_id,
"position": str(start),
"endTime": self._adjust_end_time(),
}
track.original = search track.original = search
track.track_id = search.track_id
# Set track_id for later lavalink searches data = {
"op": "play",
"guildId": str(self.guild.id),
"track": search.track_id,
"startTime": str(start),
"noReplace": ignore_if_playing
}
else: else:
data = { data = {
"encodedTrack": track.track_id, "op": "play",
"position": str(start), "guildId": str(self.guild.id),
"endTime": self._adjust_end_time(), "track": track.track_id,
"startTime": str(start),
"noReplace": ignore_if_playing
} }
# Lets set the current track before we play it so any
# corresponding events can capture it correctly
self._current = track
# Remove preloaded filters if last track had any
if self.filters.has_preload:
for filter in self.filters.get_preload_filters():
await self.remove_filter(filter_tag=filter.tag)
# Global filters take precedence over track filters
# So if no global filters are detected, lets apply any
# necessary track filters
# Check if theres no global filters and if the track has any filters
# that need to be applied
if track.filters and not self.filters.has_global:
# Now apply all filters
for filter in track.filters:
await self.add_filter(_filter=filter)
# Lavalink v3.7.5 changed the way the end time parameter works
# so now the end time cannot be zero.
# If it isnt zero, it'll be set to None.
# Otherwise, it'll be set here:
if end > 0: if end > 0:
data["endTime"] = str(end) data["endTime"] = str(end)
await self._node.send( await self._node.send(**data)
method="PATCH",
path=self._player_endpoint_uri,
guild_id=self._guild.id,
data=data,
query=f"noReplace={ignore_if_playing}",
)
if self._log:
self._log.debug(
f"Playing {track.title} from uri {track.uri} with a length of {track.length}",
)
self._current = track
return self._current return self._current
async def seek(self, position: float) -> float: async def seek(self, position: float) -> float:
"""Seeks to a position in the currently playing track milliseconds""" """Seeks to a position in the currently playing track milliseconds"""
if not self._current or not self._current.original: if position < 0 or position > self.current.length:
return 0.0
if position < 0 or position > self._current.original.length:
raise TrackInvalidPosition( raise TrackInvalidPosition(
"Seek position must be between 0 and the track length", f"Seek position must be between 0 and the track length"
) )
await self._node.send( await self._node.send(op="seek", guildId=str(self.guild.id), position=position)
method="PATCH", return self._position
path=self._player_endpoint_uri,
guild_id=self._guild.id,
data={"position": position},
)
if self._log:
self._log.debug(f"Seeking to {position}.")
return self.position
async def set_pause(self, pause: bool) -> bool: async def set_pause(self, pause: bool) -> bool:
"""Sets the pause state of the currently playing track.""" """Sets the pause state of the currently playing track."""
await self._node.send( await self._node.send(op="pause", guildId=str(self.guild.id), pause=pause)
method="PATCH",
path=self._player_endpoint_uri,
guild_id=self._guild.id,
data={"paused": pause},
)
self._paused = pause self._paused = pause
if self._log:
self._log.debug(f"Player has been {'paused' if pause else 'resumed'}.")
return self._paused return self._paused
async def set_volume(self, volume: int) -> int: async def set_volume(self, volume: int) -> int:
"""Sets the volume of the player as an integer. Lavalink accepts values from 0 to 500.""" """Sets the volume of the player as an integer. Lavalink accepts values from 0 to 500."""
await self._node.send( await self._node.send(op="volume", guildId=str(self.guild.id), volume=volume)
method="PATCH",
path=self._player_endpoint_uri,
guild_id=self._guild.id,
data={"volume": volume},
)
self._volume = volume self._volume = volume
if self._log:
self._log.debug(f"Player volume has been adjusted to {volume}")
return self._volume return self._volume
async def move_to(self, channel: VoiceChannel) -> None: async def set_filter(self, filter: Filter) -> Filter:
"""Moves the player to a new voice channel.""" """Sets a filter of the player. Takes a pomice.Filter object.
This will only work if you are using the development version of Lavalink.
await self.guild.change_voice_state(channel=channel)
self.channel = channel
await self._dispatch_voice_update()
async def add_filter(self, _filter: Filter, fast_apply: bool = False) -> Filters:
"""Adds a filter to the player. Takes a pomice.Filter object.
This will only work if you are using a version of Lavalink that supports filters.
If you would like for the filter to apply instantly, set the `fast_apply` arg to `True`.
(You must have a song playing in order for `fast_apply` to work.)
""" """
await self._node.send(op="filters", guildId=str(self.guild.id), **filter.payload)
self._filters.add_filter(filter=_filter) await self.seek(self.position)
payload = self._filters.get_all_payloads() self._filter = filter
await self._node.send( return filter
method="PATCH",
path=self._player_endpoint_uri,
guild_id=self._guild.id,
data={"filters": payload},
)
if self._log:
self._log.debug(f"Filter has been applied to player with tag {_filter.tag}")
if fast_apply:
if self._log:
self._log.debug(f"Fast apply passed, now applying filter instantly.")
await self.seek(self.position)
return self._filters
async def remove_filter(self, filter_tag: str, fast_apply: bool = False) -> Filters:
"""Removes a filter from the player. Takes a filter tag.
This will only work if you are using a version of Lavalink that supports filters.
If you would like for the filter to apply instantly, set the `fast_apply` arg to `True`.
(You must have a song playing in order for `fast_apply` to work.)
"""
self._filters.remove_filter(filter_tag=filter_tag)
payload = self._filters.get_all_payloads()
await self._node.send(
method="PATCH",
path=self._player_endpoint_uri,
guild_id=self._guild.id,
data={"filters": payload},
)
if self._log:
self._log.debug(f"Filter has been removed from player with tag {filter_tag}")
if fast_apply:
if self._log:
self._log.debug(f"Fast apply passed, now removing filter instantly.")
await self.seek(self.position)
return self._filters
async def edit_filter(
self,
*,
filter_tag: str,
edited_filter: Filter,
fast_apply: bool = False,
) -> Filters:
"""Edits a filter from the player using its filter tag and a new filter of the same type.
The filter to be replaced must have the same tag as the one you are replacing it with.
This will only work if you are using a version of Lavalink that supports filters.
If you would like for the filter to apply instantly, set the `fast_apply` arg to `True`.
(You must have a song playing in order for `fast_apply` to work.)
"""
self._filters.edit_filter(filter_tag=filter_tag, to_apply=edited_filter)
payload = self._filters.get_all_payloads()
await self._node.send(
method="PATCH",
path=self._player_endpoint_uri,
guild_id=self._guild.id,
data={"filters": payload},
)
if self._log:
self._log.debug(f"Filter with tag {filter_tag} has been edited to {edited_filter!r}")
if fast_apply:
if self._log:
self._log.debug(f"Fast apply passed, now editing filter instantly.")
await self.seek(self.position)
return self._filters
async def reset_filters(self, *, fast_apply: bool = False) -> None:
"""Resets all currently applied filters to their default parameters.
You must have filters applied in order for this to work.
If you would like the filters to be removed instantly, set the `fast_apply` arg to `True`.
(You must have a song playing in order for `fast_apply` to work.)
"""
if not self._filters:
raise FilterInvalidArgument(
"You must have filters applied first in order to use this method.",
)
self._filters.reset_filters()
await self._node.send(
method="PATCH",
path=self._player_endpoint_uri,
guild_id=self._guild.id,
data={"filters": {}},
)
if self._log:
self._log.debug(f"All filters have been removed from player.")
if fast_apply:
if self._log:
self._log.debug(f"Fast apply passed, now removing all filters instantly.")
await self.seek(self.position)

File diff suppressed because it is too large Load Diff

View File

View File

@ -1,374 +0,0 @@
from __future__ import annotations
import random
from copy import copy
from typing import Iterable
from typing import Iterator
from typing import List
from typing import Optional
from typing import Union
from .enums import LoopMode
from .exceptions import QueueEmpty
from .exceptions import QueueException
from .exceptions import QueueFull
from .objects import Track
__all__ = ("Queue",)
class Queue(Iterable[Track]):
"""Queue for Pomice. This queue takes pomice.Track as an input and includes looping and shuffling."""
__slots__ = (
"max_size",
"_queue",
"_overflow",
"_loop_mode",
"_current_item",
)
def __init__(
self,
max_size: Optional[int] = None,
*,
overflow: bool = True,
):
self.max_size: Optional[int] = max_size
self._current_item: Track
self._queue: List[Track] = []
self._overflow: bool = overflow
self._loop_mode: Optional[LoopMode] = None
def __str__(self) -> str:
"""String showing all Track objects appearing as a list."""
return str(list(f"'{t}'" for t in self))
def __repr__(self) -> str:
"""Official representation with max_size and member count."""
return f"<{self.__class__.__name__} max_size={self.max_size} members={self.count}>"
def __bool__(self) -> bool:
"""Treats the queue as a bool, with it evaluating True when it contains members."""
return bool(self.count)
def __call__(self, item: Track) -> None:
"""Allows the queue instance to be called directly in order to add a member."""
self.put(item)
def __len__(self) -> int:
"""Return the number of members in the queue."""
return self.count
def __getitem__(self, index: int) -> Track:
"""Returns a member at the given position.
Does not remove item from queue.
"""
if not isinstance(index, int):
raise ValueError("'int' type required.'")
return self._queue[index]
def __setitem__(self, index: int, item: Track) -> None:
"""Inserts an item at given position."""
if not isinstance(index, int):
raise ValueError("'int' type required.'")
self.put_at_index(index, item)
def __delitem__(self, index: int) -> None:
"""Delete item at given position."""
self._queue.__delitem__(index)
def __iter__(self) -> Iterator[Track]:
"""Iterate over members in the queue.
Does not remove items when iterating.
"""
return self._queue.__iter__()
def __reversed__(self) -> Iterator[Track]:
"""Iterate over members in reverse order."""
return self._queue.__reversed__()
def __contains__(self, item: Track) -> bool:
"""Check if an item is a member of the queue."""
return item in self._queue
def __add__(self, other: Iterable[Track]) -> Queue:
"""Return a new queue containing all members.
The new queue will have the same max_size as the original.
"""
if not isinstance(other, Iterable):
raise TypeError(
f"Adding with the '{type(other)}' type is not supported.",
)
new_queue = self.copy()
new_queue.extend(other)
return new_queue
def __iadd__(self, other: Union[Iterable[Track], Track]) -> Queue:
"""Add items to queue."""
if isinstance(other, Track):
self.put(other)
return self
if isinstance(other, Iterable):
self.extend(other)
return self
raise TypeError(
f"Adding '{type(other)}' type to the queue is not supported.",
)
def _get(self) -> Track:
return self._queue.pop(0)
def _drop(self) -> Track:
return self._queue.pop()
def _index(self, item: Track) -> int:
return self._queue.index(item)
def _put(self, item: Track) -> None:
self._queue.append(item)
def _insert(self, index: int, item: Track) -> None:
self._queue.insert(index, item)
def _remove(self, item: Track) -> None:
self._queue.remove(item)
def _get_random_float(self) -> float:
return random.random()
@staticmethod
def _check_track(item: Track) -> Track:
if not isinstance(item, Track):
raise TypeError("Only pomice.Track objects are supported.")
return item
@classmethod
def _check_track_container(cls, iterable: Iterable) -> List[Track]:
iterable = list(iterable)
for item in iterable:
cls._check_track(item)
return iterable
@property
def count(self) -> int:
"""Returns queue member count."""
return len(self._queue)
@property
def is_empty(self) -> bool:
"""Returns True if queue has no members."""
return not bool(self.count)
@property
def is_full(self) -> bool:
"""Returns True if queue item count has reached max_size."""
return False if self.max_size is None else self.count >= self.max_size
@property
def is_looping(self) -> bool:
"""Returns True if the queue is looping either a track or the queue"""
return bool(self._loop_mode)
@property
def loop_mode(self) -> Optional[LoopMode]:
"""Returns the LoopMode enum set in the queue object"""
return self._loop_mode
@property
def size(self) -> int:
"""Returns the amount of items in the queue"""
return len(self._queue)
def get_queue(self) -> List:
"""Returns the queue as a List"""
return self._queue
def get(self) -> Track:
"""Return next immediately available item in queue if any.
Raises QueueEmpty if no items in queue.
"""
if self._loop_mode == LoopMode.TRACK:
return self._current_item
if self.is_empty:
raise QueueEmpty("No items in the queue.")
if self._loop_mode == LoopMode.QUEUE:
# set current item to first track in queue if not set already
# otherwise exception will be raised
if not self._current_item or self._current_item not in self._queue:
if self._queue:
item = self._queue[0]
else:
raise QueueEmpty("No items in the queue.")
# set current item to first track in queue if not set already
if not self._current_item:
self._current_item = self._queue[0]
item = self._current_item
# we reached the end of the queue, go back to first track
if self._index(self._current_item) == len(self._queue) - 1:
item = self._queue[0]
# we are in the middle of the queue, go the next item
else:
index = self._index(self._current_item) + 1
item = self._queue[index]
else:
item = self._get()
self._current_item = item
return item
def pop(self) -> Track:
"""Return item from the right end side of the queue.
Raises QueueEmpty if no items in queue.
"""
if self.is_empty:
raise QueueEmpty("No items in the queue.")
return self._queue.pop()
def remove(self, item: Track) -> None:
"""
Removes a item within the queue.
Raises ValueError if item is not in queue.
"""
return self._remove(self._check_track(item))
def find_position(self, item: Track) -> int:
"""Find the position a given item within the queue.
Raises ValueError if item is not in queue.
"""
return self._index(self._check_track(item))
def put(self, item: Track) -> None:
"""Put the given item into the back of the queue."""
if self.is_full:
if not self._overflow:
raise QueueFull(
f"Queue max_size of {self.max_size} has been reached.",
)
self._drop()
return self._put(self._check_track(item))
def put_at_index(self, index: int, item: Track) -> None:
"""Put the given item into the queue at the specified index."""
if self.is_full:
if not self._overflow:
raise QueueFull(
f"Queue max_size of {self.max_size} has been reached.",
)
self._drop()
return self._insert(index, self._check_track(item))
def put_at_front(self, item: Track) -> None:
"""Put the given item into the front of the queue."""
return self.put_at_index(0, item)
def extend(self, iterable: Iterable[Track], *, atomic: bool = True) -> None:
"""
Add the members of the given iterable to the end of the queue.
If atomic is set to True, no tracks will be added upon any exceptions.
If atomic is set to False, as many tracks will be added as possible.
When overflow is enabled for the queue, `atomic=True` won't prevent dropped items.
"""
if atomic:
iterable = self._check_track_container(iterable)
if not self._overflow and self.max_size is not None:
new_len = len(iterable)
if (new_len + self.count) > self.max_size:
raise QueueFull(
f"Queue has {self.count}/{self.max_size} items, "
f"cannot add {new_len} more.",
)
for item in iterable:
self.put(item)
def copy(self) -> Queue:
"""Create a copy of the current queue including it's members."""
new_queue = self.__class__(max_size=self.max_size)
new_queue._queue = copy(self._queue)
return new_queue
def clear(self) -> None:
"""Remove all items from the queue."""
self._queue.clear()
def set_loop_mode(self, mode: LoopMode) -> None:
"""
Sets the loop mode of the queue.
Takes the LoopMode enum as an argument.
"""
self._loop_mode = mode
if self._loop_mode == LoopMode.QUEUE:
try:
index = self._index(self._current_item)
except ValueError:
index = 0
if self._current_item not in self._queue:
self._queue.insert(index, self._current_item)
self._current_item = self._queue[index]
def disable_loop(self) -> None:
"""
Disables loop mode if set.
Raises QueueException if loop mode is already None.
"""
if not self._loop_mode:
raise QueueException("Queue loop is already disabled.")
if self._loop_mode == LoopMode.QUEUE:
index = self.find_position(self._current_item) + 1
self._queue = self._queue[index:]
self._loop_mode = None
def shuffle(self) -> None:
"""Shuffles the queue."""
return random.shuffle(self._queue)
def clear_track_filters(self) -> None:
"""Clears all filters applied to tracks"""
for track in self._queue:
track.filters = None
def jump(self, item: Track) -> None:
"""
Jumps to the item specified in the queue.
If the queue is not looping, the queue will be mutated.
Otherwise, the current item will be adjusted to the item
before the specified track.
The queue is adjusted so that the next item that is retrieved
is the track that is specified, effectively 'jumping' the queue.
"""
if self._loop_mode == LoopMode.TRACK:
raise QueueException("Jumping the queue whilst looping a track is not allowed.")
index = self.find_position(item)
if self._loop_mode == LoopMode.QUEUE:
self._current_item = self._queue[index - 1]
else:
new_queue = self._queue[index : self.size]
self._queue = new_queue

View File

@ -1,33 +0,0 @@
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .pool import Node
from .utils import RouteStats
__all__ = ("RoutePlanner",)
class RoutePlanner:
"""
The base route planner class for Pomice.
Handles all requests made to the route planner API for Lavalink.
"""
def __init__(self, node: Node) -> None:
self.node: Node = node
async def get_status(self) -> RouteStats:
"""Gets the status of the route planner API."""
data: dict = await self.node.send(method="GET", path="routeplanner/status")
return RouteStats(data)
async def free_address(self, ip: str) -> None:
"""Frees an address using the route planner API"""
await self.node.send(method="POST", path="routeplanner/free/address", data={"address": ip})
async def free_all_addresses(self) -> None:
"""Frees all available addresses using the route planner api"""
await self.node.send(method="POST", path="routeplanner/free/address/all")

View File

@ -1,4 +1,7 @@
"""Spotify module for Pomice, made possible by cloudwithax 2023""" """Spotify module for Pomice, made possible by cloudwithax 2021"""
from .exceptions import InvalidSpotifyURL, SpotifyRequestException
from .track import Track
from .playlist import Playlist
from .album import Album
from .client import Client from .client import Client
from .exceptions import *
from .objects import *

20
pomice/spotify/album.py Normal file
View File

@ -0,0 +1,20 @@
from .track import Track
class Album:
"""The base class for a Spotify album"""
def __init__(self, data: dict) -> None:
self.name = data["name"]
self.artists = ", ".join(artist["name"] for artist in data["artists"])
self.tracks = [Track(track) for track in data["tracks"]["items"]]
self.total_tracks = data["total_tracks"]
self.id = data["id"]
self.image = data["images"][0]["url"]
self.uri = data["external_urls"]["spotify"]
def __repr__(self) -> str:
return (
f"<Pomice.spotify.Album name={self.name} artists={self.artists} id={self.id} "
f"total_tracks={self.total_tracks} tracks={self.tracks}>"
)

View File

@ -1,360 +1,93 @@
from __future__ import annotations
import asyncio
import logging
import re import re
import time import time
from base64 import b64encode from base64 import b64encode
from typing import AsyncGenerator
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
from urllib.parse import quote
import aiohttp import aiohttp
import orjson as json
from .exceptions import InvalidSpotifyURL
from .exceptions import SpotifyRequestException
from .objects import *
__all__ = ("Client",)
from .album import Album
from .exceptions import InvalidSpotifyURL, SpotifyRequestException
from .playlist import Playlist
from .track import Track
GRANT_URL = "https://accounts.spotify.com/api/token" GRANT_URL = "https://accounts.spotify.com/api/token"
REQUEST_URL = "https://api.spotify.com/v1/{type}s/{id}" REQUEST_URL = "https://api.spotify.com/v1/{type}s/{id}"
# Keep this in sync with URLRegex.SPOTIFY_URL (enums.py). Accept intl locale segment,
# optional trailing slash, and query parameters.
SPOTIFY_URL_REGEX = re.compile( SPOTIFY_URL_REGEX = re.compile(
r"https?://open\.spotify\.com/(?:intl-[a-zA-Z-]+/)?(?P<type>album|playlist|track|artist)/(?P<id>[a-zA-Z0-9]+)(?:/)?(?:\?.*)?$", r"https?://open.spotify.com/(?P<type>album|playlist|track)/(?P<id>[a-zA-Z0-9]+)"
) )
class Client: class Client:
"""The base client for the Spotify module of Pomice. """The base client for the Spotify module of Pomice.
This class will do all the heavy lifting of getting all the metadata This class will do all the heavy lifting of getting all the metadata
for any Spotify URL you throw at it. for any Spotify URL you throw at it.
""" """
def __init__( def __init__(self, client_id: str, client_secret: str) -> None:
self,
client_id: str,
client_secret: str,
*,
playlist_concurrency: int = 10,
playlist_page_limit: Optional[int] = None,
) -> None:
self._client_id = client_id self._client_id = client_id
self._client_secret = client_secret self._client_secret = client_secret
# HTTP session will be injected by Node self.session = aiohttp.ClientSession()
self.session: Optional[aiohttp.ClientSession] = None
self._bearer_token: Optional[str] = None self._bearer_token: str = None
self._expiry: float = 0.0 self._expiry = 0
self._auth_token = b64encode(f"{self._client_id}:{self._client_secret}".encode()) self._auth_token = b64encode(f"{self._client_id}:{self._client_secret}".encode())
self._grant_headers = {"Authorization": f"Basic {self._auth_token.decode()}"} self._grant_headers = {"Authorization": f"Basic {self._auth_token.decode()}"}
self._bearer_headers: Optional[Dict] = None self._bearer_headers = None
self._log = logging.getLogger(__name__)
# Performance tuning knobs
self._playlist_concurrency = max(1, playlist_concurrency)
self._playlist_page_limit = playlist_page_limit
async def _set_session(self, session: aiohttp.ClientSession) -> None:
self.session = session
async def _fetch_bearer_token(self) -> None: async def _fetch_bearer_token(self) -> None:
_data = {"grant_type": "client_credentials"} _data = {"grant_type": "client_credentials"}
if not self.session: async with self.session.post(GRANT_URL, data=_data, headers=self._grant_headers) as resp:
raise SpotifyRequestException("HTTP session not initialized for Spotify client.") if resp.status != 200:
resp = await self.session.post(GRANT_URL, data=_data, headers=self._grant_headers) raise SpotifyRequestException(
f"Error fetching bearer token: {resp.status} {resp.reason}"
)
if resp.status != 200: data: dict = await resp.json()
raise SpotifyRequestException(
f"Error fetching bearer token: {resp.status} {resp.reason}",
)
data: dict = await resp.json(loads=json.loads)
if self._log:
self._log.debug(f"Fetched Spotify bearer token successfully")
self._bearer_token = data["access_token"] self._bearer_token = data["access_token"]
self._expiry = time.time() + (int(data["expires_in"]) - 10) self._expiry = time.time() + (int(data["expires_in"]) - 10)
self._bearer_headers = { self._bearer_headers = {"Authorization": f"Bearer {self._bearer_token}"}
"Authorization": f"Bearer {self._bearer_token}",
}
async def search(self, *, query: str) -> Union[Track, Album, Artist, Playlist]: async def search(self, *, query: str):
if not self._bearer_token or time.time() >= self._expiry: if not self._bearer_token or time.time() >= self._expiry:
await self._fetch_bearer_token() await self._fetch_bearer_token()
result = SPOTIFY_URL_REGEX.match(query) result = SPOTIFY_URL_REGEX.match(query)
if not result:
raise InvalidSpotifyURL("The Spotify link provided is not valid.")
spotify_type = result.group("type") spotify_type = result.group("type")
spotify_id = result.group("id") spotify_id = result.group("id")
if not result:
return InvalidSpotifyURL("The Spotify link provided is not valid.")
request_url = REQUEST_URL.format(type=spotify_type, id=spotify_id) request_url = REQUEST_URL.format(type=spotify_type, id=spotify_id)
if not self.session: async with self.session.get(request_url, headers=self._bearer_headers) as resp:
raise SpotifyRequestException("HTTP session not initialized for Spotify client.") if resp.status != 200:
resp = await self.session.get(request_url, headers=self._bearer_headers) raise SpotifyRequestException(
if resp.status != 200: f"Error while fetching results: {resp.status} {resp.reason}"
raise SpotifyRequestException( )
f"Error while fetching results: {resp.status} {resp.reason}",
)
data: dict = await resp.json(loads=json.loads) data: dict = await resp.json()
if self._log:
self._log.debug(
f"Made request to Spotify API with status {resp.status} and response {data}",
)
if spotify_type == "track": if spotify_type == "track":
return Track(data) return Track(data)
elif spotify_type == "album": elif spotify_type == "album":
return Album(data) return Album(data)
elif spotify_type == "artist":
if not self.session:
raise SpotifyRequestException("HTTP session not initialized for Spotify client.")
resp = await self.session.get(
f"{request_url}/top-tracks?market=US",
headers=self._bearer_headers,
)
if resp.status != 200:
raise SpotifyRequestException(
f"Error while fetching results: {resp.status} {resp.reason}",
)
track_data: dict = await resp.json(loads=json.loads)
tracks = track_data["tracks"]
return Artist(data, tracks)
else: else:
# For playlists we optionally use a reduced fields payload to shrink response sizes. tracks = [Track(track["track"]) for track in data["tracks"]["items"]]
# NB: We cannot apply fields filter to initial request because original metadata is needed. next_page_url = data["tracks"]["next"]
tracks = [
Track(track["track"])
for track in data["tracks"]["items"]
if track["track"] is not None
]
if not tracks: while next_page_url is not None:
raise SpotifyRequestException( async with self.session.get(next_page_url, headers=self._bearer_headers) as resp:
"This playlist is empty and therefore cannot be queued.", if resp.status != 200:
) raise SpotifyRequestException(
f"Error while fetching results: {resp.status} {resp.reason}"
)
total_tracks = data["tracks"]["total"] next_data: dict = await resp.json()
limit = data["tracks"]["limit"]
# Shortcircuit small playlists (single page) tracks += [Track(track["track"]) for track in next_data["items"]]
if total_tracks <= limit: next_page_url = next_data["next"]
return Playlist(data, tracks)
# Build remaining page URLs; Spotify supports offset-based pagination.
remaining_offsets = range(limit, total_tracks, limit)
page_urls: List[str] = []
fields_filter = (
"items(track(name,duration_ms,id,is_local,external_urls,external_ids,artists(name),album(images)))"
",next"
)
for idx, offset in enumerate(remaining_offsets):
if self._playlist_page_limit is not None and idx >= self._playlist_page_limit:
break
page_urls.append(
f"{request_url}/tracks?offset={offset}&limit={limit}&fields={quote(fields_filter)}",
)
if page_urls:
semaphore = asyncio.Semaphore(self._playlist_concurrency)
async def fetch_page(url: str) -> Optional[List[Track]]:
async with semaphore:
if not self.session:
raise SpotifyRequestException(
"HTTP session not initialized for Spotify client.",
)
resp = await self.session.get(url, headers=self._bearer_headers)
if resp.status != 200:
if self._log:
self._log.warning(
f"Page fetch failed {resp.status} {resp.reason} for {url}",
)
return None
page_json: dict = await resp.json(loads=json.loads)
return [
Track(item["track"])
for item in page_json.get("items", [])
if item.get("track") is not None
]
# Chunk gather in waves to avoid creating thousands of tasks at once
aggregated: List[Track] = []
wave_size = self._playlist_concurrency * 2
for i in range(0, len(page_urls), wave_size):
wave = page_urls[i : i + wave_size]
results = await asyncio.gather(
*[fetch_page(url) for url in wave],
return_exceptions=False,
)
for result in results:
if result:
aggregated.extend(result)
tracks.extend(aggregated)
return Playlist(data, tracks) return Playlist(data, tracks)
async def iter_playlist_tracks(
self,
*,
query: str,
batch_size: int = 100,
) -> AsyncGenerator[List[Track], None]:
"""Stream playlist tracks in batches without waiting for full materialization.
Parameters
----------
query: str
Spotify playlist URL.
batch_size: int
Number of tracks yielded per batch (logical grouping after fetch). Does not alter API page size.
"""
if not self._bearer_token or time.time() >= self._expiry:
await self._fetch_bearer_token()
match = SPOTIFY_URL_REGEX.match(query)
if not match or match.group("type") != "playlist":
raise InvalidSpotifyURL("Provided query is not a valid Spotify playlist URL.")
playlist_id = match.group("id")
request_url = REQUEST_URL.format(type="playlist", id=playlist_id)
if not self.session:
raise SpotifyRequestException("HTTP session not initialized for Spotify client.")
resp = await self.session.get(request_url, headers=self._bearer_headers)
if resp.status != 200:
raise SpotifyRequestException(
f"Error while fetching results: {resp.status} {resp.reason}",
)
data: dict = await resp.json(loads=json.loads)
# Yield first page immediately
first_page_tracks = [
Track(item["track"])
for item in data["tracks"]["items"]
if item.get("track") is not None
]
# Batch yield
for i in range(0, len(first_page_tracks), batch_size):
yield first_page_tracks[i : i + batch_size]
total = data["tracks"]["total"]
limit = data["tracks"]["limit"]
remaining_offsets = range(limit, total, limit)
fields_filter = (
"items(track(name,duration_ms,id,is_local,external_urls,external_ids,artists(name),album(images)))"
",next"
)
semaphore = asyncio.Semaphore(self._playlist_concurrency)
async def fetch(offset: int) -> List[Track]:
url = (
f"{request_url}/tracks?offset={offset}&limit={limit}&fields={quote(fields_filter)}"
)
async with semaphore:
if not self.session:
raise SpotifyRequestException(
"HTTP session not initialized for Spotify client.",
)
r = await self.session.get(url, headers=self._bearer_headers)
if r.status != 200:
if self._log:
self._log.warning(
f"Skipping page offset={offset} due to {r.status} {r.reason}",
)
return []
pj: dict = await r.json(loads=json.loads)
return [
Track(item["track"])
for item in pj.get("items", [])
if item.get("track") is not None
]
# Fetch pages in rolling waves; yield promptly as soon as a wave completes.
wave_size = self._playlist_concurrency * 2
for i, offset in enumerate(remaining_offsets):
# Build wave
if i % wave_size == 0:
wave_offsets = list(
o for o in remaining_offsets if o >= offset and o < offset + wave_size
)
results = await asyncio.gather(*[fetch(o) for o in wave_offsets])
for page_tracks in results:
if not page_tracks:
continue
for j in range(0, len(page_tracks), batch_size):
yield page_tracks[j : j + batch_size]
# Skip ahead in iterator by adjusting enumerate drive (consume extras)
# Fast-forward the generator manually
for _ in range(len(wave_offsets) - 1):
try:
next(remaining_offsets) # type: ignore
except StopIteration:
break
async def get_recommendations(self, *, query: str) -> List[Track]:
if not self._bearer_token or time.time() >= self._expiry:
await self._fetch_bearer_token()
result = SPOTIFY_URL_REGEX.match(query)
if not result:
raise InvalidSpotifyURL("The Spotify link provided is not valid.")
spotify_type = result.group("type")
spotify_id = result.group("id")
if not spotify_type == "track":
raise InvalidSpotifyURL(
"The provided query is not a Spotify track.",
)
request_url = REQUEST_URL.format(
type="recommendation",
id=f"?seed_tracks={spotify_id}",
)
if not self.session:
raise SpotifyRequestException("HTTP session not initialized for Spotify client.")
resp = await self.session.get(request_url, headers=self._bearer_headers)
if resp.status != 200:
raise SpotifyRequestException(
f"Error while fetching results: {resp.status} {resp.reason}",
)
data: dict = await resp.json(loads=json.loads)
tracks = [Track(track) for track in data["tracks"]]
return tracks
async def track_search(self, *, query: str) -> List[Track]:
if not self._bearer_token or time.time() >= self._expiry:
await self._fetch_bearer_token()
request_url = f"https://api.spotify.com/v1/search?q={quote(query)}&type=track"
if not self.session:
raise SpotifyRequestException("HTTP session not initialized for Spotify client.")
resp = await self.session.get(request_url, headers=self._bearer_headers)
if resp.status != 200:
raise SpotifyRequestException(
f"Error while fetching results: {resp.status} {resp.reason}",
)
data: dict = await resp.json(loads=json.loads)
tracks = [Track(track) for track in data["tracks"]["items"]]
return tracks

View File

@ -1,16 +1,8 @@
__all__ = (
"SpotifyRequestException",
"InvalidSpotifyURL",
)
class SpotifyRequestException(Exception): class SpotifyRequestException(Exception):
"""An error occurred when making a request to the Spotify API""" """An error occurred when making a request to the Spotify API"""
pass pass
class InvalidSpotifyURL(Exception): class InvalidSpotifyURL(Exception):
"""An invalid Spotify URL was passed""" """An invalid Spotify URL was passed"""
pass pass

View File

@ -1,97 +0,0 @@
from typing import List
from typing import Optional
__all__ = (
"Track",
"Playlist",
"Album",
"Artist",
)
class Track:
"""The base class for a Spotify Track"""
def __init__(self, data: dict, image: Optional[str] = None) -> None:
self.name: str = data["name"]
self.artists: str = ", ".join(artist["name"] for artist in data["artists"])
self.length: float = data["duration_ms"]
self.id: str = data["id"]
self.isrc: Optional[str] = None
if data.get("external_ids"):
self.isrc = data["external_ids"]["isrc"]
self.image: Optional[str] = image
if data.get("album") and data["album"].get("images"):
self.image = data["album"]["images"][0]["url"]
self.uri: Optional[str] = None
if not data["is_local"]:
self.uri = data["external_urls"]["spotify"]
def __repr__(self) -> str:
return (
f"<Pomice.spotify.Track name={self.name} artists={self.artists} "
f"length={self.length} id={self.id} isrc={self.isrc}>"
)
class Playlist:
"""The base class for a Spotify playlist"""
def __init__(self, data: dict, tracks: List[Track]) -> None:
self.name: str = data["name"]
self.tracks = tracks
self.owner: str = data["owner"]["display_name"]
self.total_tracks: int = data["tracks"]["total"]
self.id: str = data["id"]
if data.get("images") and len(data["images"]):
self.image = data["images"][0]["url"]
else:
self.image = self.tracks[0].image
self.uri = data["external_urls"]["spotify"]
def __repr__(self) -> str:
return (
f"<Pomice.spotify.Playlist name={self.name} owner={self.owner} id={self.id} "
f"total_tracks={self.total_tracks} tracks={self.tracks}>"
)
class Album:
"""The base class for a Spotify album"""
def __init__(self, data: dict) -> None:
self.name: str = data["name"]
self.artists: str = ", ".join(artist["name"] for artist in data["artists"])
self.image: str = data["images"][0]["url"]
self.tracks = [Track(track, image=self.image) for track in data["tracks"]["items"]]
self.total_tracks: int = data["total_tracks"]
self.id: str = data["id"]
self.uri: str = data["external_urls"]["spotify"]
def __repr__(self) -> str:
return (
f"<Pomice.spotify.Album name={self.name} artists={self.artists} id={self.id} "
f"total_tracks={self.total_tracks} tracks={self.tracks}>"
)
class Artist:
"""The base class for a Spotify artist"""
def __init__(self, data: dict, tracks: dict) -> None:
self.name: str = (
# Setting that because its only playing top tracks
f"Top tracks for {data['name']}"
)
self.genres: str = ", ".join(genre for genre in data["genres"])
self.followers: int = data["followers"]["total"]
self.image: str = data["images"][0]["url"]
self.tracks = [Track(track, image=self.image) for track in tracks]
self.id: str = data["id"]
self.uri: str = data["external_urls"]["spotify"]
def __repr__(self) -> str:
return f"<Pomice.spotify.Artist name={self.name} id={self.id} " f"tracks={self.tracks}>"

View File

@ -0,0 +1,21 @@
from .track import Track
from typing import List
class Playlist:
"""The base class for a Spotify playlist"""
def __init__(self, data: dict, tracks: List[Track]) -> None:
self.name = data["name"]
self.tracks = tracks
self.owner = data["owner"]["display_name"]
self.total_tracks = data["tracks"]["total"]
self.id = data["id"]
self.image = data["images"][0]["url"]
self.uri = data["external_urls"]["spotify"]
def __repr__(self) -> str:
return (
f"<Pomice.spotify.Playlist name={self.name} owner={self.owner} id={self.id} "
f"total_tracks={self.total_tracks} tracks={self.tracks}>"
)

21
pomice/spotify/track.py Normal file
View File

@ -0,0 +1,21 @@
class Track:
"""The base class for a Spotify Track"""
def __init__(self, data: dict) -> None:
self.name = data["name"]
self.artists = ", ".join(artist["name"] for artist in data["artists"])
self.length = data["duration_ms"]
self.id = data["id"]
if data.get("album") and data["album"]["images"]:
self.image = data["album"]["images"][0]["url"]
else:
self.image = None
self.uri = data["external_urls"]["spotify"]
def __repr__(self) -> str:
return (
f"<Pomice.spotify.Track name={self.name} artists={self.artists} "
f"length={self.length} id={self.id}>"
)

View File

@ -1,56 +1,48 @@
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
import random import random
import socket
import time import time
from datetime import datetime from typing import Union
from itertools import zip_longest
from timeit import default_timer as timer
from typing import Any
from typing import Callable
from typing import Dict
from typing import Iterable
from typing import NamedTuple
from typing import Optional
from .enums import RouteIPType from discord import AutoShardedClient, Client
from .enums import RouteStrategy from discord.ext.commands import AutoShardedBot, Bot
__all__ = ( __all__ = [
"ClientType",
"ExponentialBackoff", "ExponentialBackoff",
"NodeStats", "NodeStats"
"FailingIPBlock", ]
"RouteStats",
"Ping", ClientType = Union[AutoShardedBot, AutoShardedClient, Bot, Client]
"LavalinkVersion",
)
class ExponentialBackoff: class ExponentialBackoff:
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
def __init__(self, base: int = 1, *, integral: bool = False) -> None: def __init__(self, base: int = 1, *, integral: bool = False) -> None:
self._base = base self._base = base
self._exp = 0 self._exp = 0
self._max = 10 self._max = 10
self._reset_time = base * 2**11 self._reset_time = base * 2 ** 11
self._last_invocation = time.monotonic() self._last_invocation = time.monotonic()
rand = random.Random() rand = random.Random()
@ -59,6 +51,7 @@ class ExponentialBackoff:
self._randfunc = rand.randrange if integral else rand.uniform self._randfunc = rand.randrange if integral else rand.uniform
def delay(self) -> float: def delay(self) -> float:
invocation = time.monotonic() invocation = time.monotonic()
interval = invocation - self._last_invocation interval = invocation - self._last_invocation
self._last_invocation = invocation self._last_invocation = invocation
@ -67,35 +60,23 @@ class ExponentialBackoff:
self._exp = 0 self._exp = 0
self._exp = min(self._exp + 1, self._max) self._exp = min(self._exp + 1, self._max)
return self._randfunc(0, self._base * 2**self._exp) # type: ignore return self._randfunc(0, self._base * 2 ** self._exp)
class NodeStats: class NodeStats:
"""The base class for the node stats object. """The base class for the node stats object.
Gives critical information on the node, which is updated every minute. Gives critical information on the node, which is updated every minute.
""" """
__slots__ = ( def __init__(self, data: dict) -> None:
"used",
"free",
"reservable",
"allocated",
"cpu_cores",
"cpu_system_load",
"cpu_process_load",
"players_active",
"players_total",
"uptime",
)
def __init__(self, data: Dict[str, Any]) -> None: memory = data.get("memory")
memory: dict = data.get("memory", {})
self.used = memory.get("used") self.used = memory.get("used")
self.free = memory.get("free") self.free = memory.get("free")
self.reservable = memory.get("reservable") self.reservable = memory.get("reservable")
self.allocated = memory.get("allocated") self.allocated = memory.get("allocated")
cpu: dict = data.get("cpu", {}) cpu = data.get("cpu")
self.cpu_cores = cpu.get("cores") self.cpu_cores = cpu.get("cores")
self.cpu_system_load = cpu.get("systemLoad") self.cpu_system_load = cpu.get("systemLoad")
self.cpu_process_load = cpu.get("lavalinkLoad") self.cpu_process_load = cpu.get("lavalinkLoad")
@ -106,173 +87,3 @@ class NodeStats:
def __repr__(self) -> str: def __repr__(self) -> str:
return f"<Pomice.NodeStats total_players={self.players_total!r} playing_active={self.players_active!r}>" return f"<Pomice.NodeStats total_players={self.players_total!r} playing_active={self.players_active!r}>"
class FailingIPBlock:
"""
The base class for the failing IP block object from the route planner stats.
Gives critical information about any failing addresses on the block
and the time they failed.
"""
__slots__ = ("address", "failing_time")
def __init__(self, data: dict) -> None:
self.address = data.get("address")
self.failing_time = datetime.fromtimestamp(
float(data.get("failingTimestamp", 0)),
)
def __repr__(self) -> str:
return f"<Pomice.FailingIPBlock address={self.address} failing_time={self.failing_time}>"
class RouteStats:
"""
The base class for the route planner stats object.
Gives critical information about the route planner strategy on the node.
"""
__slots__ = (
"strategy",
"ip_block_type",
"ip_block_size",
"failing_addresses",
"block_index",
"address_index",
)
def __init__(self, data: Dict[str, Any]) -> None:
self.strategy = RouteStrategy(data.get("class"))
details: dict = data.get("details", {})
ip_block: dict = details.get("ipBlock", {})
self.ip_block_type = RouteIPType(ip_block.get("type"))
self.ip_block_size = ip_block.get("size")
self.failing_addresses = [
FailingIPBlock(
data,
)
for data in details.get("failingAddresses", [])
]
self.block_index = details.get("blockIndex")
self.address_index = details.get("currentAddressIndex")
def __repr__(self) -> str:
return f"<Pomice.RouteStats route_strategy={self.strategy!r} failing_addresses={len(self.failing_addresses)}>"
class Ping:
# Thanks to https://github.com/zhengxiaowai/tcping for the nice ping impl
def __init__(self, host: str, port: int, timeout: int = 5) -> None:
self.timer = self.Timer()
self._successed = 0
self._failed = 0
self._conn_time = None
self._host = host
self._port = port
self._timeout = timeout
class Socket:
def __init__(self, family: int, type_: int, timeout: Optional[float]) -> None:
s = socket.socket(family, type_)
s.settimeout(timeout)
self._s = s
def connect(self, host: str, port: int) -> None:
self._s.connect((host, port))
def shutdown(self) -> None:
self._s.shutdown(socket.SHUT_RD)
def close(self) -> None:
self._s.close()
class Timer:
def __init__(self) -> None:
self._start: float = 0.0
self._stop: float = 0.0
def start(self) -> None:
self._start = timer()
def stop(self) -> None:
self._stop = timer()
def cost(self, funcs: Iterable[Callable], args: Any) -> float:
self.start()
for func, arg in zip_longest(funcs, args):
if arg:
func(*arg)
else:
func()
self.stop()
return self._stop - self._start
def _create_socket(self, family: int, type_: int) -> Socket:
return self.Socket(family, type_, self._timeout)
def get_ping(self) -> float:
s = self._create_socket(socket.AF_INET, socket.SOCK_STREAM)
cost_time = self.timer.cost(
(s.connect, s.shutdown),
((self._host, self._port), None),
)
s_runtime = 1000 * (cost_time)
return s_runtime
class LavalinkVersion(NamedTuple):
major: int
minor: int
fix: int
def __eq__(self, other: object) -> bool:
if not isinstance(other, LavalinkVersion):
return False
return (
(self.major == other.major) and (self.minor == other.minor) and (self.fix == other.fix)
)
def __ne__(self, other: object) -> bool:
if not isinstance(other, LavalinkVersion):
return False
return not (self == other)
def __lt__(self, other: object) -> bool:
if not isinstance(other, LavalinkVersion):
return False
if self.major > other.major:
return False
if self.minor > other.minor:
return False
if self.fix > other.fix:
return False
return True
def __gt__(self, other: object) -> bool:
if not isinstance(other, LavalinkVersion):
return False
return not (self < other)
def __le__(self, other: object) -> bool:
if not isinstance(other, LavalinkVersion):
return False
return (self < other) or (self == other)
def __ge__(self, other: object) -> bool:
if not isinstance(other, LavalinkVersion):
return False
return (self > other) or (self == other)

View File

@ -5,15 +5,8 @@ requires = [
] ]
build-backend = "setuptools.build_meta" build-backend = "setuptools.build_meta"
[tool.black] [tool.autopep8]
line-length = 100 max_line_length = 100
in-place = true
[tool.mypy] recursive = true
mypy_path = "./" aggressive = 3
files = ["pomice"]
disallow_untyped_defs = true
disallow_any_unimported = true
no_implicit_optional = true
check_untyped_defs = true
warn_unused_ignores = true
show_error_codes = true

View File

@ -1,73 +1,32 @@
# type: ignore
import re
import setuptools import setuptools
version = ""
requirements = ["aiohttp>=3.7.4,<4", "orjson", "websockets"]
with open("pomice/__init__.py") as f:
version = re.search(
r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
f.read(),
re.MULTILINE,
).group(1)
if not version:
raise RuntimeError("version is not set")
if version.endswith(("a", "b", "rc")):
# append version identifier based on commit count
try:
import subprocess
p = subprocess.Popen(
["git", "rev-list", "--count", "HEAD"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
out, err = p.communicate()
if out:
version += out.decode("utf-8").strip()
p = subprocess.Popen(
["git", "rev-parse", "--short", "HEAD"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
out, err = p.communicate()
if out:
version += "+g" + out.decode("utf-8").strip()
except Exception:
pass
with open("README.md") as f: with open("README.md") as f:
readme = f.read() readme = f.read()
setuptools.setup( setuptools.setup(
name="pomice", name="pomice",
author="cloudwithax", author="cloudwithax",
version=version, version="1.1.1",
url="https://github.com/cloudwithax/pomice", url="https://github.com/cloudwithax/pomice",
packages=setuptools.find_packages(), packages=setuptools.find_packages(),
license="GPL", license="GPL",
description="The modern Lavalink wrapper designed for Discord.py", description="The modern Lavalink wrapper designed for Discord.py",
long_description=readme, long_description=readme,
long_description_content_type="text/markdown", long_description_content_type="text/markdown",
package_data={"pomice": ["py.typed"]},
include_package_data=True, include_package_data=True,
install_requires=requirements, install_requires=['discord.py>=2.0.0a'],
extra_require=None, extra_require=None,
classifiers=[ classifiers=[
"Framework :: AsyncIO", "Framework :: AsyncIO",
"Operating System :: OS Independent", 'Operating System :: OS Independent',
"Natural Language :: English", 'Natural Language :: English',
"Intended Audience :: Developers", 'Intended Audience :: Developers',
"Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.8",
"Topic :: Software Development :: Libraries :: Python Modules", 'Topic :: Software Development :: Libraries :: Python Modules',
"Topic :: Software Development :: Libraries", 'Topic :: Software Development :: Libraries',
"Topic :: Internet", "Topic :: Internet"
], ],
python_requires=">=3.8", python_requires='>=3.8',
keywords=["pomice", "lavalink", "discord.py"], keywords=['pomice', 'lavalink', "discord.py"],
) )