🔊 Add basic logging

This commit is contained in:
Joshua Arulsamy 2020-07-26 22:08:00 -06:00
parent 4043c972c0
commit ac25330f70
4 changed files with 71 additions and 8 deletions

View File

@ -1,8 +1,36 @@
import yaml
from pathlib import Path
from typing import Dict
import logging
import sys
FORMAT = "%(asctime)s %(levelname)s: [%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
logging.basicConfig(format=FORMAT)
logger = logging.getLogger("PlexBot")
def load_config(filename: str) -> None:
def load_config(filename: str) -> Dict[str, str]:
# All config files should be in /config
# for docker deployment.
filename = Path("/config", filename)
try:
with open(filename, "r") as f:
config = yaml.safe_load(f)
except FileNotFoundError:
logging.fatal("Configuration file not found.")
sys.exit(-1)
# Convert str level type to logging constant
levels = {
"DEBUG": logging.DEBUG,
"INFO": logging.INFO,
"WARNING": logging.WARNING,
"ERROR": logging.ERROR,
"CRITICAL": logging.CRITICAL,
}
level = config["general"]["log_level"]
config["general"]["log_level"] = levels[level.upper()]
return config

View File

@ -3,7 +3,11 @@ from discord.ext.commands import Bot
from .bot import General
from .bot import Plex
from PlexBot import load_config
from . import FORMAT
import logging
# Load config from file
config = load_config("config.yaml")
BOT_PREFIX = config["discord"]["prefix"]
@ -12,6 +16,12 @@ TOKEN = config["discord"]["token"]
BASE_URL = config["plex"]["base_url"]
PLEX_TOKEN = config["plex"]["token"]
LIBRARY_NAME = config["plex"]["library_name"]
LOG_LEVEL = config["general"]["log_level"]
# Set appropiate log level
logger = logging.getLogger("PlexBot")
logging.basicConfig(format=FORMAT)
logger.setLevel(LOG_LEVEL)
bot = Bot(command_prefix=BOT_PREFIX)
bot.add_cog(General(bot))

View File

@ -7,6 +7,10 @@ from discord.ext.commands import command
from fuzzywuzzy import fuzz
from plexapi.server import PlexServer
import logging
logger = logging.getLogger("PlexBot")
class General(commands.Cog):
def __init__(self, bot):
@ -16,6 +20,7 @@ class General(commands.Cog):
async def kill(self, ctx):
await ctx.send(f"Stopping upon the request of {ctx.author.mention}")
await self.bot.close()
logger.info(f"Stopping upon the request of {ctx.author.mention}")
class Plex(commands.Cog):
@ -29,7 +34,11 @@ class Plex(commands.Cog):
self.music = self.pms.library.section(self.library_name)
self.vc = None
self.current_track = None
self.play_queue = Queue()
logger.info("Started bot successfully")
# self.callback_ctx = None
def _search_tracks(self, title):
@ -51,9 +60,13 @@ class Plex(commands.Cog):
await ctx.send(f"Hello {member}")
async def _after_callback(self, error=None):
if self.play_queue.empty():
self.current_track = None
else:
track = self.play_queue.get()
audio_stream = FFmpegPCMAudio(track.getStreamURL())
self.vc.play(audio_stream)
self.current_track = track
await self.callback_ctx.send(f"Playing {track.title}")
@command()
@ -67,16 +80,21 @@ class Plex(commands.Cog):
return
if not self.vc:
self.vc = await ctx.author.voice.channel.connect()
logger.debug("Connected to vc")
if self.vc.is_playing():
self.play_queue.put(track)
self.callback_ctx = ctx
await ctx.send(f"Added {track.title} to queue.")
logger.debug(f"Added {track.title} to queue.")
else:
audio_stream = FFmpegPCMAudio(track_url)
self.vc.play(audio_stream, after=self._after_callback)
self.current_track = track
logger.debug(f"Playing {track.title}")
await ctx.send(f"Playing {track.title}")
else:
logger.debug(f"{title} was not found.")
await ctx.send("Song not found!")
@command()
@ -85,7 +103,6 @@ class Plex(commands.Cog):
self.vc.stop()
await self.vc.disconnect()
self.vc = None
await ctx.send("Stopped")
@command()
@ -106,3 +123,7 @@ class Plex(commands.Cog):
await self.vc.stop()
if not self.play_queue.empty():
await self._after_callback()
@command()
async def np(self, ctx):
await ctx.send(f"Currently playing: {self.current_track.title}")

View File

@ -1,3 +1,7 @@
general:
# Options: debug, info, warning, error, critical
log_level: "info"
discord:
prefix: "?"
token: "<BOT_TOKEN>"