rebuild bot and reimplement boice based on lavalink
This commit is contained in:
parent
bb4ed90e4b
commit
9cfb027385
18 changed files with 804 additions and 683 deletions
|
|
@ -1,17 +1,24 @@
|
|||
from radioCommands import *
|
||||
startuptime = time()
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
|
||||
@bot.slash_command(description="Print information about the bot")
|
||||
import nextcord
|
||||
|
||||
import runtime
|
||||
from utils import interaction_log_context, send_response
|
||||
|
||||
|
||||
startuptime = runtime.time()
|
||||
|
||||
|
||||
@runtime.bot.slash_command(description="Print information about the bot")
|
||||
async def about(interaction: nextcord.Interaction):
|
||||
global startuptime
|
||||
difference = int(round(time() - startuptime))
|
||||
uptime = str(timedelta(seconds=difference))
|
||||
uptime = str(timedelta(seconds=int(round(runtime.time() - startuptime))))
|
||||
logging.getLogger("discordyoutubemonitor.commands.about").info("About requested: %s", interaction_log_context(interaction))
|
||||
|
||||
embed = nextcord.Embed(title="About DJ Bot", url="https://jonasled.de", color=0xff0000)
|
||||
embed.add_field(name="Support", value=f"<@{adminUserID}>", inline=True)
|
||||
embed.add_field(name="Support", value=f"<@{runtime.adminUserID}>", inline=True)
|
||||
embed.add_field(name="Darley Jefferson", value="youtube.com/c/DarleyJefferson", inline=True)
|
||||
embed.add_field(name="Uptime", value=uptime, inline=True)
|
||||
embed.add_field(name="Servers", value=str(len(bot.guilds)), inline=True)
|
||||
embed.add_field(name="Invite", value=inviteURL, inline=True)
|
||||
embed.add_field(name="Servers", value=str(len(runtime.bot.guilds)), inline=True)
|
||||
embed.add_field(name="Invite", value=runtime.inviteURL, inline=True)
|
||||
await send_response(interaction, embed=embed)
|
||||
|
|
|
|||
75
app/bot.py
75
app/bot.py
|
|
@ -1,60 +1,75 @@
|
|||
#!/usr/bin/env python3
|
||||
from heartBeatTask import *
|
||||
import runtime
|
||||
|
||||
logger.info("Welcome to DJ Bot, initializing files")
|
||||
import aboutCommand # noqa: F401
|
||||
import generalCommands # noqa: F401
|
||||
import monitorCommands # noqa: F401
|
||||
import radioCommands # noqa: F401
|
||||
from checkVideos import checkVideos
|
||||
from heartBeatTask import hearBeat
|
||||
from radioTask import checkForNextTrack
|
||||
from utils import interaction_log_context, log_exception, send_response
|
||||
|
||||
@bot.event # print the username and id to the console and change the game status
|
||||
|
||||
runtime.logger.info("Welcome to DJ Bot, initializing files")
|
||||
runtime.initialize_dummy_players()
|
||||
runtime.logger.info("Dummy player state generated")
|
||||
|
||||
|
||||
@runtime.bot.event
|
||||
async def on_ready():
|
||||
logger.info("Startup complete, logged in as %s (%s)", bot.user.name, bot.user.id)
|
||||
logger.info("Connected to %s guilds", len(bot.guilds))
|
||||
# change the presence of the bot to listening the custom status text
|
||||
await bot.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.listening, name=status))
|
||||
logger.info("Presence updated to listening status '%s'", status)
|
||||
await runtime.connect_lavalink()
|
||||
runtime.logger.info("Startup complete, logged in as %s (%s)", runtime.bot.user.name, runtime.bot.user.id)
|
||||
runtime.logger.info("Connected to %s guilds", len(runtime.bot.guilds))
|
||||
await runtime.bot.change_presence(
|
||||
activity=runtime.nextcord.Activity(type=runtime.nextcord.ActivityType.listening, name=runtime.status)
|
||||
)
|
||||
runtime.logger.info("Presence updated to listening status '%s'", runtime.status)
|
||||
|
||||
|
||||
@bot.event
|
||||
@runtime.bot.event
|
||||
async def on_guild_join(guild):
|
||||
logger.info("Joined guild %s (%s) with %s members", guild.name, guild.id, guild.member_count)
|
||||
runtime.logger.info("Joined guild %s (%s) with %s members", guild.name, guild.id, guild.member_count)
|
||||
|
||||
|
||||
@bot.event
|
||||
@runtime.bot.event
|
||||
async def on_guild_remove(guild):
|
||||
logger.info("Removed from guild %s (%s)", guild.name, guild.id)
|
||||
runtime.logger.info("Removed from guild %s (%s)", guild.name, guild.id)
|
||||
|
||||
|
||||
@bot.event
|
||||
@runtime.bot.event
|
||||
async def on_application_command(interaction):
|
||||
logger.info("Slash command received: %s", interaction_log_context(interaction))
|
||||
runtime.logger.info("Slash command received: %s", interaction_log_context(interaction))
|
||||
|
||||
|
||||
@bot.event
|
||||
@runtime.bot.event
|
||||
async def on_application_command_error(interaction, error):
|
||||
if isinstance(error, PermissionError):
|
||||
logger.warning("Permission denied: %s error=%s", interaction_log_context(interaction), error)
|
||||
runtime.logger.warning("Permission denied: %s error=%s", interaction_log_context(interaction), error)
|
||||
await send_response(interaction, str(error), ephemeral=True)
|
||||
return
|
||||
if isinstance(error, ValueError):
|
||||
logger.warning("Invalid slash command usage: %s error=%s", interaction_log_context(interaction), error)
|
||||
runtime.logger.warning("Invalid slash command usage: %s error=%s", interaction_log_context(interaction), error)
|
||||
await send_response(interaction, str(error), ephemeral=True)
|
||||
return
|
||||
log_exception("Unhandled application command error: %s error=%s", interaction_log_context(interaction), error)
|
||||
await send_response(interaction, "An unexpected error occurred while running this command.", ephemeral=True)
|
||||
|
||||
|
||||
async def checkVideosTask(): # run every hour the checkVideos task
|
||||
await bot.wait_until_ready()
|
||||
logger.info("Video monitor loop started with %s minute interval", updateInterval)
|
||||
async def checkVideosTask():
|
||||
await runtime.bot.wait_until_ready()
|
||||
runtime.logger.info("Video monitor loop started with %s minute interval", runtime.updateInterval)
|
||||
while True:
|
||||
logger.debug("Starting scheduled video check run")
|
||||
await checkVideos() # run the task
|
||||
logger.debug("Scheduled video check run completed")
|
||||
await sleep(updateInterval*60) # wait the update interval time
|
||||
runtime.logger.debug("Starting scheduled video check run")
|
||||
await checkVideos()
|
||||
runtime.logger.debug("Scheduled video check run completed")
|
||||
await runtime.sleep(runtime.updateInterval * 60)
|
||||
|
||||
logger.info("Commands loaded, starting monitor task")
|
||||
bot.loop.create_task(checkVideosTask()) # create the monitoring task
|
||||
logger.info("Monitor task started, starting player task")
|
||||
bot.loop.create_task(checkForNextTrack()) # create the radio task
|
||||
|
||||
logger.info("All tasks started, starting heartbeat and bot login")
|
||||
runtime.logger.info("Commands loaded, starting monitor task")
|
||||
runtime.bot.loop.create_task(checkVideosTask())
|
||||
runtime.logger.info("Monitor task started, starting player task")
|
||||
runtime.bot.loop.create_task(checkForNextTrack())
|
||||
runtime.logger.info("All tasks started, starting heartbeat and bot login")
|
||||
hearBeat.start()
|
||||
bot.run(token) # start the bot with the options in config.py
|
||||
runtime.bot.run(runtime.token)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,12 @@
|
|||
from generalCommands import *
|
||||
from datetime import datetime
|
||||
from time import time
|
||||
import logging
|
||||
|
||||
import nextcord
|
||||
|
||||
import runtime
|
||||
from utils import log_exception
|
||||
|
||||
|
||||
video_logger = logging.getLogger("discordyoutubemonitor.video")
|
||||
recent_notifications = {}
|
||||
|
|
@ -7,7 +15,7 @@ recent_notifications = {}
|
|||
def should_send_block_notification(channel_id, video_id, blocked_state):
|
||||
notification_key = (channel_id, video_id, blocked_state)
|
||||
now = time()
|
||||
window_seconds = max(updateInterval * 60, 60)
|
||||
window_seconds = max(runtime.updateInterval * 60, 60)
|
||||
|
||||
expired_keys = [key for key, timestamp in recent_notifications.items() if now - timestamp > window_seconds]
|
||||
for key in expired_keys:
|
||||
|
|
@ -20,176 +28,158 @@ def should_send_block_notification(channel_id, video_id, blocked_state):
|
|||
recent_notifications[notification_key] = now
|
||||
return True
|
||||
|
||||
|
||||
async def checkVideo(results):
|
||||
global apikeyID
|
||||
global dbconnection
|
||||
try:
|
||||
dbconnection.ping(reconnect=True)
|
||||
runtime.dbconnection.ping(reconnect=True)
|
||||
except Exception:
|
||||
dbconnection = pymysql.connect(
|
||||
host=mysqlHostname,
|
||||
user=mysqlUsername,
|
||||
password=mysqlPassword,
|
||||
database=mysqlDatabase,
|
||||
runtime.dbconnection = runtime.pymysql.connect(
|
||||
host=runtime.mysqlHostname,
|
||||
user=runtime.mysqlUsername,
|
||||
password=runtime.mysqlPassword,
|
||||
database=runtime.mysqlDatabase,
|
||||
autocommit=True,
|
||||
)
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
await sleep(1)
|
||||
repeat = True # this is used to repeat the get request if the key limit is reached
|
||||
startKeyID = apikeyID # save the current ID
|
||||
while (repeat):
|
||||
await sleep(1)
|
||||
video = getr(
|
||||
"https://www.googleapis.com/youtube/v3/videos?part=contentDetails,statistics&id=" +
|
||||
results['videoID'] + "&key=" + apikey[
|
||||
apikeyID]) # get the block list via the Youtube Data API V3
|
||||
video_logger.debug("Loading video metadata for video=%s key_index=%s", results['videoID'], apikeyID)
|
||||
if (video.status_code == 403): # check if the status code is 403 (access denies)
|
||||
video_logger.warning("YouTube API quota reached for key index %s, rotating key", apikeyID)
|
||||
apikeyID = apikeyID + 1 # if yes use the next apiKey
|
||||
# if the current APIkey is the last one in the array, use the first one
|
||||
if (apikeyID >= len(apikey)):
|
||||
apikeyID = 0
|
||||
if (startKeyID == apikeyID):
|
||||
await bot.get_user(adminUserID).send("used up all API keys for YouTube, please add more")
|
||||
await runtime.sleep(1)
|
||||
repeat = True
|
||||
startKeyID = runtime.apikeyID
|
||||
while repeat:
|
||||
await runtime.sleep(1)
|
||||
video = runtime.getr(
|
||||
"https://www.googleapis.com/youtube/v3/videos?part=contentDetails,statistics&id="
|
||||
+ results["videoID"]
|
||||
+ "&key="
|
||||
+ runtime.apikey[runtime.apikeyID]
|
||||
)
|
||||
video_logger.debug("Loading video metadata for video=%s key_index=%s", results["videoID"], runtime.apikeyID)
|
||||
if video.status_code == 403:
|
||||
video_logger.warning("YouTube API quota reached for key index %s, rotating key", runtime.apikeyID)
|
||||
runtime.apikeyID += 1
|
||||
if runtime.apikeyID >= len(runtime.apikey):
|
||||
runtime.apikeyID = 0
|
||||
if startKeyID == runtime.apikeyID:
|
||||
await runtime.bot.get_user(runtime.adminUserID).send("used up all API keys for YouTube, please add more")
|
||||
video_logger.error("All YouTube API keys are exhausted")
|
||||
return # we can stop here, the bot will hang here
|
||||
return
|
||||
else:
|
||||
repeat = False
|
||||
# load the json response in the json library
|
||||
video = loads(video.text)
|
||||
|
||||
try: # check if the video exists
|
||||
await sleep(1)
|
||||
# if the video doesn't exist, delete it
|
||||
if (video["pageInfo"]["totalResults"] == 0):
|
||||
# Video got deleted, we can stop monitoring
|
||||
dbcursor.execute(
|
||||
"UPDATE VIDEOS SET videoAvailable=0 WHERE id = %s", [results['id']])
|
||||
video = runtime.loads(video.text)
|
||||
|
||||
try:
|
||||
await runtime.sleep(1)
|
||||
if video["pageInfo"]["totalResults"] == 0:
|
||||
dbcursor.execute("UPDATE VIDEOS SET videoAvailable=0 WHERE id = %s", [results["id"]])
|
||||
|
||||
# get the blocked countries (as array)
|
||||
blockedCountries = video["items"][0]["contentDetails"]["regionRestriction"]["blocked"]
|
||||
blocked = ""
|
||||
# rotate through the countries and build the String for the embed
|
||||
for countries in sorted(blockedCountries):
|
||||
# decode the country code and add a ", " to the end (for the next entry)
|
||||
blocked = blocked + \
|
||||
countryDecode.get(alpha_2=countries).name + ", "
|
||||
blocked = blocked[:-2] # remove the last ", "
|
||||
# we define blocked in more than 200 countries means worldwide
|
||||
if (len(blockedCountries) > 200):
|
||||
for country in sorted(blockedCountries):
|
||||
blocked = blocked + runtime.countryDecode.get(alpha_2=country).name + ", "
|
||||
blocked = blocked[:-2]
|
||||
if len(blockedCountries) > 200:
|
||||
blocked = "worldwide"
|
||||
# if we can't find the "blocked" tag in the json, no country is blocked yet
|
||||
except:
|
||||
video_logger.warning("Failed fetching region restriction data for video=%s", results['videoID'])
|
||||
except Exception:
|
||||
video_logger.warning("Failed fetching region restriction data for video=%s", results["videoID"])
|
||||
blocked = "no countries yet"
|
||||
await sleep(1)
|
||||
# check if we have a change in the blocked countries
|
||||
resultList = set(results['blockedIn'].split(", "))
|
||||
resultList2 = set(blocked.split(", "))
|
||||
if (resultList != resultList2):
|
||||
video_logger.info("Blocklist diff detected for video=%s old=%s new=%s", results['videoID'], results['blockedIn'], blocked)
|
||||
dbcursor.execute("UPDATE VIDEOS SET blockedIn = %s WHERE id = %s", [
|
||||
blocked, results['id']]) # if yes update the database
|
||||
|
||||
await sleep(1)
|
||||
try: # try to update the embed, this can fail if the message got deleted
|
||||
# get the message via the channelID and the message ID from the database
|
||||
message = await bot.get_channel(results['channelID']).fetch_message(results['messageID'])
|
||||
embed = message.embeds[0] # get the embed from the message
|
||||
# update the blocked in field
|
||||
await runtime.sleep(1)
|
||||
previous_state = set(results["blockedIn"].split(", "))
|
||||
next_state = set(blocked.split(", "))
|
||||
if previous_state != next_state:
|
||||
video_logger.info(
|
||||
"Blocklist diff detected for video=%s old=%s new=%s",
|
||||
results["videoID"],
|
||||
results["blockedIn"],
|
||||
blocked,
|
||||
)
|
||||
dbcursor.execute("UPDATE VIDEOS SET blockedIn = %s WHERE id = %s", [blocked, results["id"]])
|
||||
|
||||
await runtime.sleep(1)
|
||||
try:
|
||||
channel = runtime.bot.get_channel(results["channelID"])
|
||||
message = await channel.fetch_message(results["messageID"])
|
||||
embed = message.embeds[0]
|
||||
embed.set_field_at(0, name="Blocked in", value=blocked)
|
||||
await message.edit(embed=embed) # send the updated embed
|
||||
# if it's not the update from "waiting for data" to "no countries yet" then send a @here message to notify everyone
|
||||
if (blocked != "no countries yet"):
|
||||
dbcursor.execute(
|
||||
"SELECT * FROM monitorConfig WHERE Server=" + str(
|
||||
bot.get_channel(results['channelID']).guild.id))
|
||||
if (dbcursor.fetchone() == None):
|
||||
dbcursor.execute(
|
||||
"INSERT INTO monitorConfig (Server) VALUES (" + str(
|
||||
bot.get_channel(results['channelID']).guild.id) + ")")
|
||||
await message.edit(embed=embed)
|
||||
|
||||
dbcursor.execute("SELECT * FROM monitorConfig WHERE Server=" + str(
|
||||
bot.get_channel(results['channelID']).guild.id))
|
||||
if blocked != "no countries yet":
|
||||
dbcursor.execute("SELECT * FROM monitorConfig WHERE Server=%s", [channel.guild.id])
|
||||
if dbcursor.fetchone() is None:
|
||||
dbcursor.execute("INSERT INTO monitorConfig (Server) VALUES (%s)", [channel.guild.id])
|
||||
|
||||
dbcursor.execute("SELECT * FROM monitorConfig WHERE Server=%s", [channel.guild.id])
|
||||
result2 = dbcursor.fetchone()
|
||||
if should_send_block_notification(results['channelID'], results['videoID'], blocked):
|
||||
await bot.get_channel(results['channelID']).send(result2['pingMessage'])
|
||||
if should_send_block_notification(results["channelID"], results["videoID"], blocked):
|
||||
await channel.send(result2["pingMessage"])
|
||||
else:
|
||||
video_logger.info(
|
||||
"Skipping duplicate block notification for video=%s channel=%s state=%s",
|
||||
results['videoID'],
|
||||
results['channelID'],
|
||||
results["videoID"],
|
||||
results["channelID"],
|
||||
blocked,
|
||||
)
|
||||
if (blocked == "worldwide"):
|
||||
dbcursor.execute(
|
||||
"DELETE FROM VIDEOS WHERE id = %s", [results['id']])
|
||||
except: # skip if error occurs
|
||||
log_exception("Failed to update changed monitor embed for video=%s", results['videoID'])
|
||||
try: # try to update the embed, this can fail if the message got deleted
|
||||
await sleep(1)
|
||||
# get the message via the channelID and the message ID from the database
|
||||
|
||||
if blocked == "worldwide":
|
||||
dbcursor.execute("DELETE FROM VIDEOS WHERE id = %s", [results["id"]])
|
||||
except Exception:
|
||||
log_exception("Failed to update changed monitor embed for video=%s", results["videoID"])
|
||||
|
||||
try:
|
||||
await runtime.sleep(1)
|
||||
channel = runtime.bot.get_channel(results["channelID"])
|
||||
try:
|
||||
message = await bot.get_channel(results['channelID']).fetch_message(results['messageID'])
|
||||
message = await channel.fetch_message(results["messageID"])
|
||||
except nextcord.errors.NotFound:
|
||||
video_logger.warning("Message with DB ID %s not found; disabling video monitor", results["id"])
|
||||
dbcursor.execute(
|
||||
"UPDATE VIDEOS SET videoAvailable=0 WHERE id = %s", [results['id']])
|
||||
embed = message.embeds[0] # get the embed from the message
|
||||
# remove the description (was here from a prevois bug)
|
||||
dbcursor.execute("UPDATE VIDEOS SET videoAvailable=0 WHERE id = %s", [results["id"]])
|
||||
return
|
||||
|
||||
embed = message.embeds[0]
|
||||
embed.description = ""
|
||||
try:
|
||||
embed.remove_field(2) # clear the like and view fields
|
||||
except:
|
||||
video_logger.debug("Embed field 2 missing while refreshing video=%s", results['videoID'])
|
||||
embed.remove_field(2)
|
||||
except Exception:
|
||||
video_logger.debug("Embed field 2 missing while refreshing video=%s", results["videoID"])
|
||||
try:
|
||||
embed.remove_field(1)
|
||||
except:
|
||||
video_logger.debug("Embed field 1 missing while refreshing video=%s", results['videoID'])
|
||||
embed.set_footer(text="") # clear the footer
|
||||
await sleep(1)
|
||||
dbcursor.execute(
|
||||
"SELECT * FROM monitorConfig WHERE Server=" + str(
|
||||
bot.get_channel(results['channelID']).guild.id))
|
||||
if (dbcursor.fetchone() == None):
|
||||
dbcursor.execute("INSERT INTO monitorConfig (Server) VALUES (" +
|
||||
str(bot.get_channel(results['channelID']).guild.id) + ")")
|
||||
except Exception:
|
||||
video_logger.debug("Embed field 1 missing while refreshing video=%s", results["videoID"])
|
||||
embed.set_footer(text="")
|
||||
|
||||
dbcursor.execute("SELECT * FROM monitorConfig WHERE Server=" + str(
|
||||
bot.get_channel(results['channelID']).guild.id))
|
||||
await runtime.sleep(1)
|
||||
dbcursor.execute("SELECT * FROM monitorConfig WHERE Server=%s", [channel.guild.id])
|
||||
if dbcursor.fetchone() is None:
|
||||
dbcursor.execute("INSERT INTO monitorConfig (Server) VALUES (%s)", [channel.guild.id])
|
||||
|
||||
dbcursor.execute("SELECT * FROM monitorConfig WHERE Server=%s", [channel.guild.id])
|
||||
result2 = dbcursor.fetchone()
|
||||
footer = "" # make a empty footer variable
|
||||
footer = ""
|
||||
|
||||
if (result2['likeAndViewsAsField']): # if we show the likes and views as field, run this
|
||||
if (result2['showViewCounter']): # if we show the view counter, add the field for it
|
||||
embed.add_field(name="Views", value=str(
|
||||
video["items"][0]["statistics"]["viewCount"]))
|
||||
if (result2['showLikeCounter']): # if we show the like counter add the field for it
|
||||
embed.add_field(name="Likes", value=str(
|
||||
video["items"][0]["statistics"]["likeCount"]))
|
||||
else: # this runs if we show the likes / views in the footer
|
||||
if (result2['showViewCounter']): # check if the view counter is turned on, if yes add it
|
||||
footer = "Views: " + \
|
||||
str(video["items"][0]["statistics"]["viewCount"])
|
||||
if (result2['showLikeCounter']):
|
||||
footer = footer + ", " # if both are on add a ", " to seperate them
|
||||
if (result2['showLikeCounter']): # add, if wanted the like counter
|
||||
footer = footer + "Likes: " + \
|
||||
str(video["items"][0]["statistics"]["likeCount"])
|
||||
if result2["likeAndViewsAsField"]:
|
||||
if result2["showViewCounter"]:
|
||||
embed.add_field(name="Views", value=str(video["items"][0]["statistics"]["viewCount"]))
|
||||
if result2["showLikeCounter"]:
|
||||
embed.add_field(name="Likes", value=str(video["items"][0]["statistics"]["likeCount"]))
|
||||
else:
|
||||
if result2["showViewCounter"]:
|
||||
footer = "Views: " + str(video["items"][0]["statistics"]["viewCount"])
|
||||
if result2["showLikeCounter"]:
|
||||
footer = footer + ", "
|
||||
if result2["showLikeCounter"]:
|
||||
footer = footer + "Likes: " + str(video["items"][0]["statistics"]["likeCount"])
|
||||
|
||||
if(result2["showLastUpdate"]):
|
||||
# write last update date to footer
|
||||
if result2["showLastUpdate"]:
|
||||
footer = footer + " Last update: " + datetime.now().strftime("%d.%m.%Y %H:%M")
|
||||
|
||||
# set the footer to the embed
|
||||
embed.set_footer(text=footer)
|
||||
|
||||
await sleep(1)
|
||||
await message.edit(embed=embed) # send the updated embed
|
||||
except:
|
||||
log_exception("Failed to refresh monitor embed for video=%s", results['videoID'])
|
||||
await runtime.sleep(1)
|
||||
await message.edit(embed=embed)
|
||||
except Exception:
|
||||
log_exception("Failed to refresh monitor embed for video=%s", results["videoID"])
|
||||
except Exception:
|
||||
log_exception("checkVideo failed for DB row id=%s", results.get("id"))
|
||||
finally:
|
||||
dbcursor.close()
|
||||
except:
|
||||
log_exception("checkVideo failed for DB row id=%s", results.get('id'))
|
||||
|
|
|
|||
|
|
@ -1,29 +1,38 @@
|
|||
from checkVideo import *
|
||||
import logging
|
||||
|
||||
import runtime
|
||||
from checkVideo import checkVideo
|
||||
from utils import log_exception
|
||||
|
||||
|
||||
video_batch_logger = logging.getLogger("discordyoutubemonitor.video.batch")
|
||||
|
||||
async def checkVideos(): # This task checks all Videos for new changes in blocklist
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
global apikeyID # get the global apikey variable
|
||||
|
||||
async def checkVideos():
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
# if True:#used for development (for easy disabling the try and catch block)
|
||||
try:
|
||||
dbcursor.execute("SELECT * FROM VIDEOS WHERE videoAvailable=1") # get all videos
|
||||
except:
|
||||
dbconnection = pymysql.connect(host=mysqlHostname, user=mysqlUsername, password=mysqlPassword, database=mysqlDatabase, autocommit=True)
|
||||
# make a database cursor (to execute SQL commands)
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor.execute(
|
||||
"SELECT * FROM VIDEOS") # get all videos
|
||||
request = dbcursor.fetchall() # get the entries
|
||||
dbcursor.execute("SELECT * FROM VIDEOS WHERE videoAvailable=1")
|
||||
except Exception:
|
||||
runtime.dbconnection = runtime.pymysql.connect(
|
||||
host=runtime.mysqlHostname,
|
||||
user=runtime.mysqlUsername,
|
||||
password=runtime.mysqlPassword,
|
||||
database=runtime.mysqlDatabase,
|
||||
autocommit=True,
|
||||
)
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
dbcursor.execute("SELECT * FROM VIDEOS")
|
||||
|
||||
request = dbcursor.fetchall()
|
||||
video_batch_logger.info("Checking %s monitored videos", len(request))
|
||||
for results in request: # rotate through all entries
|
||||
for results in request:
|
||||
try:
|
||||
await checkVideo(results)
|
||||
except:
|
||||
log_exception("Failed to fetch data for video=%s", results.get('videoID'))
|
||||
await sleep(1)
|
||||
except:
|
||||
except Exception:
|
||||
log_exception("Failed to fetch data for video=%s", results.get("videoID"))
|
||||
await runtime.sleep(1)
|
||||
except Exception:
|
||||
log_exception("checkVideos batch run failed")
|
||||
dbcursor.close()
|
||||
finally:
|
||||
dbcursor.close()
|
||||
|
|
|
|||
36
app/command_guards.py
Normal file
36
app/command_guards.py
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
from permissionCheck import (
|
||||
checkIfMusikEnabledAsync,
|
||||
checkIfMusikNotEnabledAsync,
|
||||
checkIfPremiumAsync,
|
||||
checkRoleAsync,
|
||||
)
|
||||
|
||||
|
||||
def require_guild(interaction):
|
||||
if interaction.guild is None:
|
||||
raise ValueError("This command can only be used in a server.")
|
||||
|
||||
|
||||
async def require_role_access(interaction):
|
||||
require_guild(interaction)
|
||||
if not await checkRoleAsync(interaction):
|
||||
raise PermissionError("You are not allowed to use this command.")
|
||||
|
||||
|
||||
async def require_monitor_access(interaction):
|
||||
await require_role_access(interaction)
|
||||
if not await checkIfPremiumAsync(interaction):
|
||||
raise PermissionError("This command is only available on registered premium servers.")
|
||||
|
||||
|
||||
async def require_music_enabled(interaction):
|
||||
await require_role_access(interaction)
|
||||
if not await checkIfMusikEnabledAsync(interaction):
|
||||
raise PermissionError("Music is not configured on this server.")
|
||||
|
||||
|
||||
async def require_music_disabled(interaction):
|
||||
await require_role_access(interaction)
|
||||
if not await checkIfMusikNotEnabledAsync(interaction):
|
||||
raise PermissionError("Music is already configured on this server.")
|
||||
|
||||
|
|
@ -1,71 +1,60 @@
|
|||
from setup import *
|
||||
from random import choice
|
||||
import logging
|
||||
|
||||
from requests import get as getNonAsync
|
||||
|
||||
import runtime
|
||||
|
||||
|
||||
download_logger = logging.getLogger("discordyoutubemonitor.download")
|
||||
|
||||
def download(url, serverID):
|
||||
global nextTitle
|
||||
global apikeyID
|
||||
|
||||
def choose_random_playlist_video(url, serverID):
|
||||
download_logger.info("Loading playlist for guild=%s url=%s", serverID, url)
|
||||
playlist = url.split("list=")[1]
|
||||
r = getNonAsync("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=" + playlist + "&key=" + apikey[apikeyID])
|
||||
response = getNonAsync(
|
||||
"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId="
|
||||
+ playlist
|
||||
+ "&key="
|
||||
+ runtime.apikey[runtime.apikeyID]
|
||||
)
|
||||
|
||||
startKeyID = apikeyID
|
||||
while(r.status_code == 403):
|
||||
apikeyID+=1
|
||||
download_logger.warning("Playlist download quota hit, switching to API key index %s", apikeyID)
|
||||
if (apikeyID >= len(apikey)):
|
||||
apikeyID = 0
|
||||
if (startKeyID == apikeyID):
|
||||
download_logger.error("All YouTube API keys exhausted while downloading playlist for guild=%s", serverID)
|
||||
return # we can stop here, the bot will hang here
|
||||
startKeyID = runtime.apikeyID
|
||||
while response.status_code == 403:
|
||||
runtime.apikeyID += 1
|
||||
download_logger.warning("Playlist download quota hit, switching to API key index %s", runtime.apikeyID)
|
||||
if runtime.apikeyID >= len(runtime.apikey):
|
||||
runtime.apikeyID = 0
|
||||
if startKeyID == runtime.apikeyID:
|
||||
download_logger.error("All YouTube API keys exhausted while loading playlist for guild=%s", serverID)
|
||||
return None
|
||||
|
||||
r = getNonAsync("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=" + playlist + "&key=" + apikey[apikeyID])
|
||||
response = getNonAsync(
|
||||
"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId="
|
||||
+ playlist
|
||||
+ "&key="
|
||||
+ runtime.apikey[runtime.apikeyID]
|
||||
)
|
||||
|
||||
if(r.status_code != 200):
|
||||
download_logger.error("Received status code %s while loading playlist for guild=%s with key index %s", r.status_code, serverID, apikeyID)
|
||||
return
|
||||
if response.status_code != 200:
|
||||
download_logger.error(
|
||||
"Received status code %s while loading playlist for guild=%s with key index %s",
|
||||
response.status_code,
|
||||
serverID,
|
||||
runtime.apikeyID,
|
||||
)
|
||||
return None
|
||||
|
||||
playlistData = loads(r.text)
|
||||
playlistData = runtime.loads(response.text)
|
||||
videosInPlaylist = [result["snippet"]["resourceId"]["videoId"] for result in playlistData["items"]]
|
||||
|
||||
videosInPlaylist = []
|
||||
# search for titles in playlist
|
||||
for results in playlistData["items"]:
|
||||
videosInPlaylist.append(results["snippet"]["resourceId"]["videoId"])
|
||||
|
||||
for video in blocklist:
|
||||
for video in runtime.blocklist:
|
||||
if video in videosInPlaylist:
|
||||
videosInPlaylist.remove(video)
|
||||
|
||||
if not videosInPlaylist:
|
||||
download_logger.warning("Playlist for guild=%s contains no playable videos", serverID)
|
||||
return None
|
||||
|
||||
videoID = choice(videosInPlaylist)
|
||||
videoURL = "https://youtu.be/" + videoID
|
||||
|
||||
|
||||
ydl_opts = { # youtube-dl arguments
|
||||
'format': 'bestaudio/best', # we want the best audio available
|
||||
'quiet': True,
|
||||
'postprocessors': [{ # this is the configuration for the mp3 converter
|
||||
'key': 'FFmpegExtractAudio',
|
||||
'preferredcodec': 'mp3',
|
||||
'preferredquality': '192',
|
||||
}],
|
||||
# set our custom file name
|
||||
'outtmpl': "/downloadTemp/" + videoID + ".mp3",
|
||||
}
|
||||
|
||||
# put the URL in the next title list
|
||||
nextTitle[str(serverID)] = videoID
|
||||
|
||||
if(isfile("/downloadTemp/" + videoID + ".mp3")): # delete (if exist) old entries
|
||||
download_logger.info("File already downloaded for guild=%s video=%s", serverID, videoID)
|
||||
return
|
||||
|
||||
download_logger.info("Downloading track for guild=%s video=%s", serverID, videoID)
|
||||
try: # download the song with the arguments from up
|
||||
YoutubeDL(ydl_opts).download([videoURL])
|
||||
except:
|
||||
log_exception("Track download failed for guild=%s video=%s", serverID, videoID)
|
||||
nextTitle[str(serverID)] = ""
|
||||
download_logger.warning("Download failed for guild=%s video=%s; sleeping before retry", serverID, videoID)
|
||||
sleept(60) # wait 1 minute on fail, to not risk a ban
|
||||
return "https://youtu.be/" + videoID
|
||||
|
|
|
|||
|
|
@ -1,12 +1,15 @@
|
|||
class dummyPlayer:
|
||||
@staticmethod
|
||||
async def connect():
|
||||
return True
|
||||
def is_connected(self):
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
async def disconnect():
|
||||
return True
|
||||
def is_playing(self):
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
async def is_connected():
|
||||
return False
|
||||
def stop(self):
|
||||
return None
|
||||
|
||||
def play(self, *args, **kwargs):
|
||||
return None
|
||||
|
||||
async def disconnect(self):
|
||||
return True
|
||||
|
|
|
|||
|
|
@ -1,35 +1,40 @@
|
|||
from download import *
|
||||
from datetime import datetime
|
||||
import logging
|
||||
|
||||
import nextcord
|
||||
|
||||
import runtime
|
||||
from command_guards import require_guild, require_role_access
|
||||
from utils import interaction_log_context, log_exception, send_response
|
||||
|
||||
|
||||
command_logger = logging.getLogger("discordyoutubemonitor.commands.general")
|
||||
|
||||
|
||||
def require_guild(interaction):
|
||||
if interaction.guild is None:
|
||||
raise ValueError("This command can only be used in a server.")
|
||||
|
||||
|
||||
async def require_role_access(interaction):
|
||||
require_guild(interaction)
|
||||
if not await checkRoleAsync(interaction):
|
||||
raise PermissionError("You are not allowed to use this command.")
|
||||
|
||||
|
||||
@bot.slash_command(description="Register a premium server")
|
||||
@runtime.bot.slash_command(description="Register a premium server")
|
||||
async def register(interaction: nextcord.Interaction, registration_key: str, server: str = None):
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
require_guild(interaction)
|
||||
target_server = int(server) if server else interaction.guild.id
|
||||
command_logger.info("Register requested: %s target_server=%s", interaction_log_context(interaction), target_server)
|
||||
dbcursor.execute("SELECT * FROM registeredServer WHERE Server=" + str(target_server) + " AND registerKey=%s", [registration_key])
|
||||
if(dbcursor.fetchone() == None):
|
||||
dbcursor.execute(
|
||||
"SELECT * FROM registeredServer WHERE Server=%s AND registerKey=%s",
|
||||
[target_server, registration_key],
|
||||
)
|
||||
if dbcursor.fetchone() is None:
|
||||
await send_response(interaction, "wrong key", ephemeral=True)
|
||||
command_logger.warning("Register failed: invalid key for server %s", target_server)
|
||||
else:
|
||||
dbcursor.execute("UPDATE registeredServer SET registered=1 WHERE Server=" + str(target_server) + " AND registerKey=%s", [registration_key])
|
||||
await send_response(interaction, "The Server has been registered and the bot can now be used.", ephemeral=True)
|
||||
dbcursor.execute(
|
||||
"UPDATE registeredServer SET registered=1 WHERE Server=%s AND registerKey=%s",
|
||||
[target_server, registration_key],
|
||||
)
|
||||
await send_response(
|
||||
interaction,
|
||||
"The Server has been registered and the bot can now be used.",
|
||||
ephemeral=True,
|
||||
)
|
||||
command_logger.info("Register succeeded for server %s", target_server)
|
||||
except Exception:
|
||||
log_exception("Register command failed: %s", interaction_log_context(interaction))
|
||||
|
|
@ -38,7 +43,7 @@ async def register(interaction: nextcord.Interaction, registration_key: str, ser
|
|||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.slash_command(description="Print the bot latency")
|
||||
@runtime.bot.slash_command(description="Print the bot latency")
|
||||
async def ping(interaction: nextcord.Interaction):
|
||||
await require_role_access(interaction)
|
||||
command_logger.info("Ping requested: %s", interaction_log_context(interaction))
|
||||
|
|
@ -47,15 +52,14 @@ async def ping(interaction: nextcord.Interaction):
|
|||
delta = round((now - created_at).total_seconds() * 1000)
|
||||
embed = nextcord.Embed(
|
||||
title=":ping_pong: | Pong!",
|
||||
description="```prolog\nLatency :: " + str(round(bot.latency * 1000)) + "ms\nResponse :: " + str(delta) + "ms```",
|
||||
description="```prolog\nLatency :: " + str(round(runtime.bot.latency * 1000)) + "ms\nResponse :: " + str(delta) + "ms```",
|
||||
)
|
||||
await send_response(interaction, embed=embed)
|
||||
|
||||
|
||||
@bot.slash_command(description="Allow a role to use the bot")
|
||||
@runtime.bot.slash_command(description="Allow a role to use the bot")
|
||||
async def addadmin(interaction: nextcord.Interaction, server_role: nextcord.Role):
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
await require_role_access(interaction)
|
||||
dbcursor.execute("INSERT INTO adminRoles (Server, roleID) VALUES (%s, %s)", [interaction.guild.id, server_role.id])
|
||||
|
|
@ -68,10 +72,9 @@ async def addadmin(interaction: nextcord.Interaction, server_role: nextcord.Role
|
|||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.slash_command(description="Disallow a role from using the bot")
|
||||
@runtime.bot.slash_command(description="Disallow a role from using the bot")
|
||||
async def removeadmin(interaction: nextcord.Interaction, role: nextcord.Role):
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
await require_role_access(interaction)
|
||||
dbcursor.execute("DELETE FROM adminRoles WHERE Server=%s AND roleID=%s", [interaction.guild.id, role.id])
|
||||
|
|
@ -84,7 +87,7 @@ async def removeadmin(interaction: nextcord.Interaction, role: nextcord.Role):
|
|||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.slash_command(description="Explain the slash-command migration")
|
||||
@runtime.bot.slash_command(description="Explain the slash-command migration")
|
||||
async def changeprefix(interaction: nextcord.Interaction):
|
||||
await require_role_access(interaction)
|
||||
command_logger.info("Changeprefix requested after slash migration: %s", interaction_log_context(interaction))
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
from aboutCommand import *
|
||||
from nextcord.ext import tasks
|
||||
|
||||
import runtime
|
||||
|
||||
|
||||
@tasks.loop(seconds=60)
|
||||
async def hearBeat():
|
||||
if(heartBeatEnabled):
|
||||
logger.debug("Heartbeat ping to %s", heartBeatURL)
|
||||
r = getr(heartBeatURL)
|
||||
if runtime.heartBeatEnabled:
|
||||
runtime.logger.debug("Heartbeat ping to %s", runtime.heartBeatURL)
|
||||
runtime.getr(runtime.heartBeatURL)
|
||||
|
|
|
|||
|
|
@ -1,25 +1,25 @@
|
|||
from checkVideos import *
|
||||
import logging
|
||||
|
||||
import nextcord
|
||||
|
||||
import runtime
|
||||
from checkVideo import checkVideo
|
||||
from command_guards import require_monitor_access
|
||||
from utils import defer_response, interaction_log_context, log_exception, send_response
|
||||
|
||||
|
||||
command_logger = logging.getLogger("discordyoutubemonitor.commands.monitor")
|
||||
|
||||
|
||||
async def require_monitor_access(interaction):
|
||||
await require_role_access(interaction)
|
||||
if not await checkIfPremiumAsync(interaction):
|
||||
raise PermissionError("This command is only available on registered premium servers.")
|
||||
|
||||
|
||||
async def fetch_youtube_video_metadata(youtube_video_url):
|
||||
async with ClientSession() as session:
|
||||
async with runtime.ClientSession() as session:
|
||||
response = await session.get("https://www.youtube.com/oembed?format=json&url=" + youtube_video_url)
|
||||
return loads(await response.text())
|
||||
return runtime.loads(await response.text())
|
||||
|
||||
|
||||
@bot.slash_command(description="Start a new monitoring job in this channel")
|
||||
@runtime.bot.slash_command(description="Start a new monitoring job in this channel")
|
||||
async def monitor(interaction: nextcord.Interaction, youtube_video_url: str):
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
await require_monitor_access(interaction)
|
||||
await defer_response(interaction)
|
||||
|
|
@ -27,19 +27,22 @@ async def monitor(interaction: nextcord.Interaction, youtube_video_url: str):
|
|||
command_logger.info("Monitor requested: %s url=%s", interaction_log_context(interaction), youtube_video_url)
|
||||
|
||||
response = await fetch_youtube_video_metadata(youtube_video_url)
|
||||
|
||||
videoID = response["thumbnail_url"].split("/vi/")[1].split("/hqdefault.jpg")[0]
|
||||
dbcursor.execute("INSERT INTO VIDEOS (videoID, blockedIn, messageID, channelID) VALUES (%s, 'waiting for data', 0, 0)", [videoID])
|
||||
dbcursor.execute("SELECT * FROM VIDEOS WHERE videoID=%s", [videoID])
|
||||
dbcursor.execute(
|
||||
"INSERT INTO VIDEOS (videoID, blockedIn, messageID, channelID) VALUES (%s, 'waiting for data', 0, 0)",
|
||||
[videoID],
|
||||
)
|
||||
monitor_id = dbcursor.lastrowid
|
||||
dbcursor.execute("SELECT * FROM VIDEOS WHERE id=%s", [monitor_id])
|
||||
result = dbcursor.fetchone()
|
||||
|
||||
embed = nextcord.Embed(title=response["title"], description="", color=0xff0000, url="https://youtu.be/" + videoID)
|
||||
embed.add_field(name="Blocked in", value=result['blockedIn'])
|
||||
embed.add_field(name="Blocked in", value=result["blockedIn"])
|
||||
embed.set_thumbnail(url=response["thumbnail_url"])
|
||||
message = await interaction.channel.send(embed=embed)
|
||||
|
||||
dbcursor.execute("UPDATE VIDEOS SET messageID = %s, channelID = %s WHERE videoID = %s", [message.id, channel_id, result['videoID']])
|
||||
dbcursor.execute("SELECT * FROM VIDEOS WHERE messageID = %s", [message.id])
|
||||
dbcursor.execute("UPDATE VIDEOS SET messageID=%s, channelID=%s WHERE id=%s", [message.id, channel_id, monitor_id])
|
||||
dbcursor.execute("SELECT * FROM VIDEOS WHERE id=%s", [monitor_id])
|
||||
await checkVideo(dbcursor.fetchone())
|
||||
await send_response(interaction, "Monitoring created for `" + videoID + "`.", ephemeral=True)
|
||||
command_logger.info("Monitor created: guild=%s video=%s message=%s", interaction.guild.id, videoID, message.id)
|
||||
|
|
@ -50,22 +53,19 @@ async def monitor(interaction: nextcord.Interaction, youtube_video_url: str):
|
|||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.slash_command(description="Run a monitor update immediately")
|
||||
@runtime.bot.slash_command(description="Run a monitor update immediately")
|
||||
async def updatemonitor(interaction: nextcord.Interaction, youtube_video_url: str):
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
await require_monitor_access(interaction)
|
||||
await defer_response(interaction, ephemeral=True)
|
||||
channel_id = interaction.channel.id
|
||||
command_logger.info("Updatemonitor requested: %s url=%s", interaction_log_context(interaction), youtube_video_url)
|
||||
|
||||
response = await fetch_youtube_video_metadata(youtube_video_url)
|
||||
videoID = response["thumbnail_url"].split("/vi/")[1].split("/hqdefault.jpg")[0]
|
||||
|
||||
dbcursor.execute(
|
||||
"SELECT * FROM VIDEOS WHERE videoID=%s AND channelID=%s ORDER BY id DESC",
|
||||
[videoID, channel_id],
|
||||
[videoID, interaction.channel.id],
|
||||
)
|
||||
result = dbcursor.fetchone()
|
||||
if result is None:
|
||||
|
|
@ -81,59 +81,66 @@ async def updatemonitor(interaction: nextcord.Interaction, youtube_video_url: st
|
|||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.slash_command(description="Change settings of the YouTube monitor")
|
||||
@runtime.bot.slash_command(description="Change settings of the YouTube monitor")
|
||||
async def monitorsettings(interaction: nextcord.Interaction, setting_name: str = None, value: str = None):
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
await require_monitor_access(interaction)
|
||||
command_logger.info("Monitorsettings requested: %s setting=%s value=%s", interaction_log_context(interaction), setting_name, value)
|
||||
dbcursor.execute("SELECT * FROM monitorConfig WHERE Server=" + str(interaction.guild.id))
|
||||
if(dbcursor.fetchone() == None):
|
||||
dbcursor.execute("INSERT INTO monitorConfig (Server) VALUES (" + str(interaction.guild.id) + ")")
|
||||
command_logger.info(
|
||||
"Monitorsettings requested: %s setting=%s value=%s",
|
||||
interaction_log_context(interaction),
|
||||
setting_name,
|
||||
value,
|
||||
)
|
||||
dbcursor.execute("SELECT * FROM monitorConfig WHERE Server=%s", [interaction.guild.id])
|
||||
if dbcursor.fetchone() is None:
|
||||
dbcursor.execute("INSERT INTO monitorConfig (Server) VALUES (%s)", [interaction.guild.id])
|
||||
|
||||
if(setting_name == None):
|
||||
await send_response(interaction, "Use `/monitorsettings setting_name:<name> value:<value>`.\nAvailable settings: `viewCounter`, `likeCounter`, `style`, `showLastUpdate`, `pingMessage`.")
|
||||
if setting_name is None:
|
||||
await send_response(
|
||||
interaction,
|
||||
"Use `/monitorsettings setting_name:<name> value:<value>`.\nAvailable settings: `viewCounter`, `likeCounter`, `style`, `showLastUpdate`, `pingMessage`.",
|
||||
)
|
||||
return
|
||||
|
||||
if(value is None):
|
||||
dbcursor.execute("SELECT * FROM monitorConfig WHERE Server=" + str(interaction.guild.id))
|
||||
if value is None:
|
||||
dbcursor.execute("SELECT * FROM monitorConfig WHERE Server=%s", [interaction.guild.id])
|
||||
result = dbcursor.fetchone()
|
||||
if (setting_name == "viewCounter"):
|
||||
await send_response(interaction, setting_name + ": " + ("on" if result['showViewCounter'] else "off"))
|
||||
elif (setting_name == "likeCounter"):
|
||||
await send_response(interaction, setting_name + ": " + ("on" if result['showLikeCounter'] else "off"))
|
||||
elif (setting_name == "showLastUpdate"):
|
||||
await send_response(interaction, setting_name + ": " + ("on" if result['showLastUpdate'] else "off"))
|
||||
elif (setting_name == "style"):
|
||||
await send_response(interaction, setting_name + ": " + ("footer" if result['likeAndViewsAsField'] else "field"))
|
||||
elif (setting_name == "pingMessage"):
|
||||
await send_response(interaction, setting_name + ": " + result['pingMessage'])
|
||||
if setting_name == "viewCounter":
|
||||
await send_response(interaction, setting_name + ": " + ("on" if result["showViewCounter"] else "off"))
|
||||
elif setting_name == "likeCounter":
|
||||
await send_response(interaction, setting_name + ": " + ("on" if result["showLikeCounter"] else "off"))
|
||||
elif setting_name == "showLastUpdate":
|
||||
await send_response(interaction, setting_name + ": " + ("on" if result["showLastUpdate"] else "off"))
|
||||
elif setting_name == "style":
|
||||
await send_response(interaction, setting_name + ": " + ("footer" if result["likeAndViewsAsField"] else "field"))
|
||||
elif setting_name == "pingMessage":
|
||||
await send_response(interaction, setting_name + ": " + result["pingMessage"])
|
||||
else:
|
||||
await send_response(interaction, "Unknown setting.", ephemeral=True)
|
||||
return
|
||||
|
||||
if(setting_name == "pingMessage"):
|
||||
dbcursor.execute("UPDATE monitorConfig SET pingMessage=%s WHERE Server=" + str(interaction.guild.id), [value])
|
||||
if setting_name == "pingMessage":
|
||||
dbcursor.execute("UPDATE monitorConfig SET pingMessage=%s WHERE Server=%s", [value, interaction.guild.id])
|
||||
await send_response(interaction, "New message on block change is: " + value)
|
||||
return
|
||||
|
||||
state = "1" if value == "1" else "0"
|
||||
tableName = ""
|
||||
if(setting_name == "viewCounter"):
|
||||
if setting_name == "viewCounter":
|
||||
tableName = "showViewCounter"
|
||||
elif(setting_name == "likeCounter"):
|
||||
elif setting_name == "likeCounter":
|
||||
tableName = "showLikeCounter"
|
||||
elif(setting_name == "showLastUpdate"):
|
||||
elif setting_name == "showLastUpdate":
|
||||
tableName = "showLastUpdate"
|
||||
elif(setting_name == "style"):
|
||||
elif setting_name == "style":
|
||||
tableName = "likeAndViewsAsField"
|
||||
|
||||
if tableName == "":
|
||||
await send_response(interaction, "Unknown setting.", ephemeral=True)
|
||||
return
|
||||
|
||||
dbcursor.execute("UPDATE monitorConfig SET " + tableName + "=" + state + " WHERE Server=" + str(interaction.guild.id))
|
||||
dbcursor.execute("UPDATE monitorConfig SET " + tableName + "=%s WHERE Server=%s", [state, interaction.guild.id])
|
||||
await send_response(interaction, "Updated " + setting_name + ", new state is " + value)
|
||||
except Exception:
|
||||
log_exception("Monitorsettings failed: %s", interaction_log_context(interaction))
|
||||
|
|
|
|||
|
|
@ -1,18 +1,22 @@
|
|||
import pymysql
|
||||
from asyncio import to_thread
|
||||
from config import *
|
||||
from random import choice
|
||||
from string import ascii_letters # used for the registration string generation
|
||||
from string import ascii_letters
|
||||
import logging
|
||||
|
||||
import pymysql
|
||||
|
||||
import runtime
|
||||
|
||||
|
||||
logger = logging.getLogger("discordyoutubemonitor.permissions")
|
||||
|
||||
|
||||
def create_dbconnection():
|
||||
return pymysql.connect(
|
||||
host=mysqlHostname,
|
||||
user=mysqlUsername,
|
||||
password=mysqlPassword,
|
||||
database=mysqlDatabase,
|
||||
host=runtime.mysqlHostname,
|
||||
user=runtime.mysqlUsername,
|
||||
password=runtime.mysqlPassword,
|
||||
database=runtime.mysqlDatabase,
|
||||
autocommit=True,
|
||||
connect_timeout=5,
|
||||
read_timeout=10,
|
||||
|
|
@ -20,28 +24,23 @@ def create_dbconnection():
|
|||
)
|
||||
|
||||
|
||||
dbconnection = create_dbconnection()
|
||||
|
||||
def checkRole(ctx): # this function checks, if the user has the roles to run the command (admins are always permitted)
|
||||
def checkRole(ctx):
|
||||
dbconnection = create_dbconnection()
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
try:
|
||||
author = getattr(ctx, "user", None) or getattr(ctx, "author", None)
|
||||
if author is None:
|
||||
return False
|
||||
if(author.id == adminUserID):
|
||||
if author.id == runtime.adminUserID:
|
||||
return True
|
||||
for roles in author.roles: # rotate through the roles the user has
|
||||
dbcursor.execute(
|
||||
"SELECT * FROM adminRoles WHERE Server=" + str(ctx.guild.id)) # get all videos
|
||||
|
||||
request = dbcursor.fetchall() # get the entries
|
||||
for results in request: # rotate through all entries
|
||||
roleeID = results['roleID']
|
||||
if(roles.id == roleeID):
|
||||
return True
|
||||
dbcursor.execute("SELECT * FROM adminRoles WHERE Server=%s", [ctx.guild.id])
|
||||
request = dbcursor.fetchall()
|
||||
allowed_role_ids = {result["roleID"] for result in request}
|
||||
for role in author.roles:
|
||||
if role.id in allowed_role_ids:
|
||||
return True
|
||||
|
||||
# if we checked all roles and didn't found a matching one, we check if the user is a admin, if not he is not allowed to use the command
|
||||
return author.guild_permissions.administrator
|
||||
finally:
|
||||
dbcursor.close()
|
||||
|
|
@ -52,43 +51,32 @@ def checkIfMusikEnabled(ctx):
|
|||
dbconnection = create_dbconnection()
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
try:
|
||||
# check if the player exist, if yes the music Bot is enabled on this Server
|
||||
dbcursor.execute("SELECT * FROM PLAYER WHERE Server=" + str(ctx.guild.id))
|
||||
result = dbcursor.fetchone()
|
||||
return result != None
|
||||
dbcursor.execute("SELECT * FROM PLAYER WHERE Server=%s", [ctx.guild.id])
|
||||
return dbcursor.fetchone() is not None
|
||||
finally:
|
||||
dbcursor.close()
|
||||
dbconnection.close()
|
||||
|
||||
|
||||
def checkIfMusikNotEnabled(ctx):
|
||||
dbconnection = create_dbconnection()
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
try:
|
||||
# check if the player exist, if yes the music Bot is enabled on this Server
|
||||
dbcursor.execute("SELECT * FROM PLAYER WHERE Server=" + str(ctx.guild.id))
|
||||
result = dbcursor.fetchone()
|
||||
return result == None
|
||||
finally:
|
||||
dbcursor.close()
|
||||
dbconnection.close()
|
||||
return not checkIfMusikEnabled(ctx)
|
||||
|
||||
|
||||
def checkIfPremium(ctx):
|
||||
dbconnection = create_dbconnection()
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
try:
|
||||
dbcursor.execute("SELECT * FROM registeredServer WHERE Server=" + str(ctx.guild.id))
|
||||
result = dbcursor.fetchone() # check if the server is registered
|
||||
if (result == None): # if not, start the process
|
||||
registerKey = ''.join(choice(ascii_letters)
|
||||
for i in range(20)) # generate the registration key
|
||||
dbcursor.execute("INSERT INTO registeredServer (Server, registerKey) VALUES (" + str(
|
||||
ctx.guild.id) + ", '" + registerKey + "')") # make a database entry for the server with the key
|
||||
# send to the admin user specified in the config the key
|
||||
dbcursor.execute("SELECT * FROM registeredServer WHERE Server=%s", [ctx.guild.id])
|
||||
result = dbcursor.fetchone()
|
||||
if result is None:
|
||||
registerKey = "".join(choice(ascii_letters) for _ in range(20))
|
||||
dbcursor.execute(
|
||||
"INSERT INTO registeredServer (Server, registerKey) VALUES (%s, %s)",
|
||||
[ctx.guild.id, registerKey],
|
||||
)
|
||||
logger.warning("Register key for %s (%s): %s", ctx.guild.name, ctx.guild.id, registerKey)
|
||||
return False
|
||||
else:
|
||||
return result["registered"] == 1
|
||||
return result["registered"] == 1
|
||||
finally:
|
||||
dbcursor.close()
|
||||
dbconnection.close()
|
||||
|
|
|
|||
|
|
@ -1,39 +1,37 @@
|
|||
from radioTask import *
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
|
||||
import mafic
|
||||
import nextcord
|
||||
|
||||
import runtime
|
||||
from command_guards import require_music_disabled, require_music_enabled
|
||||
from permissionCheck import checkIfPremiumAsync
|
||||
from radioTask import ensure_player_connected, load_next_track
|
||||
from utils import interaction_log_context, log_exception, send_response
|
||||
|
||||
|
||||
command_logger = logging.getLogger("discordyoutubemonitor.commands.radio")
|
||||
|
||||
|
||||
async def require_music_enabled(interaction):
|
||||
await require_role_access(interaction)
|
||||
if not await checkIfMusikEnabledAsync(interaction):
|
||||
raise PermissionError("Music is not configured on this server.")
|
||||
def get_guild_player(interaction):
|
||||
player = interaction.guild.voice_client
|
||||
if player is not None and isinstance(player, mafic.Player):
|
||||
runtime.player[str(interaction.guild.id)] = player
|
||||
return player
|
||||
|
||||
|
||||
async def require_music_disabled(interaction):
|
||||
await require_role_access(interaction)
|
||||
if not await checkIfMusikNotEnabledAsync(interaction):
|
||||
raise PermissionError("Music is already configured on this server.")
|
||||
|
||||
|
||||
@bot.slash_command(description="Stop the music and disconnect the bot")
|
||||
@runtime.bot.slash_command(description="Stop the music and disconnect the bot")
|
||||
async def stop(interaction: nextcord.Interaction):
|
||||
global dbconnection
|
||||
global player
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
await require_music_enabled(interaction)
|
||||
command_logger.info("Stop requested: %s", interaction_log_context(interaction))
|
||||
dbcursor.execute("UPDATE PLAYER SET enabled=0 WHERE Server=" + str(interaction.guild.id))
|
||||
try:
|
||||
player[str(interaction.guild.id)].stop()
|
||||
await sleep(1)
|
||||
except Exception:
|
||||
command_logger.debug("Player already stopped on guild %s", interaction.guild.id)
|
||||
try:
|
||||
await player[str(interaction.guild.id)].disconnect()
|
||||
except Exception:
|
||||
command_logger.debug("Player already disconnected on guild %s", interaction.guild.id)
|
||||
dbcursor.execute("UPDATE PLAYER SET enabled=0 WHERE Server=%s", [interaction.guild.id])
|
||||
player = get_guild_player(interaction)
|
||||
if player is not None:
|
||||
await player.stop()
|
||||
await player.disconnect()
|
||||
await send_response(interaction, "The bot was stopped by <@" + str(interaction.user.id) + ">")
|
||||
except Exception:
|
||||
log_exception("Stop command failed: %s", interaction_log_context(interaction))
|
||||
|
|
@ -42,16 +40,19 @@ async def stop(interaction: nextcord.Interaction):
|
|||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.slash_command(description="Start the playback")
|
||||
@runtime.bot.slash_command(description="Start the playback")
|
||||
async def start(interaction: nextcord.Interaction):
|
||||
global dbconnection, t
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
await require_music_enabled(interaction)
|
||||
await runtime.connect_lavalink()
|
||||
command_logger.info("Start requested: %s", interaction_log_context(interaction))
|
||||
dbcursor.execute("UPDATE PLAYER SET enabled=1 WHERE Server=" + str(interaction.guild.id))
|
||||
t[str(interaction.guild.id)] = Thread(target=nothing)
|
||||
player[str(interaction.guild.id)] = dummyPlayer()
|
||||
dbcursor.execute("UPDATE PLAYER SET enabled=1 WHERE Server=%s", [interaction.guild.id])
|
||||
dbcursor.execute("SELECT * FROM PLAYER WHERE Server=%s", [interaction.guild.id])
|
||||
result = dbcursor.fetchone()
|
||||
player = await ensure_player_connected(interaction.guild.id, result["PlayChannel"])
|
||||
if player is not None and getattr(player, "current", None) is None:
|
||||
await load_next_track(player, result["youtubeChannelID"], interaction.guild.id)
|
||||
await send_response(interaction, "The bot was started by <@" + str(interaction.user.id) + ">")
|
||||
except Exception:
|
||||
log_exception("Start command failed: %s", interaction_log_context(interaction))
|
||||
|
|
@ -60,26 +61,29 @@ async def start(interaction: nextcord.Interaction):
|
|||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.slash_command(description="Change the voice channel the bot is listening to")
|
||||
@runtime.bot.slash_command(description="Change the voice channel the bot is listening to")
|
||||
async def changechannel(interaction: nextcord.Interaction):
|
||||
global dbconnection
|
||||
global player
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
await require_music_enabled(interaction)
|
||||
await runtime.connect_lavalink()
|
||||
command_logger.info("Changechannel requested: %s", interaction_log_context(interaction))
|
||||
try:
|
||||
channel = interaction.user.voice.channel
|
||||
except Exception:
|
||||
await send_response(interaction, "To change the MusicBot Channel you have to connect to a voice channel and then run this command", ephemeral=True)
|
||||
await send_response(
|
||||
interaction,
|
||||
"To change the MusicBot Channel you have to connect to a voice channel and then run this command",
|
||||
ephemeral=True,
|
||||
)
|
||||
return
|
||||
|
||||
dbcursor.execute("UPDATE PLAYER SET PlayChannel=%s WHERE Server=%s", [channel.id, interaction.guild.id])
|
||||
try:
|
||||
player[str(interaction.guild.id)].stop()
|
||||
except Exception:
|
||||
command_logger.debug("Stop skipped during channel change on guild %s", interaction.guild.id)
|
||||
await sleep(1)
|
||||
await player[str(interaction.guild.id)].disconnect()
|
||||
player = await ensure_player_connected(interaction.guild.id, channel.id)
|
||||
if player is not None and getattr(player, "current", None) is None:
|
||||
dbcursor.execute("SELECT * FROM PLAYER WHERE Server=%s", [interaction.guild.id])
|
||||
result = dbcursor.fetchone()
|
||||
await load_next_track(player, result["youtubeChannelID"], interaction.guild.id)
|
||||
await send_response(interaction, "Playback channel updated to <#" + str(channel.id) + ">")
|
||||
except Exception:
|
||||
log_exception("Changechannel failed: %s", interaction_log_context(interaction))
|
||||
|
|
@ -88,74 +92,100 @@ async def changechannel(interaction: nextcord.Interaction):
|
|||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.slash_command(description="Change the volume in percent")
|
||||
@runtime.bot.slash_command(description="Change the volume in percent")
|
||||
async def volume(interaction: nextcord.Interaction, volume: int):
|
||||
global audioPlayer
|
||||
try:
|
||||
await require_music_enabled(interaction)
|
||||
command_logger.info("Volume requested: %s volume=%s", interaction_log_context(interaction), volume)
|
||||
if(volume < 0) or (volume > 100):
|
||||
if volume < 0 or volume > 100:
|
||||
await send_response(interaction, "Volume has to be between 0 and 100", ephemeral=True)
|
||||
return
|
||||
audioPlayer[str(interaction.guild.id)].volume = volume / 100
|
||||
player = get_guild_player(interaction)
|
||||
if player is None:
|
||||
await send_response(interaction, "Nothing is currently playing.", ephemeral=True)
|
||||
return
|
||||
await player.set_volume(volume)
|
||||
await send_response(interaction, "Volume set to " + str(volume) + "%")
|
||||
except Exception:
|
||||
log_exception("Volume command failed: %s", interaction_log_context(interaction))
|
||||
await send_response(interaction, "Failed to change the volume.", ephemeral=True)
|
||||
|
||||
|
||||
@bot.slash_command(description="Skip the current mix")
|
||||
@runtime.bot.slash_command(description="Skip the current mix")
|
||||
async def skip(interaction: nextcord.Interaction):
|
||||
global player
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
await require_music_enabled(interaction)
|
||||
command_logger.info("Skip requested: %s", interaction_log_context(interaction))
|
||||
player[str(interaction.guild.id)].stop()
|
||||
player = get_guild_player(interaction)
|
||||
if player is None:
|
||||
await send_response(interaction, "Nothing is currently playing.", ephemeral=True)
|
||||
return
|
||||
|
||||
dbcursor.execute("SELECT * FROM PLAYER WHERE Server=%s", [interaction.guild.id])
|
||||
result = dbcursor.fetchone()
|
||||
await player.stop()
|
||||
await load_next_track(player, result["youtubeChannelID"], interaction.guild.id)
|
||||
await send_response(interaction, "Skipped the current track.")
|
||||
except Exception:
|
||||
log_exception("Skip command failed: %s", interaction_log_context(interaction))
|
||||
await send_response(interaction, "Failed to skip the current track.", ephemeral=True)
|
||||
finally:
|
||||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.slash_command(description="Print the currently playing track")
|
||||
@runtime.bot.slash_command(description="Print the currently playing track")
|
||||
async def current(interaction: nextcord.Interaction):
|
||||
global currentTitle
|
||||
global starttime
|
||||
try:
|
||||
await require_music_enabled(interaction)
|
||||
command_logger.info("Current requested: %s", interaction_log_context(interaction))
|
||||
ydl_opts = {
|
||||
'format': 'bestaudio/best',
|
||||
'postprocessors': [{
|
||||
'key': 'FFmpegExtractAudio',
|
||||
'preferredcodec': 'mp3',
|
||||
'preferredquality': '192',
|
||||
}],
|
||||
}
|
||||
video_data = YoutubeDL(ydl_opts).extract_info("https://youtu.be/" + currentTitle[str(interaction.guild.id)], download=False)
|
||||
embed = nextcord.Embed(title=video_data["title"], description="", url="https://youtu.be/" + currentTitle[str(interaction.guild.id)])
|
||||
embed.set_thumbnail(url=video_data["thumbnail"])
|
||||
embed.add_field(name="time", value=str(timedelta(seconds=round(time() - starttime[str(interaction.guild.id)]))))
|
||||
player = get_guild_player(interaction)
|
||||
current_track = getattr(player, "current", None) if player is not None else None
|
||||
if current_track is None:
|
||||
await send_response(interaction, "Nothing is currently playing.", ephemeral=True)
|
||||
return
|
||||
|
||||
embed = nextcord.Embed(
|
||||
title=getattr(current_track, "title", "Unknown track"),
|
||||
description="",
|
||||
url=getattr(current_track, "uri", None),
|
||||
)
|
||||
artwork_url = getattr(current_track, "artwork_url", None) or getattr(current_track, "thumbnail", None)
|
||||
if artwork_url:
|
||||
embed.set_thumbnail(url=artwork_url)
|
||||
embed.add_field(
|
||||
name="time",
|
||||
value=str(timedelta(seconds=round(runtime.time() - runtime.starttime.get(str(interaction.guild.id), runtime.time())))),
|
||||
)
|
||||
await send_response(interaction, embed=embed)
|
||||
except Exception:
|
||||
log_exception("Current command failed: %s", interaction_log_context(interaction))
|
||||
await send_response(interaction, "Failed to load the current track.", ephemeral=True)
|
||||
|
||||
|
||||
@bot.slash_command(description="Set the music player channel")
|
||||
@runtime.bot.slash_command(description="Set the music player channel")
|
||||
async def setupmusic(interaction: nextcord.Interaction, channel: nextcord.VoiceChannel):
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
await require_music_disabled(interaction)
|
||||
command_logger.info("Setupmusic requested: %s play_channel=%s", interaction_log_context(interaction), channel.id)
|
||||
dbcursor.execute("SELECT * FROM PLAYER WHERE Server=" + str(interaction.guild.id))
|
||||
if(dbcursor.fetchone() != None):
|
||||
await send_response(interaction, "Bot is already configured on this Server, please try to start it with `/start` or contact me if you need future assistance (<@" + str(adminUserID) + ">)")
|
||||
dbcursor.execute("SELECT * FROM PLAYER WHERE Server=%s", [interaction.guild.id])
|
||||
if dbcursor.fetchone() is not None:
|
||||
await send_response(
|
||||
interaction,
|
||||
"Bot is already configured on this Server, please try to start it with `/start` or contact me if you need future assistance (<@"
|
||||
+ str(runtime.adminUserID)
|
||||
+ ">)",
|
||||
)
|
||||
return
|
||||
dbcursor.execute("INSERT INTO PLAYER (PlayChannel, Server, youtubeChannelID) VALUES (%s, %s, %s)", (channel.id, interaction.guild.id, defaultPlaylistURL))
|
||||
t[str(interaction.guild.id)] = Thread(target=nothing)
|
||||
await send_response(interaction, "Setup complete, " + bot.user.name + " should now connect to <#" + str(channel.id) + "> and start playing Music soon.")
|
||||
dbcursor.execute(
|
||||
"INSERT INTO PLAYER (PlayChannel, Server, youtubeChannelID) VALUES (%s, %s, %s)",
|
||||
(channel.id, interaction.guild.id, runtime.defaultPlaylistURL),
|
||||
)
|
||||
await send_response(
|
||||
interaction,
|
||||
"Setup complete, " + runtime.bot.user.name + " should now connect to <#" + str(channel.id) + "> and start playing Music soon.",
|
||||
)
|
||||
except Exception:
|
||||
log_exception("Setupmusic failed: %s", interaction_log_context(interaction))
|
||||
await send_response(interaction, "Failed to configure music playback.", ephemeral=True)
|
||||
|
|
@ -163,29 +193,26 @@ async def setupmusic(interaction: nextcord.Interaction, channel: nextcord.VoiceC
|
|||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.slash_command(description="Restart the player")
|
||||
@runtime.bot.slash_command(description="Restart the player")
|
||||
async def restart(interaction: nextcord.Interaction):
|
||||
global dbconnection
|
||||
global player
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
await require_music_enabled(interaction)
|
||||
await runtime.connect_lavalink()
|
||||
command_logger.info("Restart requested: %s", interaction_log_context(interaction))
|
||||
await send_response(interaction, "restarting music bot, please wait one moment")
|
||||
dbcursor.execute("UPDATE PLAYER SET enabled=0 WHERE Server=" + str(interaction.guild.id))
|
||||
try:
|
||||
player[str(interaction.guild.id)].stop()
|
||||
await sleep(1)
|
||||
except Exception:
|
||||
command_logger.debug("Restart stop skipped on guild %s", interaction.guild.id)
|
||||
try:
|
||||
await player[str(interaction.guild.id)].disconnect()
|
||||
except Exception:
|
||||
command_logger.debug("Restart disconnect skipped on guild %s", interaction.guild.id)
|
||||
await sleep(10)
|
||||
dbcursor.execute("UPDATE PLAYER SET enabled=1 WHERE Server=" + str(interaction.guild.id))
|
||||
t[str(interaction.guild.id)] = Thread(target=nothing)
|
||||
player[str(interaction.guild.id)] = dummyPlayer()
|
||||
dbcursor.execute("UPDATE PLAYER SET enabled=0 WHERE Server=%s", [interaction.guild.id])
|
||||
player = get_guild_player(interaction)
|
||||
if player is not None:
|
||||
await player.stop()
|
||||
await player.disconnect()
|
||||
await runtime.sleep(2)
|
||||
dbcursor.execute("UPDATE PLAYER SET enabled=1 WHERE Server=%s", [interaction.guild.id])
|
||||
dbcursor.execute("SELECT * FROM PLAYER WHERE Server=%s", [interaction.guild.id])
|
||||
result = dbcursor.fetchone()
|
||||
player = await ensure_player_connected(interaction.guild.id, result["PlayChannel"])
|
||||
if player is not None:
|
||||
await load_next_track(player, result["youtubeChannelID"], interaction.guild.id)
|
||||
except Exception:
|
||||
log_exception("Restart command failed: %s", interaction_log_context(interaction))
|
||||
await send_response(interaction, "Failed to restart the player.", ephemeral=True)
|
||||
|
|
@ -193,18 +220,19 @@ async def restart(interaction: nextcord.Interaction):
|
|||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.slash_command(description="Change the playlist for the music bot")
|
||||
@runtime.bot.slash_command(description="Change the playlist for the music bot")
|
||||
async def changeplaylist(interaction: nextcord.Interaction, new_playlist_url: str):
|
||||
global dbconnection
|
||||
global player
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
await require_music_enabled(interaction)
|
||||
if not await checkIfPremiumAsync(interaction):
|
||||
raise PermissionError("Changing playlists is only available on registered premium servers.")
|
||||
command_logger.info("Changeplaylist requested: %s url=%s", interaction_log_context(interaction), new_playlist_url)
|
||||
dbcursor.execute("UPDATE PLAYER SET youtubeChannelID = %s WHERE Server = %s", [new_playlist_url, interaction.guild.id])
|
||||
player[str(interaction.guild.id)].stop()
|
||||
player = get_guild_player(interaction)
|
||||
if player is not None:
|
||||
await player.stop()
|
||||
await load_next_track(player, new_playlist_url, interaction.guild.id)
|
||||
await send_response(interaction, "changed Playlist to `" + new_playlist_url + "`")
|
||||
except Exception:
|
||||
log_exception("Changeplaylist failed: %s", interaction_log_context(interaction))
|
||||
|
|
|
|||
160
app/radioTask.py
160
app/radioTask.py
|
|
@ -1,91 +1,89 @@
|
|||
from monitorCommands import *
|
||||
import logging
|
||||
|
||||
import mafic
|
||||
|
||||
import runtime
|
||||
from download import choose_random_playlist_video
|
||||
from utils import log_exception
|
||||
|
||||
|
||||
radio_logger = logging.getLogger("discordyoutubemonitor.radio")
|
||||
|
||||
|
||||
async def ensure_player_connected(guild_id, channel_id):
|
||||
guild = runtime.bot.get_guild(int(guild_id))
|
||||
if guild is None:
|
||||
return None
|
||||
|
||||
voice_channel = guild.get_channel(int(channel_id))
|
||||
if voice_channel is None:
|
||||
return None
|
||||
|
||||
player = guild.voice_client
|
||||
if player is None:
|
||||
player = await voice_channel.connect(cls=mafic.Player)
|
||||
radio_logger.info("Connected Lavalink player to guild=%s channel=%s", guild_id, channel_id)
|
||||
elif player.channel.id != voice_channel.id:
|
||||
await player.move_to(voice_channel)
|
||||
radio_logger.info("Moved Lavalink player to guild=%s channel=%s", guild_id, channel_id)
|
||||
|
||||
runtime.player[str(guild_id)] = player
|
||||
return player
|
||||
|
||||
|
||||
async def load_next_track(player, playlist_url, guild_id):
|
||||
track_url = choose_random_playlist_video(playlist_url, guild_id)
|
||||
if track_url is None:
|
||||
return False
|
||||
|
||||
tracks = await player.fetch_tracks(track_url)
|
||||
if not tracks:
|
||||
radio_logger.warning("No Lavalink tracks resolved for guild=%s url=%s", guild_id, track_url)
|
||||
return False
|
||||
|
||||
track = tracks[0]
|
||||
await player.play(track)
|
||||
runtime.currentTitle[str(guild_id)] = getattr(track, "identifier", "") or track_url.rsplit("/", 1)[-1]
|
||||
runtime.starttime[str(guild_id)] = runtime.time()
|
||||
radio_logger.info("Playing track guild=%s title=%s", guild_id, getattr(track, "title", "unknown"))
|
||||
return True
|
||||
|
||||
|
||||
async def checkForNextTrack():
|
||||
global dbconnection
|
||||
global audioPlayer # import global variables
|
||||
global player
|
||||
global currentTitle
|
||||
global nextTitle
|
||||
global t
|
||||
global starttime
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
|
||||
await bot.wait_until_ready() # wait until the bot is fully loaded
|
||||
await runtime.bot.wait_until_ready()
|
||||
await runtime.connect_lavalink()
|
||||
radio_logger.info("Radio playback loop started")
|
||||
while(True):
|
||||
|
||||
while True:
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
try:
|
||||
dbcursor.execute(
|
||||
"SELECT * FROM PLAYER WHERE enabled=1") # get all videos
|
||||
except:
|
||||
dbconnection = pymysql.connect(host=mysqlHostname, user=mysqlUsername, password=mysqlPassword, database=mysqlDatabase, autocommit=True)
|
||||
# make a database cursor (to execute SQL commands)
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor.execute(
|
||||
"SELECT * FROM PLAYER WHERE enabled=1") # get all videos
|
||||
request = dbcursor.fetchall() # get the entries
|
||||
for result in request: # rotate through all entries
|
||||
try:
|
||||
channel = bot.get_channel(result['PlayChannel'])
|
||||
if(channel != None) and not player[str(result['Server'])].is_connected():
|
||||
player[str(result['Server'])] = await channel.connect()
|
||||
radio_logger.info("Connected player to guild=%s channel=%s", result['Server'], result['PlayChannel'])
|
||||
# check if we need to download the next track
|
||||
dbcursor.execute("SELECT * FROM PLAYER WHERE enabled=1")
|
||||
except Exception:
|
||||
runtime.dbconnection = runtime.pymysql.connect(
|
||||
host=runtime.mysqlHostname,
|
||||
user=runtime.mysqlUsername,
|
||||
password=runtime.mysqlPassword,
|
||||
database=runtime.mysqlDatabase,
|
||||
autocommit=True,
|
||||
)
|
||||
dbcursor = runtime.dbconnection.cursor(runtime.pymysql.cursors.DictCursor)
|
||||
dbcursor.execute("SELECT * FROM PLAYER WHERE enabled=1")
|
||||
|
||||
for result in dbcursor.fetchall():
|
||||
try:
|
||||
nextChannelTitle = nextTitle[str(result['Server'])]
|
||||
except KeyError:
|
||||
nextChannelTitle = ""
|
||||
guild_id = str(result["Server"])
|
||||
player = await ensure_player_connected(guild_id, result["PlayChannel"])
|
||||
if player is None:
|
||||
radio_logger.warning("Cannot resolve voice channel for guild=%s channel=%s", guild_id, result["PlayChannel"])
|
||||
continue
|
||||
|
||||
try:
|
||||
isPlaying = player[str(result['Server'])].is_playing()
|
||||
except:
|
||||
isPlaying = False
|
||||
current = getattr(player, "current", None)
|
||||
if current is None and not player.paused:
|
||||
await load_next_track(player, result["youtubeChannelID"], guild_id)
|
||||
except Exception:
|
||||
log_exception("Radio loop iteration failed for guild=%s", result.get("Server"))
|
||||
finally:
|
||||
dbcursor.close()
|
||||
|
||||
if not t[str(result['Server'])].is_alive() and nextChannelTitle == "" and not isfile("/downloadTemp/" + nextChannelTitle + ".mp3"):
|
||||
radio_logger.info("Starting downloader thread for guild=%s playlist=%s", result['Server'], result['youtubeChannelID'])
|
||||
t[str(result['Server'])] = Thread(target=download, args=(
|
||||
str(result['youtubeChannelID']), str(result['Server']))) # create the download task
|
||||
t[str(result['Server'])].start() # start the download task
|
||||
await sleep(2) # wait, to give the task time to start
|
||||
|
||||
if not isPlaying:
|
||||
servername = result['Server']
|
||||
enabled = result['enabled']
|
||||
fileExist = isfile("/downloadTemp/" + nextChannelTitle + ".mp3")
|
||||
radio_logger.debug("Idle player guild=%s next_file=%s file_exists=%s enabled=%s", servername, nextChannelTitle, fileExist, enabled)
|
||||
|
||||
if not isPlaying and isfile("/downloadTemp/" + nextChannelTitle + ".mp3") and result['enabled'] > 0:
|
||||
currentTitle[str(result['Server'])
|
||||
] = nextTitle[str(result['Server'])]
|
||||
nextTitle[str(result['Server'])] = ""
|
||||
await sleep(0)
|
||||
radio_logger.info("Playing track guild=%s video=%s", result['Server'], currentTitle[str(result['Server'])])
|
||||
audioPlayer[str(result['Server'])] = nextcord.PCMVolumeTransformer(nextcord.FFmpegPCMAudio(
|
||||
"/downloadTemp/" + currentTitle[str(result['Server'])] + ".mp3")) # convert the audio player to a volume audio player
|
||||
player[str(result['Server'])].play(audioPlayer[str(result['Server'])], after=lambda e: playerFinished(e, result['Server']))
|
||||
await sleep(0)
|
||||
starttime[str(result['Server'])] = time()
|
||||
|
||||
audioPlayer[str(result['Server'])].volume = defaultVolume / 100
|
||||
except: # if a error occurs, print it to console and try to connect to the channel
|
||||
log_exception("Radio loop iteration failed for guild=%s", result.get('Server'))
|
||||
try:
|
||||
if(result['enabled'] > 0):
|
||||
channel = bot.get_channel(result['PlayChannel'])
|
||||
if(channel != None):
|
||||
player[str(result['Server'])] = await channel.connect()
|
||||
else:
|
||||
try:
|
||||
radio_logger.warning("Cannot connect to guild=%s channel=%s because the channel was not found", result['Server'], result['PlayChannel'])
|
||||
except:
|
||||
radio_logger.warning("Disabling player for guild=%s after repeated connection failures", result['Server'])
|
||||
dbcursor.execute("UPDATE PLAYER SET enabled=0 WHERE Server=" + str(result['Server']))
|
||||
except:
|
||||
log_exception("Radio recovery failed for guild=%s", result.get('Server'))
|
||||
await sleep(1) # just give the bot some time to handle his stuff
|
||||
dbcursor.close()
|
||||
|
||||
def playerFinished(error, channel):
|
||||
radio_logger.info("Finished playing on channel %s with error %s", channel, error)
|
||||
player[str(channel)].stop()
|
||||
await runtime.sleep(3)
|
||||
|
|
|
|||
|
|
@ -5,3 +5,4 @@ yt_dlp
|
|||
aiohttp
|
||||
PyMySQL
|
||||
cryptography
|
||||
mafic
|
||||
|
|
|
|||
104
app/runtime.py
Normal file
104
app/runtime.py
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
#!/usr/bin/env python3
|
||||
from json import loads
|
||||
from os import mkdir
|
||||
from shutil import rmtree
|
||||
from threading import Thread
|
||||
from time import sleep as sleept
|
||||
from time import time
|
||||
from traceback import format_exc
|
||||
import logging
|
||||
import os
|
||||
|
||||
import mafic
|
||||
import nextcord
|
||||
import pymysql
|
||||
from aiohttp import ClientSession
|
||||
from nextcord.ext import commands
|
||||
from pycountry import countries as countryDecode
|
||||
from requests import get as getr
|
||||
from yt_dlp import YoutubeDL
|
||||
|
||||
from config import *
|
||||
from dummyPlayer import dummyPlayer
|
||||
|
||||
|
||||
os.environ["PYTHONIOENCODING"] = "utf-8"
|
||||
|
||||
LOG_LEVEL = logging.DEBUG if debugLog else logging.INFO
|
||||
logging.basicConfig(
|
||||
level=LOG_LEVEL,
|
||||
format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
|
||||
)
|
||||
|
||||
logger = logging.getLogger("discordyoutubemonitor")
|
||||
|
||||
player = {}
|
||||
audioPlayer = {}
|
||||
currentTitle = {}
|
||||
nextTitle = {}
|
||||
starttime = {}
|
||||
t = {}
|
||||
apikeyID = 0
|
||||
|
||||
logger.info("Bot using nextcord.py %s", nextcord.__version__)
|
||||
logger.info("Connecting to mysql backend")
|
||||
dbconnection = pymysql.connect(
|
||||
host=mysqlHostname,
|
||||
user=mysqlUsername,
|
||||
password=mysqlPassword,
|
||||
database=mysqlDatabase,
|
||||
autocommit=True,
|
||||
)
|
||||
logger.info("MySQL connection successful, checking download cache")
|
||||
|
||||
if not os.path.isdir("/downloadTemp"):
|
||||
mkdir("/downloadTemp")
|
||||
|
||||
logger.info("Download cache ready, generating bot object")
|
||||
intents = nextcord.Intents.default()
|
||||
intents.guilds = True
|
||||
intents.messages = True
|
||||
intents.voice_states = True
|
||||
intents.message_content = False
|
||||
bot = commands.Bot(command_prefix=commands.when_mentioned, case_insensitive=True, intents=intents)
|
||||
lavalink_pool = mafic.NodePool(bot)
|
||||
lavalink_ready = False
|
||||
logger.info("Bot object generated")
|
||||
|
||||
|
||||
def initialize_guild_state(guild_id):
|
||||
guild_key = str(guild_id)
|
||||
if guild_key not in t:
|
||||
t[guild_key] = Thread(target=lambda: None)
|
||||
if guild_key not in player:
|
||||
player[guild_key] = dummyPlayer()
|
||||
if guild_key not in nextTitle:
|
||||
nextTitle[guild_key] = ""
|
||||
return guild_key
|
||||
|
||||
|
||||
def initialize_dummy_players():
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
try:
|
||||
dbcursor.execute("SELECT * FROM PLAYER")
|
||||
request = dbcursor.fetchall()
|
||||
for result in request:
|
||||
guild_id = initialize_guild_state(result["Server"])
|
||||
logger.debug("Initialized dummy player for guild %s", result["Server"])
|
||||
finally:
|
||||
dbcursor.close()
|
||||
|
||||
|
||||
async def connect_lavalink():
|
||||
global lavalink_ready
|
||||
if lavalink_ready:
|
||||
return
|
||||
|
||||
await lavalink_pool.create_node(
|
||||
host=lavalinkHost,
|
||||
port=lavalinkPort,
|
||||
label=lavalinkLabel,
|
||||
password=lavalinkPassword,
|
||||
secure=lavalinkSecure,
|
||||
)
|
||||
lavalink_ready = True
|
||||
110
app/setup.py
110
app/setup.py
|
|
@ -1,108 +1,4 @@
|
|||
#!/usr/bin/env python3
|
||||
from asyncio import sleep # to wait a specific time
|
||||
from datetime import datetime, timedelta
|
||||
from json import loads # json parser
|
||||
from os import mkdir, remove, rename # basic file system operations
|
||||
from os.path import isfile # to check if a file exist
|
||||
from shutil import rmtree # to delete folder
|
||||
from threading import Thread # used for the download task
|
||||
from time import time # used for timestamp in the current command
|
||||
from traceback import format_exc
|
||||
import nextcord # import nextcord.py
|
||||
from nextcord.ext import commands, tasks # import the command module from nextcord.py
|
||||
# to decode the countries from the YouTube API
|
||||
from pycountry import countries as countryDecode
|
||||
from yt_dlp import YoutubeDL # youtube-downloader
|
||||
from time import sleep as sleept
|
||||
# simmilar library to requests, but running async
|
||||
from aiohttp import ClientSession
|
||||
import logging
|
||||
import os
|
||||
from dummyPlayer import dummyPlayer
|
||||
from permissionCheck import *
|
||||
from requests import get as getr
|
||||
"""Compatibility module for the refactored runtime layout."""
|
||||
|
||||
os.environ["PYTHONIOENCODING"] = "utf-8"
|
||||
|
||||
LOG_LEVEL = logging.DEBUG if debugLog else logging.INFO
|
||||
logging.basicConfig(
|
||||
level=LOG_LEVEL,
|
||||
format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
|
||||
)
|
||||
logger = logging.getLogger("discordyoutubemonitor")
|
||||
|
||||
player = {} # the Player for the music Bot
|
||||
audioPlayer = {}
|
||||
currentTitle = {}
|
||||
nextTitle = {}
|
||||
starttime = {}
|
||||
t = {}
|
||||
apikeyID = 0
|
||||
|
||||
logger.info("Bot using nextcord.py %s", nextcord.__version__)
|
||||
|
||||
logger.info("Connecting to mysql backend")
|
||||
dbconnection = pymysql.connect(host=mysqlHostname, user=mysqlUsername, password=mysqlPassword, database=mysqlDatabase, autocommit=True)
|
||||
# make a database cursor (to execute SQL commands)
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
logger.info("MySQL connection successful, checking download cache")
|
||||
|
||||
|
||||
if not os.path.isdir("/downloadTemp"):
|
||||
mkdir("/downloadTemp")
|
||||
|
||||
logger.info("Download cache ready, generating bot object")
|
||||
|
||||
intents = nextcord.Intents.default()
|
||||
intents.guilds = True
|
||||
intents.messages = True
|
||||
intents.voice_states = True
|
||||
intents.message_content = False
|
||||
|
||||
bot = commands.Bot(command_prefix=commands.when_mentioned, case_insensitive=True, intents=intents)
|
||||
|
||||
logger.info("Bot object generated, generating dummy player")
|
||||
|
||||
|
||||
def log_exception(message, *args):
|
||||
logger.error(message, *args)
|
||||
logger.debug(format_exc())
|
||||
|
||||
|
||||
def interaction_author(interaction):
|
||||
return getattr(interaction, "user", None) or getattr(interaction, "author", None)
|
||||
|
||||
|
||||
async def send_response(interaction, *args, **kwargs):
|
||||
if interaction.response.is_done():
|
||||
return await interaction.followup.send(*args, **kwargs)
|
||||
return await interaction.response.send_message(*args, **kwargs)
|
||||
|
||||
|
||||
async def defer_response(interaction, ephemeral=False):
|
||||
if not interaction.response.is_done():
|
||||
await interaction.response.defer(ephemeral=ephemeral)
|
||||
|
||||
|
||||
def interaction_log_context(interaction):
|
||||
guild_id = interaction.guild.id if interaction.guild else "dm"
|
||||
channel_id = interaction.channel.id if interaction.channel else "unknown"
|
||||
user = interaction_author(interaction)
|
||||
user_id = user.id if user else "unknown"
|
||||
command_name = interaction.application_command.qualified_name if interaction.application_command else "unknown"
|
||||
return "guild=%s channel=%s user=%s command=%s" % (guild_id, channel_id, user_id, command_name)
|
||||
|
||||
def nothing(): # we need this to initialize the new threads at bootup
|
||||
pass
|
||||
|
||||
|
||||
dbcursor.execute("SELECT * FROM PLAYER") # get all Radios
|
||||
request = dbcursor.fetchall() # get the entries
|
||||
for result in request: # rotate through all entries
|
||||
t[str(result['Server'])] = Thread(target=nothing) # create a dummy task
|
||||
player[str(result['Server'])] = dummyPlayer()
|
||||
logger.debug("Initialized dummy player for guild %s", result['Server'])
|
||||
|
||||
dbcursor.close()
|
||||
|
||||
logger.info("Dummy player state generated")
|
||||
from runtime import * # noqa: F401,F403
|
||||
from utils import * # noqa: F401,F403
|
||||
|
|
|
|||
37
app/utils.py
Normal file
37
app/utils.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
from traceback import format_exc
|
||||
|
||||
import runtime
|
||||
|
||||
|
||||
def log_exception(message, *args):
|
||||
runtime.logger.error(message, *args)
|
||||
runtime.logger.debug(format_exc())
|
||||
|
||||
|
||||
def interaction_author(interaction):
|
||||
return getattr(interaction, "user", None) or getattr(interaction, "author", None)
|
||||
|
||||
|
||||
async def send_response(interaction, *args, **kwargs):
|
||||
if interaction.response.is_done():
|
||||
return await interaction.followup.send(*args, **kwargs)
|
||||
return await interaction.response.send_message(*args, **kwargs)
|
||||
|
||||
|
||||
async def defer_response(interaction, ephemeral=False):
|
||||
if not interaction.response.is_done():
|
||||
await interaction.response.defer(ephemeral=ephemeral)
|
||||
|
||||
|
||||
def interaction_log_context(interaction):
|
||||
guild_id = interaction.guild.id if interaction.guild else "dm"
|
||||
channel_id = interaction.channel.id if interaction.channel else "unknown"
|
||||
user = interaction_author(interaction)
|
||||
user_id = user.id if user else "unknown"
|
||||
command_name = interaction.application_command.qualified_name if interaction.application_command else "unknown"
|
||||
return "guild=%s channel=%s user=%s command=%s" % (guild_id, channel_id, user_id, command_name)
|
||||
|
||||
|
||||
def nothing():
|
||||
pass
|
||||
|
||||
|
|
@ -23,4 +23,11 @@ inviteURL = ""
|
|||
|
||||
# heart beat
|
||||
heartBeatEnabled = False
|
||||
heartBeatURL = "https://google.de"
|
||||
heartBeatURL = "https://google.de"
|
||||
|
||||
# lavalink / dave-compatible voice backend
|
||||
lavalinkHost = "127.0.0.1"
|
||||
lavalinkPort = 2333
|
||||
lavalinkPassword = "youshallnotpass"
|
||||
lavalinkSecure = False
|
||||
lavalinkLabel = "main"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue