mirror of
https://github.com/jarulsamy/Plex-Bot.git
synced 2024-08-19 15:01:55 +02:00
Compare commits
14 Commits
Author | SHA1 | Date | |
---|---|---|---|
7f49c4d958 | |||
ed1a64cb52 | |||
7471da85f7 | |||
4633247004 | |||
98a36c6cbc | |||
b7ab589f6e | |||
4aadd886d5 | |||
33bbf21bab | |||
253f2a9a82 | |||
af91883635 | |||
cfd89ea6e8 | |||
9cbd0be424 | |||
1a8ec5f21f | |||
d0aacc3f0b |
@ -14,7 +14,7 @@ WORKDIR /src
|
|||||||
COPY requirements.txt .
|
COPY requirements.txt .
|
||||||
|
|
||||||
# Install all dependencies.
|
# Install all dependencies.
|
||||||
RUN pip install --only-binary all --no-cache-dir -r requirements.txt
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
# Copy PlexBot over to src.
|
# Copy PlexBot over to src.
|
||||||
COPY PlexBot/ PlexBot
|
COPY PlexBot/ PlexBot
|
||||||
|
17
Jenkinsfile
vendored
17
Jenkinsfile
vendored
@ -49,17 +49,18 @@ pipeline {
|
|||||||
steps {
|
steps {
|
||||||
sh ''' source /var/lib/jenkins/miniconda3/etc/profile.d/conda.sh
|
sh ''' source /var/lib/jenkins/miniconda3/etc/profile.d/conda.sh
|
||||||
conda activate ${BUILD_TAG}
|
conda activate ${BUILD_TAG}
|
||||||
python deploy/build.py
|
./deploy/build.sh
|
||||||
'''
|
'''
|
||||||
}
|
}
|
||||||
post {
|
|
||||||
always {
|
|
||||||
// Archive unit tests for the future
|
|
||||||
archiveArtifacts (allowEmptyArchive: true,
|
|
||||||
artifacts: 'dist/*whl',
|
|
||||||
fingerprint: true)
|
|
||||||
// sh 'python deploy/push.py'
|
|
||||||
}
|
}
|
||||||
|
stage('Push Image') {
|
||||||
|
when {
|
||||||
|
expression {
|
||||||
|
currentBuild.result == 'SUCCESS'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
steps {
|
||||||
|
sh './deploy/push.sh'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,9 @@
|
|||||||
|
"""
|
||||||
|
Plex music bot for discord.
|
||||||
|
|
||||||
|
Do not import this module, it is intended to be
|
||||||
|
used exclusively within a docker environment.
|
||||||
|
"""
|
||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@ -14,13 +20,25 @@ bot_log = logging.getLogger("Bot")
|
|||||||
|
|
||||||
|
|
||||||
def load_config(filename: str) -> Dict[str, str]:
|
def load_config(filename: str) -> Dict[str, str]:
|
||||||
|
"""Loads config from yaml file
|
||||||
|
|
||||||
|
Grabs key/value config pairs from a file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
filename: str path to yaml file.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict[str, str] Values from config file.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
FileNotFound Configuration file not found.
|
||||||
|
"""
|
||||||
# All config files should be in /config
|
# All config files should be in /config
|
||||||
# for docker deployment.
|
# for docker deployment.
|
||||||
filename = Path("/config", filename)
|
filename = Path("/config", filename)
|
||||||
try:
|
try:
|
||||||
with open(filename, "r") as f:
|
with open(filename, "r") as config_file:
|
||||||
config = yaml.safe_load(f)
|
config = yaml.safe_load(config_file)
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
root_log.fatal("Configuration file not found.")
|
root_log.fatal("Configuration file not found.")
|
||||||
sys.exit(-1)
|
sys.exit(-1)
|
||||||
|
@ -1,11 +1,14 @@
|
|||||||
|
"""
|
||||||
|
Main entrypoint script.
|
||||||
|
Sets up loggers and initiates bot.
|
||||||
|
"""
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
from discord.ext.commands import Bot
|
from discord.ext.commands import Bot
|
||||||
|
|
||||||
from . import FORMAT
|
from . import load_config
|
||||||
from .bot import General
|
from .bot import General
|
||||||
from .bot import Plex
|
from .bot import Plex
|
||||||
from PlexBot import load_config
|
|
||||||
|
|
||||||
# Load config from file
|
# Load config from file
|
||||||
config = load_config("config.yaml")
|
config = load_config("config.yaml")
|
||||||
|
@ -1 +1,5 @@
|
|||||||
VERSION = "0.0.4"
|
"""Track version number of package."""
|
||||||
|
VERSION = "1.0.0"
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print(VERSION)
|
||||||
|
342
PlexBot/bot.py
342
PlexBot/bot.py
@ -1,3 +1,4 @@
|
|||||||
|
"""All discord bot and Plex api interactions."""
|
||||||
import asyncio
|
import asyncio
|
||||||
import io
|
import io
|
||||||
import logging
|
import logging
|
||||||
@ -18,19 +19,59 @@ bot_log = logging.getLogger("Bot")
|
|||||||
|
|
||||||
|
|
||||||
class General(commands.Cog):
|
class General(commands.Cog):
|
||||||
|
"""General commands
|
||||||
|
|
||||||
|
Manage general bot behavior
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
|
"""Initialize commands
|
||||||
|
|
||||||
|
Args:
|
||||||
|
bot: discord.ext.command.Bot, bind for cogs
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
None
|
||||||
|
"""
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
|
|
||||||
@command()
|
@command()
|
||||||
async def kill(self, ctx, *args):
|
async def kill(self, ctx, *args):
|
||||||
|
"""Kill the bot
|
||||||
|
|
||||||
|
Args:
|
||||||
|
ctx: discord.ext.commands.Context message context from command
|
||||||
|
*args: optional flags
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
None
|
||||||
|
"""
|
||||||
if "silent" not in args:
|
if "silent" not in args:
|
||||||
await ctx.send(f"Stopping upon the request of {ctx.author.mention}")
|
await ctx.send(f"Stopping upon the request of {ctx.author.mention}")
|
||||||
|
|
||||||
await self.bot.close()
|
await self.bot.close()
|
||||||
bot_log.info(f"Stopping upon the request of {ctx.author.mention}")
|
bot_log.info("Stopping upon the request of %s", ctx.author.mention)
|
||||||
|
|
||||||
@command()
|
@command()
|
||||||
async def cleanup(self, ctx, limit=250):
|
async def cleanup(self, ctx, limit=250):
|
||||||
|
"""Delete old messages from bot
|
||||||
|
|
||||||
|
Args:
|
||||||
|
ctx: discord.ext.commands.Context message context from command
|
||||||
|
limit: int number of messages to go back by to delete. Default 250
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
None
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
"""
|
||||||
channel = ctx.message.channel
|
channel = ctx.message.channel
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@ -43,17 +84,51 @@ class General(commands.Cog):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
except discord.Forbidden:
|
except discord.Forbidden:
|
||||||
|
bot_log.info("Unable to delete messages, insufficient permissions.")
|
||||||
await ctx.send("I don't have the necessary permissions to delete messages.")
|
await ctx.send("I don't have the necessary permissions to delete messages.")
|
||||||
|
|
||||||
|
|
||||||
class Plex(commands.Cog):
|
class Plex(commands.Cog):
|
||||||
def __init__(self, bot, base_url, plex_token, lib_name, bot_prefix) -> None:
|
"""Discord commands pertinent to interacting with Plex
|
||||||
|
|
||||||
|
Contains user commands such as play, pause, resume, stop, etc.
|
||||||
|
Grabs, and parses all data from plex database.
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
# pylint: disable=too-many-instance-attributes
|
||||||
|
# All are necessary to detect global interactions
|
||||||
|
# within the bot.
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self, bot, base_url: str, plex_token: str, lib_name: str, bot_prefix: str
|
||||||
|
):
|
||||||
|
"""Initializes Plex resources
|
||||||
|
|
||||||
|
Connects to Plex library and sets up
|
||||||
|
all asyncronous communications.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
bot: discord.ext.command.Bot, bind for cogs
|
||||||
|
base_url: str url to Plex server
|
||||||
|
plex_token: str X-Token of Plex server
|
||||||
|
lib_name: str name of Plex library to search through
|
||||||
|
bot_prefix: str prefix used to interact with bots
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
plexapi.exceptions.Unauthorized: Invalid Plex token
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
"""
|
||||||
|
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
self.base_url = base_url
|
self.base_url = base_url
|
||||||
self.plex_token = plex_token
|
self.plex_token = plex_token
|
||||||
self.library_name = lib_name
|
self.library_name = lib_name
|
||||||
self.bot_prefix = bot_prefix
|
self.bot_prefix = bot_prefix
|
||||||
|
|
||||||
|
# Log fatal invalid plex token
|
||||||
try:
|
try:
|
||||||
self.pms = PlexServer(self.base_url, self.plex_token)
|
self.pms = PlexServer(self.base_url, self.plex_token)
|
||||||
except Unauthorized:
|
except Unauthorized:
|
||||||
@ -61,57 +136,103 @@ class Plex(commands.Cog):
|
|||||||
raise Unauthorized("Invalid Plex token")
|
raise Unauthorized("Invalid Plex token")
|
||||||
|
|
||||||
self.music = self.pms.library.section(self.library_name)
|
self.music = self.pms.library.section(self.library_name)
|
||||||
plex_log.debug(f"Connected to plex library: {self.library_name}")
|
plex_log.debug("Connected to plex library: %s", self.library_name)
|
||||||
|
|
||||||
self.vc = None
|
# Initialize necessary vars
|
||||||
|
self.voice_channel = None
|
||||||
self.current_track = None
|
self.current_track = None
|
||||||
self.np_message_id = None
|
self.np_message_id = None
|
||||||
|
self.ctx = None
|
||||||
|
|
||||||
|
# Initialize events
|
||||||
self.play_queue = asyncio.Queue()
|
self.play_queue = asyncio.Queue()
|
||||||
self.play_next_event = asyncio.Event()
|
self.play_next_event = asyncio.Event()
|
||||||
|
|
||||||
|
bot_log.info("Started bot successfully")
|
||||||
self.bot.loop.create_task(self._audio_player_task())
|
self.bot.loop.create_task(self._audio_player_task())
|
||||||
|
|
||||||
bot_log.info("Started bot successfully")
|
def _search_tracks(self, title: str):
|
||||||
|
"""Search the Plex music db
|
||||||
|
|
||||||
def _search_tracks(self, title):
|
Uses a fuzzy search algorithm to find the closest matching song
|
||||||
|
title in the Plex music database.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
title: str title of song to search for
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
plexapi.audio.Track pointing to closest matching title
|
||||||
|
None if song can't be found.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
None
|
||||||
|
"""
|
||||||
tracks = self.music.searchTracks()
|
tracks = self.music.searchTracks()
|
||||||
score = [None, -1]
|
score = [None, -1]
|
||||||
for i in tracks:
|
for i in tracks:
|
||||||
s = fuzz.ratio(title.lower(), i.title.lower())
|
ratio = fuzz.ratio(title.lower(), i.title.lower())
|
||||||
if s > score[1]:
|
if ratio > score[1]:
|
||||||
score[0] = i
|
score[0] = i
|
||||||
score[1] = s
|
score[1] = ratio
|
||||||
elif s == score[1]:
|
elif ratio == score[1]:
|
||||||
score[0] = i
|
score[0] = i
|
||||||
|
|
||||||
return score[0]
|
return score[0]
|
||||||
|
|
||||||
async def _play(self):
|
async def _play(self):
|
||||||
|
"""Heavy lifting of playing songs
|
||||||
|
|
||||||
|
Grabs the appropiate streaming URL, sends the `now playing`
|
||||||
|
message, and initiates playback in the vc.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
None
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
None
|
||||||
|
"""
|
||||||
track_url = self.current_track.getStreamURL()
|
track_url = self.current_track.getStreamURL()
|
||||||
audio_stream = FFmpegPCMAudio(track_url)
|
audio_stream = FFmpegPCMAudio(track_url)
|
||||||
|
|
||||||
while self.vc.is_playing():
|
while self.voice_channel.is_playing():
|
||||||
asyncio.sleep(2)
|
asyncio.sleep(2)
|
||||||
|
|
||||||
self.vc.play(audio_stream, after=self._toggle_next)
|
self.voice_channel.play(audio_stream, after=self._toggle_next)
|
||||||
|
|
||||||
plex_log.debug(f"{self.current_track.title} - URL: {track_url}")
|
plex_log.debug("%s - URL: %s", self.current_track, track_url)
|
||||||
|
|
||||||
embed, f = self._build_embed(self.current_track)
|
embed, img = self._build_embed(self.current_track)
|
||||||
self.np_message_id = await self.ctx.send(embed=embed, file=f)
|
self.np_message_id = await self.ctx.send(embed=embed, file=img)
|
||||||
|
|
||||||
async def _audio_player_task(self):
|
async def _audio_player_task(self):
|
||||||
|
"""Coroutine to handle playback and queuing
|
||||||
|
|
||||||
|
Always-running function awaiting new songs to be added.
|
||||||
|
Auto disconnects from VC if idle for > 15 seconds.
|
||||||
|
Handles auto deletion of now playing song notifications.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
None
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
None
|
||||||
|
"""
|
||||||
while True:
|
while True:
|
||||||
self.play_next_event.clear()
|
self.play_next_event.clear()
|
||||||
if self.vc:
|
if self.voice_channel:
|
||||||
try:
|
try:
|
||||||
# Disconnect after 15 seconds idle
|
# Disconnect after 15 seconds idle
|
||||||
async with timeout(15):
|
async with timeout(15):
|
||||||
self.current_track = await self.play_queue.get()
|
self.current_track = await self.play_queue.get()
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
await self.vc.disconnect()
|
await self.voice_channel.disconnect()
|
||||||
self.vc = None
|
self.voice_channel = None
|
||||||
|
|
||||||
if not self.current_track:
|
if not self.current_track:
|
||||||
self.current_track = await self.play_queue.get()
|
self.current_track = await self.play_queue.get()
|
||||||
@ -121,25 +242,54 @@ class Plex(commands.Cog):
|
|||||||
await self.np_message_id.delete()
|
await self.np_message_id.delete()
|
||||||
|
|
||||||
def _toggle_next(self, error=None):
|
def _toggle_next(self, error=None):
|
||||||
|
"""Callback for vc playback
|
||||||
|
|
||||||
|
Clears current track, then activates _audio_player_task
|
||||||
|
to play next in queue or disconnect.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
error: Optional parameter required for discord.py callback
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
None
|
||||||
|
"""
|
||||||
self.current_track = None
|
self.current_track = None
|
||||||
self.bot.loop.call_soon_threadsafe(self.play_next_event.set)
|
self.bot.loop.call_soon_threadsafe(self.play_next_event.set)
|
||||||
|
|
||||||
def _build_embed(self, track, t="play"):
|
def _build_embed(self, track, type_="play"):
|
||||||
"""Creates a pretty embed card.
|
"""Creates a pretty embed card.
|
||||||
|
|
||||||
|
Builds a helpful status embed with the following info:
|
||||||
|
Status, song title, album, artistm and album art. All
|
||||||
|
pertitent information is grabbed dynamically from the Plex db.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
track: plexapi.audio.Track object of song
|
||||||
|
type_: Type of card to make (play, queue).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
embed: discord.embed fully constructed img payload.
|
||||||
|
thumb_art: io.BytesIO of album thumbnail img.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: Unsupported type of embed {type_}
|
||||||
"""
|
"""
|
||||||
# Grab the relevant thumbnail
|
# Grab the relevant thumbnail
|
||||||
img_stream = urlopen(track.thumbUrl)
|
img_stream = urlopen(track.thumbUrl)
|
||||||
img = io.BytesIO(img_stream.read())
|
img = io.BytesIO(img_stream.read())
|
||||||
|
|
||||||
# Attach to discord embed
|
# Attach to discord embed
|
||||||
f = discord.File(img, filename="image0.png")
|
art_file = discord.File(img, filename="image0.png")
|
||||||
# Get appropiate status message
|
# Get appropiate status message
|
||||||
if t == "play":
|
if type_ == "play":
|
||||||
title = f"Now Playing - {track.title}"
|
title = f"Now Playing - {track.title}"
|
||||||
elif t == "queue":
|
elif type_ == "queue":
|
||||||
title = f"Added to queue - {track.title}"
|
title = f"Added to queue - {track.title}"
|
||||||
else:
|
else:
|
||||||
raise ValueError(f"Unsupported type of embed {t}")
|
raise ValueError(f"Unsupported type of embed {type_}")
|
||||||
|
|
||||||
# Include song details
|
# Include song details
|
||||||
descrip = f"{track.album().title} - {track.artist().title}"
|
descrip = f"{track.album().title} - {track.artist().title}"
|
||||||
@ -152,16 +302,31 @@ class Plex(commands.Cog):
|
|||||||
# Point to file attached with ctx object.
|
# Point to file attached with ctx object.
|
||||||
embed.set_thumbnail(url="attachment://image0.png")
|
embed.set_thumbnail(url="attachment://image0.png")
|
||||||
|
|
||||||
bot_log.debug(f"Built embed for {track.title}")
|
bot_log.debug("Built embed for %s", track.title)
|
||||||
|
|
||||||
return embed, f
|
return embed, art_file
|
||||||
|
|
||||||
@command()
|
@command()
|
||||||
async def play(self, ctx, *args):
|
async def play(self, ctx, *args):
|
||||||
|
"""User command to start playback
|
||||||
|
|
||||||
|
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 song to play
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
None
|
||||||
|
"""
|
||||||
# Save the context to use with async callbacks
|
# Save the context to use with async callbacks
|
||||||
self.ctx = ctx
|
self.ctx = ctx
|
||||||
|
|
||||||
if not len(args):
|
if not args:
|
||||||
await ctx.send(f"Usage: {self.bot_prefix}play TITLE_OF_SONG")
|
await ctx.send(f"Usage: {self.bot_prefix}play TITLE_OF_SONG")
|
||||||
bot_log.debug("Failed to play, invalid usage")
|
bot_log.debug("Failed to play, invalid usage")
|
||||||
return
|
return
|
||||||
@ -172,75 +337,152 @@ class Plex(commands.Cog):
|
|||||||
# Fail if song title can't be found
|
# Fail if song title can't be found
|
||||||
if not track:
|
if not track:
|
||||||
await ctx.send(f"Can't find song: {title}")
|
await ctx.send(f"Can't find song: {title}")
|
||||||
bot_log.debug(f"Failed to play, can't find song - {title}")
|
bot_log.debug("Failed to play, can't find song - %s", title)
|
||||||
return
|
return
|
||||||
|
|
||||||
# Fail if user not in vc
|
# Fail if user not in vc
|
||||||
elif not ctx.author.voice:
|
if not ctx.author.voice:
|
||||||
await ctx.send("Join a voice channel first!")
|
await ctx.send("Join a voice channel first!")
|
||||||
bot_log.debug("Failed to play, requester not in voice channel")
|
bot_log.debug("Failed to play, requester not in voice channel")
|
||||||
return
|
return
|
||||||
|
|
||||||
# Connect to voice if not already
|
# Connect to voice if not already
|
||||||
if not self.vc:
|
if not self.voice_channel:
|
||||||
self.vc = await ctx.author.voice.channel.connect()
|
self.voice_channel = await ctx.author.voice.channel.connect()
|
||||||
bot_log.debug("Connected to vc.")
|
bot_log.debug("Connected to vc.")
|
||||||
|
|
||||||
# Specific add to queue message
|
# Specific add to queue message
|
||||||
if self.vc.is_playing():
|
if self.voice_channel.is_playing():
|
||||||
bot_log.debug(f"Added to queue - {title}")
|
bot_log.debug("Added to queue - %s", title)
|
||||||
embed, f = self._build_embed(track, t="queue")
|
embed, img = self._build_embed(track, type_="queue")
|
||||||
await ctx.send(embed=embed, file=f)
|
await ctx.send(embed=embed, file=img)
|
||||||
|
|
||||||
# Add the song to the async queue
|
# Add the song to the async queue
|
||||||
await self.play_queue.put(track)
|
await self.play_queue.put(track)
|
||||||
|
|
||||||
@command()
|
@command()
|
||||||
async def stop(self, ctx):
|
async def stop(self, ctx):
|
||||||
if self.vc:
|
"""User command to stop playback
|
||||||
self.vc.stop()
|
|
||||||
await self.vc.disconnect()
|
Stops playback and disconnects from vc.
|
||||||
self.vc = None
|
|
||||||
|
Args:
|
||||||
|
ctx: discord.ext.commands.Context message context from command
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
None
|
||||||
|
"""
|
||||||
|
if self.voice_channel:
|
||||||
|
self.voice_channel.stop()
|
||||||
|
await self.voice_channel.disconnect()
|
||||||
|
self.voice_channel = None
|
||||||
self.ctx = None
|
self.ctx = None
|
||||||
bot_log.debug("Stopped")
|
bot_log.debug("Stopped")
|
||||||
await ctx.send(":stop_button: Stopped")
|
await ctx.send(":stop_button: Stopped")
|
||||||
|
|
||||||
@command()
|
@command()
|
||||||
async def pause(self, ctx):
|
async def pause(self, ctx):
|
||||||
if self.vc:
|
"""User command to pause playback
|
||||||
self.vc.pause()
|
|
||||||
|
Pauses playback, but doesn't reset anything
|
||||||
|
to allow playback resuming.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
ctx: discord.ext.commands.Context message context from command
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
None
|
||||||
|
"""
|
||||||
|
if self.voice_channel:
|
||||||
|
self.voice_channel.pause()
|
||||||
bot_log.debug("Paused")
|
bot_log.debug("Paused")
|
||||||
await ctx.send(":play_pause: Paused")
|
await ctx.send(":play_pause: Paused")
|
||||||
|
|
||||||
@command()
|
@command()
|
||||||
async def resume(self, ctx):
|
async def resume(self, ctx):
|
||||||
if self.vc:
|
"""User command to resume playback
|
||||||
self.vc.resume()
|
|
||||||
|
Args:
|
||||||
|
ctx: discord.ext.commands.Context message context from command
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
None
|
||||||
|
"""
|
||||||
|
if self.voice_channel:
|
||||||
|
self.voice_channel.resume()
|
||||||
bot_log.debug("Resumed")
|
bot_log.debug("Resumed")
|
||||||
await ctx.send(":play_pause: Resumed")
|
await ctx.send(":play_pause: Resumed")
|
||||||
|
|
||||||
@command()
|
@command()
|
||||||
async def skip(self, ctx):
|
async def skip(self, ctx):
|
||||||
|
"""User command to skip song in queue
|
||||||
|
|
||||||
|
Skips currently playing song. If no other songs in
|
||||||
|
queue, stops playback, otherwise moves to next song.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
ctx: discord.ext.commands.Context message context from command
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
None
|
||||||
|
"""
|
||||||
bot_log.debug("Skip")
|
bot_log.debug("Skip")
|
||||||
if self.vc:
|
if self.voice_channel:
|
||||||
self.vc.stop()
|
self.voice_channel.stop()
|
||||||
bot_log.debug("Skipped")
|
bot_log.debug("Skipped")
|
||||||
self._toggle_next()
|
self._toggle_next()
|
||||||
|
|
||||||
@command()
|
@command(name="np")
|
||||||
async def np(self, ctx):
|
async def now_playing(self, ctx):
|
||||||
|
"""User command to get currently playing song.
|
||||||
|
|
||||||
|
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
|
||||||
|
"""
|
||||||
if self.current_track:
|
if self.current_track:
|
||||||
embed, f = self._build_embed(self.current_track)
|
embed, img = self._build_embed(self.current_track)
|
||||||
bot_log.debug("Now playing")
|
bot_log.debug("Now playing")
|
||||||
if self.np_message_id:
|
if self.np_message_id:
|
||||||
await self.np_message_id.delete()
|
await self.np_message_id.delete()
|
||||||
bot_log("Deleted old np status")
|
bot_log.debug("Deleted old np status")
|
||||||
|
|
||||||
bot_log("Created np status")
|
bot_log.debug("Created np status")
|
||||||
self.np_message_id = await ctx.send(embed=embed, file=f)
|
self.np_message_id = await ctx.send(embed=embed, file=img)
|
||||||
|
|
||||||
@command()
|
@command()
|
||||||
async def clear(self, ctx):
|
async def clear(self, ctx):
|
||||||
|
"""User command to clear play queue.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
ctx: discord.ext.commands.Context message context from command
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
None
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
None
|
||||||
|
"""
|
||||||
self.play_queue = asyncio.Queue()
|
self.play_queue = asyncio.Queue()
|
||||||
bot_log.debug("Cleared queue")
|
bot_log.debug("Cleared queue")
|
||||||
await ctx.send(":boom: Queue cleared.")
|
await ctx.send(":boom: Queue cleared.")
|
||||||
|
104
README.md
104
README.md
@ -1,28 +1,70 @@
|
|||||||
# Plex-Bot
|
# Plex-Bot
|
||||||
|
|
||||||
|
[](http://perso.crans.org/besson/LICENSE.html)
|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
A Python-based Plex music bot for discord.
|
A Python-based Plex music bot for discord.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
## Setup
|
## Setup
|
||||||
|
|
||||||
Plex-Bot runs entirely in a Docker container. Ensure you have Docker and docker-compose installed according to the official Docker [documentation](https://docs.docker.com/get-docker/).
|
Plex-Bot runs entirely in a Docker container. Ensure you have Docker and docker-compose installed according to the official Docker [documentation](https://docs.docker.com/get-docker/).
|
||||||
|
|
||||||
1. Clone the repository and `cd` into it:
|
1. Create a new folder and `cd` into it:
|
||||||
|
|
||||||
```
|
```bash
|
||||||
$ git clone https://github.com/jarulsamy/Plex-Bot
|
mkdir Plex-Bot
|
||||||
$ cd Plex-Bot
|
cd Plex-Bot
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Create a configuration folder:
|
2. Make a `docker-compose.yml` file or use this sample:
|
||||||
|
|
||||||
Create a new `config` folder and copy the sample config file into it:
|
```yml
|
||||||
|
version: "3"
|
||||||
|
services:
|
||||||
|
plex-bot:
|
||||||
|
container_name: "PlexBot"
|
||||||
|
image: jarulsamy/plex-bot:latest
|
||||||
|
environment:
|
||||||
|
- PUID=1000
|
||||||
|
- PGID=1000
|
||||||
|
- TZ=America/Denver
|
||||||
|
# Required dir for configuration files
|
||||||
|
volumes:
|
||||||
|
- "./config:/config:ro"
|
||||||
|
restart: "unless-stopped"
|
||||||
|
```
|
||||||
|
|
||||||
```
|
3. Create a new `config` folder and create a config file like this::
|
||||||
$ mkdir config
|
|
||||||
$ cp sample-config.yaml config/config.yaml
|
|
||||||
```
|
|
||||||
|
|
||||||
3. Create a Discord bot application:
|
```bash
|
||||||
|
mkdir config
|
||||||
|
cd config
|
||||||
|
touch config.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
```yml
|
||||||
|
# Create a file called config.yaml with the following contents
|
||||||
|
|
||||||
|
root:
|
||||||
|
log_level: "info"
|
||||||
|
|
||||||
|
discord:
|
||||||
|
prefix: "?"
|
||||||
|
token: "<BOT_TOKEN>"
|
||||||
|
log_level: "debug"
|
||||||
|
|
||||||
|
plex:
|
||||||
|
base_url: "<BASE_URL>"
|
||||||
|
token: "<PLEX_TOKEN>"
|
||||||
|
library_name: "<LIBRARY_NAME>"
|
||||||
|
log_level: "debug"
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Create a Discord bot application:
|
||||||
|
|
||||||
1. Go to the Discord developer portal, [here](https://discord.com/developers/applications).
|
1. Go to the Discord developer portal, [here](https://discord.com/developers/applications).
|
||||||
|
|
||||||
@ -38,23 +80,38 @@ $ cp sample-config.yaml config/config.yaml
|
|||||||
6. Click Create Bot User
|
6. Click Create Bot User
|
||||||
This will provide you with your bot Username and Token
|
This will provide you with your bot Username and Token
|
||||||
|
|
||||||
7. Fill in all the necessary numbers in `config/config.yaml`
|
7. Fill in the bot token in `config/config.yaml`
|
||||||
|
|
||||||
4. Get your plex token:
|
5. Get your plex token:
|
||||||
|
|
||||||
Refer to the official [plex documentation](https://support.plex.tv/articles/204059436-finding-an-authentication-token-x-plex-token/).
|
* Refer to the official [plex documentation](https://support.plex.tv/articles/204059436-finding-an-authentication-token-x-plex-token/).
|
||||||
|
|
||||||
Add it to `config/config.yaml` in the appropiate spot.
|
* Add it to `config/config.yaml` in the appropiate spot.
|
||||||
|
|
||||||
5. Start the service:
|
6. Customize remaining settings
|
||||||
|
|
||||||
```
|
Set any remaining settings in the config file that you would like. Such as music library, and base url of the Plex server.
|
||||||
$ docker-compose up --build
|
|
||||||
|
7. Start the service:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
## Logs
|
||||||
|
|
||||||
|
You can view the logs with the following command
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker-compose logs -f CONTAINER_NAME_OR_ID
|
||||||
|
|
||||||
|
# For example
|
||||||
|
docker-compose logs -f PlexBot
|
||||||
```
|
```
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
```
|
```text
|
||||||
General:
|
General:
|
||||||
kill - Stop the bot.
|
kill - Stop the bot.
|
||||||
Plex:
|
Plex:
|
||||||
@ -71,11 +128,4 @@ Type ?help command for more info on a command.
|
|||||||
You can also type ?help category for more info on a category.
|
You can also type ?help category for more info on a category.
|
||||||
```
|
```
|
||||||
|
|
||||||
## Support
|
|
||||||
|
|
||||||
Reach out to me at one of the following places!
|
|
||||||
|
|
||||||
- Email (Best) at joshua.gf.arul@gmail.com
|
|
||||||
- Twitter at <a href="http://twitter.com/jarulsamy_" target="_blank">`@jarulsamy_`</a>
|
|
||||||
|
|
||||||
* * *
|
* * *
|
||||||
|
BIN
assets/screenshot.png
Normal file
BIN
assets/screenshot.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 17 KiB |
@ -1,8 +0,0 @@
|
|||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
sys.path.append("PlexBot")
|
|
||||||
|
|
||||||
from __version__ import VERSION
|
|
||||||
|
|
||||||
sys.exit(os.system(f"docker build -t jarulsamy/plex-bot:{VERSION} ."))
|
|
14
deploy/build.sh
Executable file
14
deploy/build.sh
Executable file
@ -0,0 +1,14 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
VERSION=$(python PlexBot/__version__.py)
|
||||||
|
|
||||||
|
docker build -t "jarulsamy/plex-bot:$VERSION" .
|
||||||
|
|
||||||
|
if [ $? -eq 0 ]
|
||||||
|
then
|
||||||
|
echo "Successfully build docker image."
|
||||||
|
exit 0
|
||||||
|
else
|
||||||
|
echo "Failed to build docker image." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
@ -1,8 +0,0 @@
|
|||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
sys.path.append("PlexBot")
|
|
||||||
|
|
||||||
from __version__ import VERSION
|
|
||||||
|
|
||||||
sys.exit(os.system(f"docker push jarulsamy/plex-bot:{VERSION}"))
|
|
14
deploy/push.sh
Executable file
14
deploy/push.sh
Executable file
@ -0,0 +1,14 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
VERSION=$(python PlexBot/__version__.py)
|
||||||
|
|
||||||
|
docker push "jarulsamy/plex-bot:$VERSION"
|
||||||
|
|
||||||
|
if [ $? -eq 0 ]
|
||||||
|
then
|
||||||
|
echo "Successfully pushed docker image."
|
||||||
|
exit 0
|
||||||
|
else
|
||||||
|
echo "Failed to push docker image." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
@ -2,7 +2,7 @@ version: "3"
|
|||||||
services:
|
services:
|
||||||
plex-bot:
|
plex-bot:
|
||||||
container_name: "PlexBot"
|
container_name: "PlexBot"
|
||||||
build: .
|
image: jarulsamy/plex-bot:latest
|
||||||
environment:
|
environment:
|
||||||
- PUID=1000
|
- PUID=1000
|
||||||
- PGID=1000
|
- PGID=1000
|
||||||
@ -10,4 +10,4 @@ services:
|
|||||||
# Required dir for configuration files
|
# Required dir for configuration files
|
||||||
volumes:
|
volumes:
|
||||||
- "./config:/config:ro"
|
- "./config:/config:ro"
|
||||||
restart: "no"
|
restart: "unless-stopped"
|
||||||
|
Reference in New Issue
Block a user