mirror of
https://github.com/jarulsamy/Plex-Bot.git
synced 2024-08-19 15:01:55 +02:00
Compare commits
21 Commits
8f05f5e27f
...
master
Author | SHA1 | Date | |
---|---|---|---|
360416bb02 | |||
ccee843a36 | |||
90c40fb0d6 | |||
8b90fb8e34 | |||
60ef54d8e4 | |||
280cbaed92 | |||
2f17494ebd | |||
ed9e677108 | |||
aa51cc4301 | |||
069d88fd1e | |||
15b7e0f50e | |||
04da5dfd42 | |||
19360e3101 | |||
52099fa794 | |||
139ce07d24 | |||
5f9c83b75e | |||
f8e5af87b6 | |||
a45ccb657e | |||
bcbce98d91 | |||
6521e7e26c | |||
add1a1af0d |
@ -1,8 +1,6 @@
|
||||
"""
|
||||
Plex music bot for discord.
|
||||
|
||||
Do not import this module, it is intended to be
|
||||
used exclusively within a docker environment.
|
||||
"""
|
||||
import logging
|
||||
import sys
|
||||
@ -19,7 +17,7 @@ plex_log = logging.getLogger("Plex")
|
||||
bot_log = logging.getLogger("Bot")
|
||||
|
||||
|
||||
def load_config(filename: str) -> Dict[str, str]:
|
||||
def load_config(basedir: str,filename: str) -> Dict[str, str]:
|
||||
"""Loads config from yaml file
|
||||
|
||||
Grabs key/value config pairs from a file.
|
||||
@ -35,12 +33,12 @@ def load_config(filename: str) -> Dict[str, str]:
|
||||
"""
|
||||
# All config files should be in /config
|
||||
# for docker deployment.
|
||||
filename = Path("/config", filename)
|
||||
filename = Path(basedir, filename)
|
||||
try:
|
||||
with open(filename, "r") as config_file:
|
||||
config = yaml.safe_load(config_file)
|
||||
except FileNotFoundError:
|
||||
root_log.fatal("Configuration file not found.")
|
||||
root_log.fatal("Configuration file not found at '"+str(filename)+"'.")
|
||||
sys.exit(-1)
|
||||
|
||||
# Convert str level type to logging constant
|
||||
@ -56,7 +54,7 @@ def load_config(filename: str) -> Dict[str, str]:
|
||||
config["plex"]["log_level"] = levels[config["plex"]["log_level"].upper()]
|
||||
config["discord"]["log_level"] = levels[config["discord"]["log_level"].upper()]
|
||||
|
||||
if config["lyrics"]["token"].lower() == "none":
|
||||
config["lyrics"]["token"] = None
|
||||
if config["lyrics"] and config["lyrics"]["token"].lower() == "none":
|
||||
config["lyrics"] = None
|
||||
|
||||
return config
|
||||
|
@ -11,7 +11,11 @@ from .bot import General
|
||||
from .bot import Plex
|
||||
|
||||
# Load config from file
|
||||
config = load_config("config.yaml")
|
||||
configdir = "config"
|
||||
from os import geteuid
|
||||
if geteuid() == 0:
|
||||
configdir = "/config"
|
||||
config = load_config(configdir,"config.yaml")
|
||||
|
||||
BOT_PREFIX = config["discord"]["prefix"]
|
||||
TOKEN = config["discord"]["token"]
|
||||
@ -20,7 +24,10 @@ BASE_URL = config["plex"]["base_url"]
|
||||
PLEX_TOKEN = config["plex"]["token"]
|
||||
LIBRARY_NAME = config["plex"]["library_name"]
|
||||
|
||||
LYRICS_TOKEN = config["lyrics"]["token"]
|
||||
if config["lyrics"]:
|
||||
LYRICS_TOKEN = config["lyrics"]["token"]
|
||||
else:
|
||||
LYRICS_TOKEN = None
|
||||
|
||||
# Set appropiate log level
|
||||
root_log = logging.getLogger()
|
||||
|
294
PlexBot/bot.py
294
PlexBot/bot.py
@ -6,7 +6,6 @@ from urllib.request import urlopen
|
||||
import requests
|
||||
|
||||
import discord
|
||||
import lyricsgenius
|
||||
from async_timeout import timeout
|
||||
from discord import FFmpegPCMAudio
|
||||
from discord.ext import commands
|
||||
@ -32,11 +31,18 @@ Plex:
|
||||
play <SONG_NAME> - Play a song from the plex server.
|
||||
album <ALBUM_NAME> - Queue an entire album to play.
|
||||
playlist <PLAYLIST_NAME> - Queue an entire playlist to play.
|
||||
show_playlists <ARG> <ARG> - Query for playlists with a name matching any of the arguments.
|
||||
lyrics - Print the lyrics of the song (Requires Genius API)
|
||||
np - Print the current playing song.
|
||||
q - Print the current queue (This can take very long!)
|
||||
stop - Halt playback and leave vc.
|
||||
loop - Loop the current song.
|
||||
loopq - Loop the current queue.
|
||||
unloop - Disable looping the current track.
|
||||
unloopq - Disable looping the current queue.
|
||||
pause - Pause playback.
|
||||
resume - Resume playback.
|
||||
skip - Skip the current song. Give a number as argument to skip more than 1.
|
||||
clear - Clear play queue.
|
||||
|
||||
[] - Optional args.
|
||||
@ -182,6 +188,7 @@ class Plex(commands.Cog):
|
||||
self.bot_prefix = bot.command_prefix
|
||||
|
||||
if kwargs["lyrics_token"]:
|
||||
import lyricsgenius
|
||||
self.genius = lyricsgenius.Genius(kwargs["lyrics_token"])
|
||||
else:
|
||||
plex_log.warning("No lyrics token specified, lyrics disabled")
|
||||
@ -200,7 +207,10 @@ class Plex(commands.Cog):
|
||||
# Initialize necessary vars
|
||||
self.voice_channel = None
|
||||
self.current_track = None
|
||||
self.is_looping = False
|
||||
self.loop_queue = None
|
||||
self.np_message_id = None
|
||||
self.show_queue_message_ids = []
|
||||
self.ctx = None
|
||||
|
||||
# Initialize events
|
||||
@ -266,6 +276,15 @@ class Plex(commands.Cog):
|
||||
except NotFound:
|
||||
raise MediaNotFoundError("Playlist cannot be found")
|
||||
|
||||
def _get_playlists(self):
|
||||
"""
|
||||
Search the Plex music db for playlist
|
||||
|
||||
Returns:
|
||||
List of plexapi.playlist
|
||||
"""
|
||||
return self.pms.playlists()
|
||||
|
||||
async def _play(self):
|
||||
"""
|
||||
Heavy lifting of playing songs
|
||||
@ -285,9 +304,12 @@ class Plex(commands.Cog):
|
||||
track_url = self.current_track.getStreamURL()
|
||||
audio_stream = FFmpegPCMAudio(track_url)
|
||||
|
||||
while self.voice_channel.is_playing():
|
||||
asyncio.sleep(2)
|
||||
while self.voice_channel and self.voice_channel.is_playing():
|
||||
bot_log.debug("waiting for track to finish")
|
||||
await asyncio.sleep(2)
|
||||
bot_log.debug("track finished")
|
||||
|
||||
if self.voice_channel:
|
||||
self.voice_channel.play(audio_stream, after=self._toggle_next)
|
||||
|
||||
plex_log.debug("%s - URL: %s", self.current_track, track_url)
|
||||
@ -295,6 +317,29 @@ class Plex(commands.Cog):
|
||||
embed, img = self._build_embed_track(self.current_track)
|
||||
self.np_message_id = await self.ctx.send(embed=embed, file=img)
|
||||
|
||||
async def _play_next(self):
|
||||
try:
|
||||
from asyncio.exceptions import CancelledError
|
||||
except ImportError:
|
||||
from concurrent.futures._base import CancelledError
|
||||
if self.is_looping:
|
||||
self.current_track = self.is_looping
|
||||
else:
|
||||
try:
|
||||
self.current_track = await self.play_queue.get()
|
||||
except CancelledError:
|
||||
bot_log.debug("failed to pop queue")
|
||||
|
||||
if not self.current_track and self.loop_queue:
|
||||
bot_log.debug("swapping loop queue and play queue")
|
||||
for item in self.loop_queue:
|
||||
await self.play_queue.put(item)
|
||||
|
||||
try:
|
||||
self.current_track = await self.play_queue.get()
|
||||
except CancelledError:
|
||||
bot_log.debug("failed to pop queue")
|
||||
|
||||
async def _audio_player_task(self):
|
||||
"""
|
||||
Coroutine to handle playback and queuing
|
||||
@ -318,16 +363,18 @@ class Plex(commands.Cog):
|
||||
try:
|
||||
# Disconnect after 15 seconds idle
|
||||
async with timeout(15):
|
||||
self.current_track = await self.play_queue.get()
|
||||
await self._play_next()
|
||||
except asyncio.TimeoutError:
|
||||
bot_log("timeout - disconnecting")
|
||||
await self.voice_channel.disconnect()
|
||||
self.voice_channel = None
|
||||
|
||||
if not self.current_track:
|
||||
self.current_track = await self.play_queue.get()
|
||||
await self._play_next()
|
||||
|
||||
await self._play()
|
||||
await self.play_next_event.wait()
|
||||
if self.np_message_id:
|
||||
await self.np_message_id.delete()
|
||||
|
||||
def _toggle_next(self, error=None):
|
||||
@ -370,16 +417,22 @@ class Plex(commands.Cog):
|
||||
ValueError: Unsupported type of embed {type_}
|
||||
"""
|
||||
# Grab the relevant thumbnail
|
||||
if track.thumbUrl:
|
||||
img_stream = requests.get(track.thumbUrl, stream=True).raw
|
||||
img = io.BytesIO(img_stream.read())
|
||||
|
||||
# Attach to discord embed
|
||||
art_file = discord.File(img, filename="image0.png")
|
||||
else:
|
||||
art_file = None
|
||||
|
||||
# Get appropiate status message
|
||||
if type_ == "play":
|
||||
title = f"Now Playing - {track.title}"
|
||||
elif type_ == "queue":
|
||||
title = f"Added to queue - {track.title}"
|
||||
elif type_ == "queued":
|
||||
title = f"Next in line - {track.title}"
|
||||
else:
|
||||
raise ValueError(f"Unsupported type of embed {type_}")
|
||||
|
||||
@ -436,7 +489,7 @@ class Plex(commands.Cog):
|
||||
return embed, art_file
|
||||
|
||||
@staticmethod
|
||||
def _build_embed_playlist(self, playlist):
|
||||
def _build_embed_playlist(self, playlist, title, descrip):
|
||||
"""
|
||||
Creates a pretty embed card for playlists
|
||||
|
||||
@ -455,13 +508,14 @@ class Plex(commands.Cog):
|
||||
None
|
||||
"""
|
||||
# Grab the relevant thumbnail
|
||||
try:
|
||||
img_stream = requests.get(self.pms.url(playlist.composite, True), stream=True).raw
|
||||
img = io.BytesIO(img_stream.read())
|
||||
except:
|
||||
raise MediaNotFoundError("no image available")
|
||||
|
||||
# Attach to discord embed
|
||||
art_file = discord.File(img, filename="image0.png")
|
||||
title = "Added playlist to queue"
|
||||
descrip = f"{playlist.title}"
|
||||
|
||||
embed = discord.Embed(
|
||||
title=title, description=descrip, colour=discord.Color.red()
|
||||
@ -493,8 +547,11 @@ class Plex(commands.Cog):
|
||||
|
||||
# Connect to voice if not already
|
||||
if not self.voice_channel:
|
||||
try:
|
||||
self.voice_channel = await ctx.author.voice.channel.connect()
|
||||
bot_log.debug("Connected to vc.")
|
||||
except asyncio.exceptions.TimeoutError:
|
||||
bot_log.debug("Cannot connect to vc - timeout")
|
||||
|
||||
@command()
|
||||
async def play(self, ctx, *args):
|
||||
@ -531,7 +588,7 @@ class Plex(commands.Cog):
|
||||
pass
|
||||
|
||||
# Specific add to queue message
|
||||
if self.voice_channel.is_playing():
|
||||
if self.voice_channel and self.voice_channel.is_playing():
|
||||
bot_log.debug("Added to queue - %s", title)
|
||||
embed, img = self._build_embed_track(track, type_="queue")
|
||||
await ctx.send(embed=embed, file=img)
|
||||
@ -580,6 +637,37 @@ class Plex(commands.Cog):
|
||||
for track in album.tracks():
|
||||
await self.play_queue.put(track)
|
||||
|
||||
async def play_playlist(self, title, shuffle=False):
|
||||
try:
|
||||
playlist = self._search_playlists(title)
|
||||
except MediaNotFoundError:
|
||||
await self.ctx.send(f"Can't find playlist: {title}")
|
||||
bot_log.debug("Failed to queue playlist, can't find - %s", title)
|
||||
return
|
||||
|
||||
try:
|
||||
await self._validate(self.ctx)
|
||||
except VoiceChannelError:
|
||||
pass
|
||||
|
||||
try:
|
||||
embed, img = self._build_embed_playlist(self, playlist, "Added playlist to queue", playlist.title)
|
||||
await self.ctx.send(embed=embed, file=img)
|
||||
|
||||
items = [ item for item in playlist.items() if item.TYPE == "track" ]
|
||||
if shuffle:
|
||||
from random import shuffle
|
||||
shuffle(items)
|
||||
|
||||
for item in items:
|
||||
await self.play_queue.put(item)
|
||||
|
||||
bot_log.debug("Added to queue - %s", title)
|
||||
|
||||
except MediaNotFoundError:
|
||||
await self.ctx.send(message="Playlist "+title+" seems to be empty!")
|
||||
bot_log.debug("Playlist empty - %s", title)
|
||||
|
||||
@command()
|
||||
async def playlist(self, ctx, *args):
|
||||
"""
|
||||
@ -601,27 +689,68 @@ class Plex(commands.Cog):
|
||||
# Save the context to use with async callbacks
|
||||
self.ctx = ctx
|
||||
title = " ".join(args)
|
||||
await self.play_playlist(title)
|
||||
|
||||
try:
|
||||
playlist = self._search_playlists(title)
|
||||
except MediaNotFoundError:
|
||||
await ctx.send(f"Can't find playlist: {title}")
|
||||
bot_log.debug("Failed to queue playlist, can't find - %s", title)
|
||||
return
|
||||
@command()
|
||||
async def playlist_shuffle(self, ctx, *args):
|
||||
"""
|
||||
User command to play playlist in shuffle mode
|
||||
|
||||
Searchs plex db and either, initiates playback, or
|
||||
adds to queue. Handles invalid usage from the user.
|
||||
|
||||
Args:
|
||||
ctx: discord.ext.commands.Context message context from command
|
||||
*args: Title of playlist to play
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Raises:
|
||||
None
|
||||
"""
|
||||
# Save the context to use with async callbacks
|
||||
self.ctx = ctx
|
||||
title = " ".join(args)
|
||||
await self.play_playlist(title,shuffle=True)
|
||||
|
||||
|
||||
@command()
|
||||
async def show_playlists(self, ctx, *args):
|
||||
"""
|
||||
User command to show playlists
|
||||
|
||||
Searchs plex db and shows playlists matching.
|
||||
|
||||
Args:
|
||||
ctx: discord.ext.commands.Context message context from command
|
||||
*args: String filter for playlist names
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Raises:
|
||||
None
|
||||
"""
|
||||
# Save the context to use with async callbacks
|
||||
self.ctx = ctx
|
||||
|
||||
playlists = self._get_playlists()
|
||||
|
||||
try:
|
||||
await self._validate(ctx)
|
||||
except VoiceChannelError:
|
||||
pass
|
||||
|
||||
bot_log.debug("Added to queue - %s", title)
|
||||
embed, img = self._build_embed_playlist(self, playlist)
|
||||
for playlist in playlists:
|
||||
if args and not any(arg in playlist.title for arg in args):
|
||||
continue
|
||||
from datetime import timedelta
|
||||
if playlist.duration:
|
||||
seconds = playlist.duration / 1000
|
||||
embed, img = self._build_embed_playlist(self, playlist, playlist.title, "{:0>8}".format(str(timedelta(seconds=seconds))))
|
||||
await ctx.send(embed=embed, file=img)
|
||||
|
||||
for item in playlist.items():
|
||||
if (item.TYPE == "track"):
|
||||
await self.play_queue.put(item)
|
||||
|
||||
@command()
|
||||
async def stop(self, ctx):
|
||||
"""
|
||||
@ -646,6 +775,80 @@ class Plex(commands.Cog):
|
||||
bot_log.debug("Stopped")
|
||||
await ctx.send(":stop_button: Stopped")
|
||||
|
||||
@command()
|
||||
async def loop(self, ctx):
|
||||
"""
|
||||
User command to activate looping the current track
|
||||
|
||||
Args:
|
||||
ctx: discord.ext.commands.Context message context from command
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Raises:
|
||||
None
|
||||
"""
|
||||
bot_log.debug("Looping "+str(self.current_track))
|
||||
self.is_looping = self.current_track
|
||||
|
||||
@command()
|
||||
async def loopq(self, ctx):
|
||||
"""
|
||||
User command to activate looping the current queue
|
||||
|
||||
Args:
|
||||
ctx: discord.ext.commands.Context message context from command
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Raises:
|
||||
None
|
||||
"""
|
||||
bot_log.debug("Looping current queue")
|
||||
if self.current_track:
|
||||
self.loop_queue = [ self.current_track ]
|
||||
else:
|
||||
self.loop_queue = []
|
||||
for item in self.play_queue._queue:
|
||||
self.loop_queue.append(item)
|
||||
|
||||
@command()
|
||||
async def unloop(self, ctx):
|
||||
"""
|
||||
User command to deactivate looping the current track
|
||||
|
||||
Args:
|
||||
ctx: discord.ext.commands.Context message context from command
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Raises:
|
||||
None
|
||||
"""
|
||||
bot_log.debug("Looping current queue")
|
||||
self.is_looping = False
|
||||
|
||||
@command()
|
||||
async def unloopq(self, ctx):
|
||||
"""
|
||||
User command to deactivate looping the current queue
|
||||
|
||||
Args:
|
||||
ctx: discord.ext.commands.Context message context from command
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Raises:
|
||||
None
|
||||
"""
|
||||
bot_log.debug("Unlooping")
|
||||
self.loop_queue = None
|
||||
|
||||
|
||||
@command()
|
||||
async def pause(self, ctx):
|
||||
"""
|
||||
@ -688,7 +891,7 @@ class Plex(commands.Cog):
|
||||
await ctx.send(":play_pause: Resumed")
|
||||
|
||||
@command()
|
||||
async def skip(self, ctx):
|
||||
async def skip(self, ctx, *args):
|
||||
"""
|
||||
User command to skip song in queue
|
||||
|
||||
@ -704,10 +907,16 @@ class Plex(commands.Cog):
|
||||
Raises:
|
||||
None
|
||||
"""
|
||||
bot_log.debug("Skip")
|
||||
n = 1
|
||||
if args:
|
||||
n = int(args[0])
|
||||
bot_log.debug("Skipping "+str(n))
|
||||
if self.voice_channel:
|
||||
self.voice_channel.stop()
|
||||
bot_log.debug("Skipped")
|
||||
if n>1:
|
||||
for i in range(n-1):
|
||||
await self.play_queue.get()
|
||||
self._toggle_next()
|
||||
|
||||
@command(name="np")
|
||||
@ -728,15 +937,51 @@ class Plex(commands.Cog):
|
||||
None
|
||||
"""
|
||||
if self.current_track:
|
||||
embed, img = self._build_embed_track(self.current_track)
|
||||
embed, img = self._build_embed_track(self.current_track,type_="play")
|
||||
bot_log.debug("Now playing")
|
||||
if self.np_message_id:
|
||||
try:
|
||||
await self.np_message_id.delete()
|
||||
bot_log.debug("Deleted old np status")
|
||||
except discord.errors.NotFound:
|
||||
pass
|
||||
|
||||
bot_log.debug("Created np status")
|
||||
self.np_message_id = await ctx.send(embed=embed, file=img)
|
||||
|
||||
@command(name="q")
|
||||
async def show_queue(self, ctx):
|
||||
"""
|
||||
User command to print the current queue
|
||||
|
||||
Deletes old `now playing` status message,
|
||||
Creates a new one with up to date information.
|
||||
|
||||
Args:
|
||||
ctx: discord.ext.commands.Context message context from command
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Raises:
|
||||
None
|
||||
"""
|
||||
bot_log.debug("Deleted old queue messages")
|
||||
for msg in self.show_queue_message_ids:
|
||||
await msg.delete()
|
||||
|
||||
# need to do this in order to avoid errors when queue is modified during inspection
|
||||
elems = []
|
||||
for track in self.play_queue._queue:
|
||||
elems.append(track)
|
||||
|
||||
for track in elems:
|
||||
embed, img = self._build_embed_track(track,type_="queued")
|
||||
bot_log.debug("Show queue")
|
||||
|
||||
bot_log.debug("Created queue message")
|
||||
self.show_queue_message_ids.append(await ctx.send(embed=embed, file=img))
|
||||
|
||||
@command()
|
||||
async def clear(self, ctx):
|
||||
"""
|
||||
@ -752,6 +997,7 @@ class Plex(commands.Cog):
|
||||
None
|
||||
"""
|
||||
self.play_queue = asyncio.Queue()
|
||||
self.loop_queue = None
|
||||
bot_log.debug("Cleared queue")
|
||||
await ctx.send(":boom: Queue cleared.")
|
||||
|
||||
|
@ -63,6 +63,9 @@ Plex-Bot runs entirely in a Docker container. Ensure you have Docker and docker-
|
||||
token: "<PLEX_TOKEN>"
|
||||
library_name: "<LIBRARY_NAME>"
|
||||
log_level: "debug"
|
||||
|
||||
lyrics:
|
||||
token: "none" # Add your token here if you enable lyrics
|
||||
```
|
||||
|
||||
4. Create a Discord bot application:
|
||||
@ -91,8 +94,6 @@ Plex-Bot runs entirely in a Docker container. Ensure you have Docker and docker-
|
||||
|
||||
6. Get your Lyrics Genius token (Optional):
|
||||
|
||||
If you wanty to disable this feature, set token to `None` in `config/config.yaml`
|
||||
|
||||
If you would like to enable the lyrics feature of the bot, you need to signup for a free GeniusLyrics account, [here](https://genius.com/api-clients).
|
||||
|
||||
After you make an account:
|
||||
@ -103,7 +104,7 @@ Plex-Bot runs entirely in a Docker container. Ensure you have Docker and docker-
|
||||
|
||||
3. Set the redirect url to: `http://localhost`
|
||||
|
||||
4. Copy the **Client Access Token** to `config/config.yaml`
|
||||
4. Copy the **Client Access Token** and replace `None` with your token in `config/config.yaml`
|
||||
|
||||
7. Customize remaining settings
|
||||
|
||||
|
Reference in New Issue
Block a user