mirror of
https://github.com/jarulsamy/Plex-Bot.git
synced 2024-08-19 15:01:55 +02:00
Compare commits
11 Commits
Author | SHA1 | Date | |
---|---|---|---|
9078ef616a | |||
72935d8c7c | |||
76d2d97c62 | |||
63fea747c6 | |||
d48188870e | |||
64a09def50 | |||
786a7d3742 | |||
5c45500450 | |||
2d633acc67 | |||
257ea91c4c | |||
21c6bcc746 |
17
Dockerfile
17
Dockerfile
@ -1,11 +1,11 @@
|
|||||||
# Python 3.7
|
FROM python:3.7-slim
|
||||||
FROM python:3.7
|
|
||||||
|
|
||||||
# Update system
|
|
||||||
RUN apt-get -y update
|
|
||||||
RUN apt-get -y upgrade
|
|
||||||
# Install ffmpeg
|
# Install ffmpeg
|
||||||
RUN apt-get install -y ffmpeg
|
RUN apt-get -y update && \
|
||||||
|
apt-get install -y --no-install-recommends ffmpeg && \
|
||||||
|
apt-get autoremove -y && \
|
||||||
|
apt-get clean && \
|
||||||
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
# All source code
|
# All source code
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
@ -14,11 +14,10 @@ WORKDIR /src
|
|||||||
COPY requirements.txt .
|
COPY requirements.txt .
|
||||||
|
|
||||||
# Install all dependencies.
|
# Install all dependencies.
|
||||||
RUN pip install -r requirements.txt
|
RUN pip install --only-binary all --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
# Copy PlexBot over to src.
|
# Copy PlexBot over to src.
|
||||||
COPY PlexBot/ PlexBot
|
COPY PlexBot/ PlexBot
|
||||||
|
|
||||||
# Run the bot
|
# Run the bot
|
||||||
# CMD ["python", "-OO", "-m", "PlexBot"]
|
CMD ["python", "-OO", "-m", "PlexBot"]
|
||||||
CMD ["python", "-m", "PlexBot"]
|
|
||||||
|
16
Jenkinsfile
vendored
16
Jenkinsfile
vendored
@ -35,7 +35,7 @@ pipeline {
|
|||||||
echo "Style check"
|
echo "Style check"
|
||||||
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}
|
||||||
pylint CHANGE_ME || true
|
pylint PlexBot || true
|
||||||
'''
|
'''
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -49,9 +49,7 @@ 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}
|
||||||
pwd
|
python deploy/build.py
|
||||||
ls
|
|
||||||
python setup.py bdist_wheel
|
|
||||||
'''
|
'''
|
||||||
}
|
}
|
||||||
post {
|
post {
|
||||||
@ -60,6 +58,7 @@ pipeline {
|
|||||||
archiveArtifacts (allowEmptyArchive: true,
|
archiveArtifacts (allowEmptyArchive: true,
|
||||||
artifacts: 'dist/*whl',
|
artifacts: 'dist/*whl',
|
||||||
fingerprint: true)
|
fingerprint: true)
|
||||||
|
// sh 'python deploy/push.py'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -68,14 +67,7 @@ pipeline {
|
|||||||
post {
|
post {
|
||||||
always {
|
always {
|
||||||
sh 'conda remove --yes -n ${BUILD_TAG} --all'
|
sh 'conda remove --yes -n ${BUILD_TAG} --all'
|
||||||
}
|
sh 'docker system prune -a -f'
|
||||||
failure {
|
|
||||||
emailext (
|
|
||||||
subject: "FAILED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
|
|
||||||
body: """<p>FAILED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
|
|
||||||
<p>Check console output at "<a href='${env.BUILD_URL}'>${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>"</p>""",
|
|
||||||
recipientProviders: [[$class: 'DevelopersRecipientProvider']]
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,7 +8,9 @@ import yaml
|
|||||||
FORMAT = "%(asctime)s %(levelname)s: [%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
|
FORMAT = "%(asctime)s %(levelname)s: [%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
|
||||||
|
|
||||||
logging.basicConfig(format=FORMAT)
|
logging.basicConfig(format=FORMAT)
|
||||||
logger = logging.getLogger("PlexBot")
|
root_log = logging.getLogger()
|
||||||
|
plex_log = logging.getLogger("Plex")
|
||||||
|
bot_log = logging.getLogger("Bot")
|
||||||
|
|
||||||
|
|
||||||
def load_config(filename: str) -> Dict[str, str]:
|
def load_config(filename: str) -> Dict[str, str]:
|
||||||
@ -20,7 +22,7 @@ def load_config(filename: str) -> Dict[str, str]:
|
|||||||
with open(filename, "r") as f:
|
with open(filename, "r") as f:
|
||||||
config = yaml.safe_load(f)
|
config = yaml.safe_load(f)
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
logging.fatal("Configuration file not found.")
|
root_log.fatal("Configuration file not found.")
|
||||||
sys.exit(-1)
|
sys.exit(-1)
|
||||||
|
|
||||||
# Convert str level type to logging constant
|
# Convert str level type to logging constant
|
||||||
@ -31,7 +33,9 @@ def load_config(filename: str) -> Dict[str, str]:
|
|||||||
"ERROR": logging.ERROR,
|
"ERROR": logging.ERROR,
|
||||||
"CRITICAL": logging.CRITICAL,
|
"CRITICAL": logging.CRITICAL,
|
||||||
}
|
}
|
||||||
level = config["general"]["log_level"]
|
|
||||||
config["general"]["log_level"] = levels[level.upper()]
|
config["root"]["log_level"] = levels[config["root"]["log_level"].upper()]
|
||||||
|
config["plex"]["log_level"] = levels[config["plex"]["log_level"].upper()]
|
||||||
|
config["discord"]["log_level"] = levels[config["discord"]["log_level"].upper()]
|
||||||
|
|
||||||
return config
|
return config
|
||||||
|
@ -16,12 +16,14 @@ TOKEN = config["discord"]["token"]
|
|||||||
BASE_URL = config["plex"]["base_url"]
|
BASE_URL = config["plex"]["base_url"]
|
||||||
PLEX_TOKEN = config["plex"]["token"]
|
PLEX_TOKEN = config["plex"]["token"]
|
||||||
LIBRARY_NAME = config["plex"]["library_name"]
|
LIBRARY_NAME = config["plex"]["library_name"]
|
||||||
LOG_LEVEL = config["general"]["log_level"]
|
|
||||||
|
|
||||||
# Set appropiate log level
|
# Set appropiate log level
|
||||||
logger = logging.getLogger("PlexBot")
|
root_log = logging.getLogger()
|
||||||
logging.basicConfig(format=FORMAT)
|
plex_log = logging.getLogger("Plex")
|
||||||
logger.setLevel(LOG_LEVEL)
|
bot_log = logging.getLogger("Bot")
|
||||||
|
|
||||||
|
plex_log.setLevel(config["plex"]["log_level"])
|
||||||
|
bot_log.setLevel(config["discord"]["log_level"])
|
||||||
|
|
||||||
bot = Bot(command_prefix=BOT_PREFIX)
|
bot = Bot(command_prefix=BOT_PREFIX)
|
||||||
bot.add_cog(General(bot))
|
bot.add_cog(General(bot))
|
||||||
|
1
PlexBot/__version__.py
Normal file
1
PlexBot/__version__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
VERSION = "0.0.4"
|
@ -12,7 +12,9 @@ from fuzzywuzzy import fuzz
|
|||||||
from plexapi.exceptions import Unauthorized
|
from plexapi.exceptions import Unauthorized
|
||||||
from plexapi.server import PlexServer
|
from plexapi.server import PlexServer
|
||||||
|
|
||||||
logger = logging.getLogger("PlexBot")
|
root_log = logging.getLogger()
|
||||||
|
plex_log = logging.getLogger("Plex")
|
||||||
|
bot_log = logging.getLogger("Bot")
|
||||||
|
|
||||||
|
|
||||||
class General(commands.Cog):
|
class General(commands.Cog):
|
||||||
@ -20,10 +22,28 @@ class General(commands.Cog):
|
|||||||
self.bot = bot
|
self.bot = bot
|
||||||
|
|
||||||
@command()
|
@command()
|
||||||
async def kill(self, ctx):
|
async def kill(self, ctx, *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()
|
||||||
logger.info(f"Stopping upon the request of {ctx.author.mention}")
|
bot_log.info(f"Stopping upon the request of {ctx.author.mention}")
|
||||||
|
|
||||||
|
@command()
|
||||||
|
async def cleanup(self, ctx, limit=250):
|
||||||
|
channel = ctx.message.channel
|
||||||
|
|
||||||
|
try:
|
||||||
|
async for i in channel.history(limit=limit):
|
||||||
|
# Only delete messages sent by self
|
||||||
|
if i.author == self.bot.user:
|
||||||
|
try:
|
||||||
|
await i.delete()
|
||||||
|
except (discord.Forbidden, discord.NotFound, discord.HTTPException):
|
||||||
|
pass
|
||||||
|
|
||||||
|
except discord.Forbidden:
|
||||||
|
await ctx.send("I don't have the necessary permissions to delete messages.")
|
||||||
|
|
||||||
|
|
||||||
class Plex(commands.Cog):
|
class Plex(commands.Cog):
|
||||||
@ -37,19 +57,22 @@ class Plex(commands.Cog):
|
|||||||
try:
|
try:
|
||||||
self.pms = PlexServer(self.base_url, self.plex_token)
|
self.pms = PlexServer(self.base_url, self.plex_token)
|
||||||
except Unauthorized:
|
except Unauthorized:
|
||||||
logger.fatal("Invalid Plex token, stopping...")
|
plex_log.fatal("Invalid Plex token, stopping...")
|
||||||
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}")
|
||||||
|
|
||||||
self.vc = None
|
self.vc = None
|
||||||
self.current_track = None
|
self.current_track = None
|
||||||
|
self.np_message_id = None
|
||||||
|
|
||||||
self.play_queue = asyncio.Queue()
|
self.play_queue = asyncio.Queue()
|
||||||
self.play_next_event = asyncio.Event()
|
self.play_next_event = asyncio.Event()
|
||||||
|
|
||||||
self.bot.loop.create_task(self._audio_player_task())
|
self.bot.loop.create_task(self._audio_player_task())
|
||||||
|
|
||||||
logger.info("Started bot successfully")
|
bot_log.info("Started bot successfully")
|
||||||
|
|
||||||
def _search_tracks(self, title):
|
def _search_tracks(self, title):
|
||||||
tracks = self.music.searchTracks()
|
tracks = self.music.searchTracks()
|
||||||
@ -64,11 +87,6 @@ class Plex(commands.Cog):
|
|||||||
|
|
||||||
return score[0]
|
return score[0]
|
||||||
|
|
||||||
@command()
|
|
||||||
async def hello(self, ctx, *, member: discord.member = None):
|
|
||||||
member = member or ctx.author
|
|
||||||
await ctx.send(f"Hello {member}")
|
|
||||||
|
|
||||||
async def _play(self):
|
async def _play(self):
|
||||||
track_url = self.current_track.getStreamURL()
|
track_url = self.current_track.getStreamURL()
|
||||||
audio_stream = FFmpegPCMAudio(track_url)
|
audio_stream = FFmpegPCMAudio(track_url)
|
||||||
@ -78,11 +96,10 @@ class Plex(commands.Cog):
|
|||||||
|
|
||||||
self.vc.play(audio_stream, after=self._toggle_next)
|
self.vc.play(audio_stream, after=self._toggle_next)
|
||||||
|
|
||||||
logger.debug(f"Playing {self.current_track.title}")
|
plex_log.debug(f"{self.current_track.title} - URL: {track_url}")
|
||||||
logger.debug(f"URL: {track_url}")
|
|
||||||
|
|
||||||
embed, f = self._build_embed(self.current_track)
|
embed, f = self._build_embed(self.current_track)
|
||||||
await self.ctx.send(embed=embed, file=f)
|
self.np_message_id = await self.ctx.send(embed=embed, file=f)
|
||||||
|
|
||||||
async def _audio_player_task(self):
|
async def _audio_player_task(self):
|
||||||
while True:
|
while True:
|
||||||
@ -101,6 +118,7 @@ class Plex(commands.Cog):
|
|||||||
|
|
||||||
await self._play()
|
await self._play()
|
||||||
await self.play_next_event.wait()
|
await self.play_next_event.wait()
|
||||||
|
await self.np_message_id.delete()
|
||||||
|
|
||||||
def _toggle_next(self, error=None):
|
def _toggle_next(self, error=None):
|
||||||
self.current_track = None
|
self.current_track = None
|
||||||
@ -134,13 +152,18 @@ 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}")
|
||||||
|
|
||||||
return embed, f
|
return embed, f
|
||||||
|
|
||||||
@command()
|
@command()
|
||||||
async def play(self, ctx, *args):
|
async def play(self, ctx, *args):
|
||||||
|
# Save the context to use with async callbacks
|
||||||
|
self.ctx = ctx
|
||||||
|
|
||||||
if not len(args):
|
if not len(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")
|
||||||
return
|
return
|
||||||
|
|
||||||
title = " ".join(args)
|
title = " ".join(args)
|
||||||
@ -149,24 +172,26 @@ 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}")
|
||||||
return
|
return
|
||||||
|
|
||||||
# Fail if user not in vc
|
# Fail if user not in vc
|
||||||
elif not ctx.author.voice:
|
elif 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")
|
||||||
return
|
return
|
||||||
|
|
||||||
# Connect to voice if not already
|
# Connect to voice if not already
|
||||||
if not self.vc:
|
if not self.vc:
|
||||||
self.vc = await ctx.author.voice.channel.connect()
|
self.vc = await ctx.author.voice.channel.connect()
|
||||||
logger.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.vc.is_playing():
|
||||||
|
bot_log.debug(f"Added to queue - {title}")
|
||||||
embed, f = self._build_embed(track, t="queue")
|
embed, f = self._build_embed(track, t="queue")
|
||||||
await ctx.send(embed=embed, file=f)
|
await ctx.send(embed=embed, file=f)
|
||||||
|
|
||||||
# Save the context to use with async callbacks
|
|
||||||
self.ctx = ctx
|
|
||||||
# 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)
|
||||||
|
|
||||||
@ -177,34 +202,45 @@ class Plex(commands.Cog):
|
|||||||
await self.vc.disconnect()
|
await self.vc.disconnect()
|
||||||
self.vc = None
|
self.vc = None
|
||||||
self.ctx = None
|
self.ctx = None
|
||||||
|
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:
|
if self.vc:
|
||||||
self.vc.pause()
|
self.vc.pause()
|
||||||
|
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:
|
if self.vc:
|
||||||
self.vc.resume()
|
self.vc.resume()
|
||||||
|
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):
|
||||||
logger.debug("Skip")
|
bot_log.debug("Skip")
|
||||||
if self.vc:
|
if self.vc:
|
||||||
self.vc.stop()
|
self.vc.stop()
|
||||||
|
bot_log.debug("Skipped")
|
||||||
self._toggle_next()
|
self._toggle_next()
|
||||||
|
|
||||||
@command()
|
@command()
|
||||||
async def np(self, ctx):
|
async def np(self, ctx):
|
||||||
if self.current_track:
|
if self.current_track:
|
||||||
embed, f = self._build_embed(self.current_track)
|
embed, f = self._build_embed(self.current_track)
|
||||||
await ctx.send(embed=embed, file=f)
|
bot_log.debug("Now playing")
|
||||||
|
if self.np_message_id:
|
||||||
|
await self.np_message_id.delete()
|
||||||
|
bot_log("Deleted old np status")
|
||||||
|
|
||||||
|
bot_log("Created np status")
|
||||||
|
self.np_message_id = await ctx.send(embed=embed, file=f)
|
||||||
|
|
||||||
@command()
|
@command()
|
||||||
async def clear(self, ctx):
|
async def clear(self, ctx):
|
||||||
self.play_queue = asyncio.Queue()
|
self.play_queue = asyncio.Queue()
|
||||||
|
bot_log.debug("Cleared queue")
|
||||||
await ctx.send(":boom: Queue cleared.")
|
await ctx.send(":boom: Queue cleared.")
|
||||||
|
8
deploy/build.py
Normal file
8
deploy/build.py
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.append("PlexBot")
|
||||||
|
|
||||||
|
from __version__ import VERSION
|
||||||
|
|
||||||
|
sys.exit(os.system(f"docker build -t jarulsamy/plex-bot:{VERSION} ."))
|
8
deploy/push.py
Executable file
8
deploy/push.py
Executable file
@ -0,0 +1,8 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.append("PlexBot")
|
||||||
|
|
||||||
|
from __version__ import VERSION
|
||||||
|
|
||||||
|
sys.exit(os.system(f"docker push jarulsamy/plex-bot:{VERSION}"))
|
@ -1,7 +1,6 @@
|
|||||||
discord.py==1.3.4
|
discord.py==1.3.4
|
||||||
PlexAPI==4.0.0
|
PlexAPI==4.0.0
|
||||||
fuzzywuzzy==0.18.0
|
fuzzywuzzy==0.18.0
|
||||||
python-Levenshtein==0.12.0
|
|
||||||
pynacl==1.4.0
|
pynacl==1.4.0
|
||||||
ffmpeg==1.4
|
ffmpeg==1.4
|
||||||
PyYAML==5.3.1
|
PyYAML==5.3.1
|
||||||
|
@ -1,12 +1,13 @@
|
|||||||
general:
|
root:
|
||||||
# Options: debug, info, warning, error, critical
|
|
||||||
log_level: "info"
|
log_level: "info"
|
||||||
|
|
||||||
discord:
|
discord:
|
||||||
prefix: "?"
|
prefix: "?"
|
||||||
token: "<BOT_TOKEN>"
|
token: "<BOT_TOKEN>"
|
||||||
|
log_level: "debug"
|
||||||
|
|
||||||
plex:
|
plex:
|
||||||
base_url: "<BASE_URL>"
|
base_url: "<BASE_URL>"
|
||||||
token: "<PLEX_TOKEN>"
|
token: "<PLEX_TOKEN>"
|
||||||
library_name: "<LIBRARY_NAME>"
|
library_name: "<LIBRARY_NAME>"
|
||||||
|
log_level: "debug"
|
||||||
|
Reference in New Issue
Block a user