Skip to content

Commit

Permalink
Update Omnitron
Browse files Browse the repository at this point in the history
  • Loading branch information
TheophileDiot committed Jul 7, 2023
1 parent b9089db commit 8a1e94d
Show file tree
Hide file tree
Showing 13 changed files with 68 additions and 567 deletions.
9 changes: 5 additions & 4 deletions DockerFile
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
FROM python:3-alpine
FROM python:3.11.4-alpine

COPY requirements.txt /bot/
WORKDIR /bot

RUN apk add --no-cache --virtual deps gcc musl-dev libffi-dev g++ git && \
pip3 install pip --no-cache-dir --upgrade && pip3 install setuptools wheel --no-cache-dir --upgrade && \
pip3 install -r requirements.txt --upgrade
pip install pip --no-cache-dir --upgrade && \
pip install setuptools wheel --no-cache-dir --upgrade && \
MAKEFLAGS="-j $(nproc)" pip install -r requirements.txt --upgrade

COPY *.py /bot/
COPY *.env /bot/

ADD data /bot/data
ADD cogs /bot/cogs

ENTRYPOINT ["/usr/local/bin/python3", "bot.py"]
ENTRYPOINT ["python", "bot.py"]
41 changes: 34 additions & 7 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,16 @@
from asyncio import new_event_loop
from datetime import date
from itertools import chain
from logging import basicConfig, DEBUG, error, info, INFO
from logging import (
Formatter,
StreamHandler,
basicConfig,
DEBUG,
error,
getLogger,
info,
INFO,
)
from multiprocessing import Process
from os import getenv, listdir, makedirs, name, path, system, remove
from subprocess import PIPE, call
Expand All @@ -27,7 +36,7 @@
Message,
OptionType,
)
from disnake.ext.commands import Bot, Context
from disnake.ext.commands import Bot, CommandSyncFlags, Context
from disnake.ext.commands.errors import (
BotMissingPermissions,
BadArgument,
Expand Down Expand Up @@ -68,13 +77,18 @@ class Omnitron(Bot):
def __init__(self, **kwargs):
"""Initialize the bot"""
super().__init__(
command_prefix=Utils.get_guild_pre or BOT_PREFIX,
command_prefix="b!",
intents=self.get_intents(),
help_command=None,
case_insensitive=True,
strip_after_prefix=True,
self_bot=False,
sync_commands_debug=True,
command_sync_flags=CommandSyncFlags(
sync_commands=True,
sync_commands_debug=getenv("ENV") == "DEVELOPMENT",
sync_global_commands=True,
sync_guild_commands=True,
sync_on_cog_actions=getenv("ENV") == "DEVELOPMENT",
),
asyncio_debug=True,
test_guilds=[872500404540280893, 874311358018105385]
if getenv("ENV") == "DEVELOPMENT"
Expand Down Expand Up @@ -401,12 +415,25 @@ async def setup(self, **kwargs):

basicConfig(
filename=f"logs/{date.today().strftime('%d-%m-%Y_')}app.log",
filemode="w" if getenv("ENV") == "DEVELOPMENT" else "a",
filemode="w"
if getenv("ENV") == "DEVELOPMENT"
or not path.exists(f"logs/{date.today().strftime('%d-%m-%Y_')}app.log")
else "a",
format="%(asctime)s - %(levelname)s - %(message)s",
datefmt="%d-%m-%y %H:%M:%S",
datefmt="%d/%m/%Y %H:%M:%S",
level=DEBUG if getenv("ENV") == "DEVELOPMENT" else INFO,
) # Configure the logging

# set up logging to console
console = StreamHandler()
console.setLevel(INFO)
# set a format which is simpler for console use
formatter = Formatter(
"%(asctime)s - %(levelname)s - %(message)s", datefmt="%d/%m/%Y %H:%M:%S"
)
console.setFormatter(formatter)
getLogger("").addHandler(console)

# system("cls" if name == "nt" else "clear")
print("Omnitron is starting...")
loop = new_event_loop()
Expand Down
41 changes: 9 additions & 32 deletions cogs/dj/play.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from asyncio import sleep
from functools import wraps
from inspect import Parameter
from os import getenv
Expand Down Expand Up @@ -34,7 +33,6 @@
from disnake.ext.commands.errors import MissingRequiredArgument
from lavalink import add_event_hook, Client
from lavalink.events import NodeConnectedEvent, QueueEndEvent, TrackEndEvent
from lavalink.exceptions import NodeException
from lavalink.models import AudioTrack

from bot import Omnitron
Expand Down Expand Up @@ -250,7 +248,7 @@ async def check(
player = self.bot.lavalink.player_manager.create(
source.guild.id, endpoint=source.author.voice.channel.rtc_region
)
except NodeException:
except:
if isinstance(source, Context):
return await source.reply(
f"⚠️ - {source.author.mention} - The player is not ready yet, please try again in a few seconds!",
Expand Down Expand Up @@ -388,10 +386,7 @@ async def add_song_to_queue(
yt_infos = self.ytdl.extract_info(track["info"]["uri"], download=False)
except Exception as e:
if not f"{e}".endswith("This video may be inappropriate for some users."):
return await source.followup.send(
f"⚠️ - {source.author.mention} - An error occurred while retrieving the video information ({track['info']['uri']}), please try again in a few moments!",
ephemeral=True,
)
pass
else:
return await source.followup.send(
f"⚠️ - {source.author.mention} - This video is not suitable for some users ({track['info']['uri']})! (I can't play some age restricted videos)",
Expand Down Expand Up @@ -423,7 +418,7 @@ async def add_song_to_queue(
if query and not query.startswith("ytsearch")
else track["info"]["uri"]
)
duration = self.bot.utils_class.duration(track["info"]["length"] / 1000)
duration = self.bot.utils_class.duration(track["info"]["duration"] / 1000)
author = track["info"]["author"]

self.bot.playlists[source.guild.id].append(
Expand Down Expand Up @@ -521,7 +516,6 @@ async def handle_play(
param=Parameter(name="query", kind=Parameter.KEYWORD_ONLY)
)
elif query and audio_file is None:

# Remove leading and trailing <>. <> may be used to suppress embedding links in Discord.
query = query.strip("<>")

Expand Down Expand Up @@ -624,12 +618,7 @@ async def handle_play(

if (
not audio_file
and (
not results
or results
and "exception" in results
or not results["tracks"]
)
and (not results or not results["tracks"])
and query
and query.startswith("ytsearch:")
):
Expand All @@ -644,18 +633,7 @@ async def handle_play(

# Results could be None if Lavalink returns an invalid response (non-JSON/non-200 (OK)).
# ALternatively, results['tracks'] could be an empty array if the query yielded no tracks.
if results and "exception" in results:
if isinstance(source, Context):
return await source.reply(
f"⚠️ - {source.author.mention} - {results['exception']['message']}",
delete_after=20,
)
else:
return await source.followup.send(
f"⚠️ - {source.author.mention} - {results['exception']['message']}",
ephemeral=True,
)
elif not results or not results["tracks"]:
if not results or not results["tracks"]:
if isinstance(source, Context):
return await source.reply(
f"⚠️ - {source.author.mention} - The video or playlist you are looking for does not exist!",
Expand Down Expand Up @@ -712,8 +690,8 @@ async def handle_play(
if not player.is_playing:
await player.play()

if yt_infos:
colour = Colour(0xFF0000) if not spotify_track else Colour(0x1DB954)
colour = Colour(0xFF0000) if not spotify_track else Colour(0x1DB954)
if yt_infos and isinstance(yt_infos, dict):
title = yt_infos["title"]
url = (
yt_infos["webpage_url"]
Expand All @@ -723,7 +701,6 @@ async def handle_play(
duration = self.bot.utils_class.duration(yt_infos["duration"])
author = f"Channel: {yt_infos['channel']}"
else:
colour = self.bot.color
title = (
track["info"]["title"]
if track["info"]["title"] != "Unknown title" or audio_file is None
Expand All @@ -734,7 +711,7 @@ async def handle_play(
if query and not query.startswith("ytsearch")
else track["info"]["uri"]
)
duration = self.bot.utils_class.duration(track["info"]["length"] / 1000)
duration = self.bot.utils_class.duration(track["info"]["duration"] / 1000)
author = track["info"]["author"]

em = Embed(
Expand All @@ -743,7 +720,7 @@ async def handle_play(
url=url,
)

if yt_infos is not None:
if yt_infos and isinstance(yt_infos, dict):
em.set_thumbnail(url=yt_infos["thumbnail"])

em.set_author(name=author)
Expand Down
2 changes: 0 additions & 2 deletions cogs/dj/playlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,6 @@ async def handle_playlist(
if not isinstance(source, Context):
await source.response.defer()

print(self.bot.playlists.get(source.guild.id))

em = Embed(colour=Colour(0xFF0000)) # YTB color

if position is not None:
Expand Down
Loading

0 comments on commit 8a1e94d

Please sign in to comment.