switch to slash commands
This commit is contained in:
parent
25bf82887e
commit
9f5be79020
13 changed files with 517 additions and 405 deletions
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
__pycache__
|
||||
|
|
@ -1,11 +1,12 @@
|
|||
from radioCommands import *
|
||||
startuptime = time()
|
||||
|
||||
@bot.command(pass_context=True, brief="print some informations about the bot")
|
||||
async def about(ctx):
|
||||
@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))
|
||||
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)
|
||||
|
|
@ -13,4 +14,4 @@ async def about(ctx):
|
|||
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)
|
||||
await ctx.send(embed=embed)
|
||||
await send_response(interaction, embed=embed)
|
||||
|
|
|
|||
49
app/bot.py
49
app/bot.py
|
|
@ -1,28 +1,59 @@
|
|||
#!/usr/bin/env python3
|
||||
print("welcome to DJ Bot, initialising files")
|
||||
logger.info("Welcome to DJ Bot, initializing files")
|
||||
from heartBeatTask import *
|
||||
|
||||
@bot.event # print the username and id to the console and change the game status
|
||||
async def on_ready():
|
||||
print('Startup complete, logged in as:')
|
||||
print("username: " + bot.user.name)
|
||||
print("userid: " + str(bot.user.id))
|
||||
print('--------------------------------')
|
||||
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)
|
||||
|
||||
|
||||
@bot.event
|
||||
async def on_guild_join(guild):
|
||||
logger.info("Joined guild %s (%s) with %s members", guild.name, guild.id, guild.member_count)
|
||||
|
||||
|
||||
@bot.event
|
||||
async def on_guild_remove(guild):
|
||||
logger.info("Removed from guild %s (%s)", guild.name, guild.id)
|
||||
|
||||
|
||||
@bot.event
|
||||
async def on_application_command(interaction):
|
||||
logger.info("Slash command received: %s", interaction_log_context(interaction))
|
||||
|
||||
|
||||
@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)
|
||||
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)
|
||||
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)
|
||||
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
|
||||
|
||||
print("commands loaded, starting monitor task")
|
||||
logger.info("Commands loaded, starting monitor task")
|
||||
bot.loop.create_task(checkVideosTask()) # create the monitoring task
|
||||
print("task started, starting player task")
|
||||
logger.info("Monitor task started, starting player task")
|
||||
bot.loop.create_task(checkForNextTrack()) # create the radio task
|
||||
|
||||
print("all task started, starting bot")
|
||||
logger.info("All tasks started, starting heartbeat and bot login")
|
||||
hearBeat.start()
|
||||
bot.run(token) # start the bot with the options in config.py
|
||||
bot.run(token) # start the bot with the options in config.py
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
from generalCommands import *
|
||||
|
||||
video_logger = logging.getLogger("discordyoutubemonitor.video")
|
||||
|
||||
async def checkVideo(results):
|
||||
global apikeyID
|
||||
global dbconnection
|
||||
|
|
@ -24,18 +26,16 @@ async def checkVideo(results):
|
|||
"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
|
||||
print("loading " + str("https://www.googleapis.com/youtube/v3/videos?part=contentDetails,statistics&id=" +
|
||||
results['videoID'] + "&key=" + apikey[
|
||||
apikeyID]))
|
||||
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)
|
||||
print("switched to next APIkey")
|
||||
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")
|
||||
print("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
|
||||
else:
|
||||
repeat = False
|
||||
|
|
@ -64,14 +64,14 @@ async def checkVideo(results):
|
|||
blocked = "worldwide"
|
||||
# if we can't find the "blocked" tag in the json, it fails and no country is blocked (yet)
|
||||
except:
|
||||
print("failed fetching data for " + results['videoID'])
|
||||
video_logger.warning("Failed fetching region restriction data for video=%s", results['videoID'])
|
||||
blocked = results['blockedIn']
|
||||
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):
|
||||
print("Diff detected in " + results['videoID'] + " old: " + results['blockedIn'] + " new: " + blocked)
|
||||
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
|
||||
|
||||
|
|
@ -102,14 +102,14 @@ async def checkVideo(results):
|
|||
dbcursor.execute(
|
||||
"DELETE FROM VIDEOS WHERE id = %s", [results['id']])
|
||||
except: # skip if error occurs
|
||||
print_exc()
|
||||
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
|
||||
try:
|
||||
message = await bot.get_channel(results['channelID']).fetch_message(results['messageID'])
|
||||
except nextcord.errors.NotFound:
|
||||
print("Message with DB ID " + str(results["id"]) + " not found")
|
||||
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
|
||||
|
|
@ -118,11 +118,11 @@ async def checkVideo(results):
|
|||
try:
|
||||
embed.remove_field(2) # clear the like and view fields
|
||||
except:
|
||||
print_exc()
|
||||
video_logger.debug("Embed field 2 missing while refreshing video=%s", results['videoID'])
|
||||
try:
|
||||
embed.remove_field(1)
|
||||
except:
|
||||
print_exc()
|
||||
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(
|
||||
|
|
@ -164,7 +164,7 @@ async def checkVideo(results):
|
|||
await sleep(1)
|
||||
await message.edit(embed=embed) # send the updated embed
|
||||
except:
|
||||
print_exc()
|
||||
log_exception("Failed to refresh monitor embed for video=%s", results['videoID'])
|
||||
dbcursor.close()
|
||||
except:
|
||||
print_exc()
|
||||
log_exception("checkVideo failed for DB row id=%s", results.get('id'))
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
from checkVideo import *
|
||||
|
||||
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)
|
||||
|
|
@ -15,13 +17,13 @@ async def checkVideos(): # This task checks all Videos for new changes in block
|
|||
dbcursor.execute(
|
||||
"SELECT * FROM VIDEOS") # get all videos
|
||||
request = dbcursor.fetchall() # get the entries
|
||||
video_batch_logger.info("Checking %s monitored videos", len(request))
|
||||
for results in request: # rotate through all entries
|
||||
try:
|
||||
await checkVideo(results)
|
||||
except:
|
||||
print("Failed to fetch data for " + results)
|
||||
print_exc()
|
||||
log_exception("Failed to fetch data for video=%s", results.get('videoID'))
|
||||
await sleep(1)
|
||||
except:
|
||||
print_exc()
|
||||
log_exception("checkVideos batch run failed")
|
||||
dbcursor.close()
|
||||
|
|
|
|||
|
|
@ -1,28 +1,30 @@
|
|||
from setup import *
|
||||
from requests import get as getNonAsync
|
||||
|
||||
download_logger = logging.getLogger("discordyoutubemonitor.download")
|
||||
|
||||
def download(url, serverID):
|
||||
global nextTitle
|
||||
global apikeyID
|
||||
|
||||
print("loading playlist " + url)
|
||||
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])
|
||||
|
||||
startKeyID = apikeyID
|
||||
while(r.status_code == 403):
|
||||
apikeyID+=1
|
||||
print("switching download to next api key. new id is " + str(apikeyID))
|
||||
download_logger.warning("Playlist download quota hit, switching to API key index %s", apikeyID)
|
||||
if (apikeyID >= len(apikey)):
|
||||
apikeyID = 0
|
||||
if (startKeyID == apikeyID):
|
||||
print("used up all API keys for YouTube, please add more")
|
||||
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
|
||||
|
||||
r = getNonAsync("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=" + playlist + "&key=" + apikey[apikeyID])
|
||||
|
||||
if(r.status_code != 200):
|
||||
print("recived status code " + str(r.status_code) + " aborting. Used API key ID was " +str(apikeyID))
|
||||
download_logger.error("Received status code %s while loading playlist for guild=%s with key index %s", r.status_code, serverID, apikeyID)
|
||||
return
|
||||
|
||||
playlistData = loads(r.text)
|
||||
|
|
@ -56,14 +58,14 @@ def download(url, serverID):
|
|||
nextTitle[str(serverID)] = videoID
|
||||
|
||||
if(isfile("/downloadTemp/" + videoID + ".mp3")): # delete (if exist) old entries
|
||||
print("file already downloaded: " + videoID + ".mp3")
|
||||
download_logger.info("File already downloaded for guild=%s video=%s", serverID, videoID)
|
||||
return
|
||||
|
||||
print("downloading track " + videoID)
|
||||
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:
|
||||
print_exc()
|
||||
log_exception("Track download failed for guild=%s video=%s", serverID, videoID)
|
||||
nextTitle[str(serverID)] = ""
|
||||
print("download failed, sleeping 60s")
|
||||
sleept(60) # wait 1 minute on fail, to not risk a ban
|
||||
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
|
||||
|
|
|
|||
|
|
@ -1,64 +1,91 @@
|
|||
from download import *
|
||||
|
||||
@bot.command(pass_context=True, hidden=True) # hide the command in the help
|
||||
async def register(ctx, registrationKey, server=None):
|
||||
|
||||
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.")
|
||||
|
||||
|
||||
def require_role_access(interaction):
|
||||
require_guild(interaction)
|
||||
if not checkRole(interaction):
|
||||
raise PermissionError("You are not allowed to use this command.")
|
||||
|
||||
|
||||
@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)
|
||||
if not server:
|
||||
print("using guild as server")
|
||||
server = ctx.guild.id
|
||||
# check if the key exists in the DB
|
||||
dbcursor.execute("SELECT * FROM registeredServer WHERE Server=" + str(server) + " AND registerKey=%s",[registrationKey])
|
||||
if(dbcursor.fetchone() == None):
|
||||
await ctx.send("wrong key") # if not send wrong key
|
||||
else: # else set the server to registered and send a success message
|
||||
dbcursor.execute("UPDATE registeredServer SET registered=1 WHERE Server=" +
|
||||
str(server) + " AND registerKey=%s", [registrationKey])
|
||||
await ctx.send("The Server has been registered and the bot can now be used.")
|
||||
dbcursor.close()
|
||||
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):
|
||||
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.")
|
||||
command_logger.info("Register succeeded for server %s", target_server)
|
||||
except Exception:
|
||||
log_exception("Register command failed: %s", interaction_log_context(interaction))
|
||||
await send_response(interaction, "Registration failed.", ephemeral=True)
|
||||
finally:
|
||||
dbcursor.close()
|
||||
|
||||
@bot.command(pass_context=True, brief="prints the ping time of the bot")
|
||||
@commands.check(checkRole) # check if the user is allowed to run this command
|
||||
async def ping(ctx): # prints the ping and the time the bot needed to process this command
|
||||
now = datetime.utcnow() # get the current time
|
||||
# substract the time the message was created from the current time 8in microsecconds), convert this to millisecconds and round
|
||||
delta = round(
|
||||
(now.microsecond - ctx.message.created_at.microsecond) / 1000)
|
||||
embed = nextcord.Embed(title=":ping_pong: | Pong!", description="```prolog\nLatency :: " + str(round(bot.latency * 1000)) +
|
||||
"ms\nResponse :: " + str(delta) + "ms```") # make the response, we format it as code and select prolog as language for nice cloloring
|
||||
|
||||
await ctx.send(embed=embed) # send the prepared message
|
||||
@bot.slash_command(description="Print the bot latency")
|
||||
async def ping(interaction: nextcord.Interaction):
|
||||
require_role_access(interaction)
|
||||
command_logger.info("Ping requested: %s", interaction_log_context(interaction))
|
||||
now = datetime.utcnow()
|
||||
created_at = interaction.created_at.replace(tzinfo=None)
|
||||
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```",
|
||||
)
|
||||
await send_response(interaction, embed=embed)
|
||||
|
||||
@bot.command(pass_context=True, brief="Allows a role to use the bot")
|
||||
@commands.check(checkRole) # check if the user is allowed to run this command
|
||||
async def addadmin(ctx, serverRole: nextcord.Role):
|
||||
|
||||
@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.execute("INSERT INTO adminRoles (Server, roleID) VALUES (%s, %s)",
|
||||
[ctx.guild.id, serverRole.id]) # inser the role ID in the database
|
||||
# send a answer to the user
|
||||
await ctx.send("Added " + serverRole.name + " to the list of Roles with bot access")
|
||||
dbcursor.close()
|
||||
try:
|
||||
require_role_access(interaction)
|
||||
dbcursor.execute("INSERT INTO adminRoles (Server, roleID) VALUES (%s, %s)", [interaction.guild.id, server_role.id])
|
||||
await send_response(interaction, "Added " + server_role.name + " to the list of Roles with bot access")
|
||||
command_logger.info("Added admin role %s on guild %s", server_role.id, interaction.guild.id)
|
||||
except Exception:
|
||||
log_exception("Addadmin failed: %s", interaction_log_context(interaction))
|
||||
await send_response(interaction, "Failed to add the role.", ephemeral=True)
|
||||
finally:
|
||||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.command(pass_context=True, brief="Disallows a role to use the bot")
|
||||
@commands.check(checkRole) # check if the user is allowed to run this command
|
||||
async def removeadmin(ctx, role: nextcord.Role):
|
||||
@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.execute("DELETE FROM adminRoles WHERE Server=%s AND roleID=%s",
|
||||
[ctx.guild.id, role.id]) # delete the role ID from the database
|
||||
# send the answer to the user
|
||||
await ctx.send("Removed " + role.name + " from the list of Roles with bot access")
|
||||
dbcursor.close()
|
||||
try:
|
||||
require_role_access(interaction)
|
||||
dbcursor.execute("DELETE FROM adminRoles WHERE Server=%s AND roleID=%s", [interaction.guild.id, role.id])
|
||||
await send_response(interaction, "Removed " + role.name + " from the list of Roles with bot access")
|
||||
command_logger.info("Removed admin role %s on guild %s", role.id, interaction.guild.id)
|
||||
except Exception:
|
||||
log_exception("Removeadmin failed: %s", interaction_log_context(interaction))
|
||||
await send_response(interaction, "Failed to remove the role.", ephemeral=True)
|
||||
finally:
|
||||
dbcursor.close()
|
||||
|
||||
@bot.command(pass_context=True, brief="changes the prefix of the bot")
|
||||
@commands.check(checkRole) # check if the user is allowed to run this command
|
||||
async def changePrefix(ctx, newPrefix):
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor.execute("DELETE from prefix where Server=%s", [ctx.guild.id])
|
||||
dbcursor.execute("INSERT INTO prefix(`prefix`,`Server`) VALUES (%s, %s)", [
|
||||
newPrefix, ctx.guild.id])
|
||||
await ctx.send("changed prefix for " + bot.user.name + " to " + newPrefix)
|
||||
dbcursor.close()
|
||||
|
||||
@bot.slash_command(description="Explain the slash-command migration")
|
||||
async def changeprefix(interaction: nextcord.Interaction):
|
||||
require_role_access(interaction)
|
||||
command_logger.info("Changeprefix requested after slash migration: %s", interaction_log_context(interaction))
|
||||
await send_response(interaction, "This bot now uses slash commands, so custom prefixes are no longer required.")
|
||||
|
|
|
|||
|
|
@ -3,4 +3,5 @@ from aboutCommand import *
|
|||
@tasks.loop(seconds=60)
|
||||
async def hearBeat():
|
||||
if(heartBeatEnabled):
|
||||
logger.debug("Heartbeat ping to %s", heartBeatURL)
|
||||
r = getr(heartBeatURL)
|
||||
|
|
|
|||
|
|
@ -1,116 +1,108 @@
|
|||
from checkVideos import *
|
||||
|
||||
|
||||
@bot.command(brief="Starts a new Monitoring job in this channel")
|
||||
@commands.check(checkRole) # check if the user is allowed to run this command
|
||||
@commands.check(checkIfPremium) #premium servers can use monitor
|
||||
async def monitor(ctx, youtubeVideoURL: str):
|
||||
command_logger = logging.getLogger("discordyoutubemonitor.commands.monitor")
|
||||
|
||||
|
||||
def require_monitor_access(interaction):
|
||||
require_role_access(interaction)
|
||||
if not checkIfPremium(interaction):
|
||||
raise PermissionError("This command is only available on registered premium servers.")
|
||||
|
||||
|
||||
@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)
|
||||
channelID = ctx.message.channel.id # get the ID of the channel
|
||||
try:
|
||||
require_monitor_access(interaction)
|
||||
await defer_response(interaction)
|
||||
channel_id = interaction.channel.id
|
||||
command_logger.info("Monitor requested: %s url=%s", interaction_log_context(interaction), youtube_video_url)
|
||||
|
||||
session = ClientSession()
|
||||
r = await session.get("https://www.youtube.com/oembed?format=json&url=" +
|
||||
youtubeVideoURL) # get some data of the youtube Video
|
||||
await session.close()
|
||||
response = loads(await r.text())
|
||||
# get the videoID (from the image path)
|
||||
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]) # insert the Video entry in the Database
|
||||
dbcursor.execute(
|
||||
"SELECT * FROM VIDEOS WHERE videoID=%s", [videoID])
|
||||
result = dbcursor.fetchone() # get the new entry
|
||||
session = ClientSession()
|
||||
r = await session.get("https://www.youtube.com/oembed?format=json&url=" + youtube_video_url)
|
||||
response = loads(await r.text())
|
||||
await session.close()
|
||||
|
||||
# make a new embed, the Title is the video name and it is linked to the Video on YouTube
|
||||
embed = nextcord.Embed(
|
||||
title=response["title"], description="", color=0xff0000, url="https://youtu.be/" + videoID)
|
||||
# add the blocked in field with the block data from the Database (default is waiting for data for new entries)
|
||||
embed.add_field(name="Blocked in", value=result['blockedIn'])
|
||||
# use the Video image as thubnail
|
||||
embed.set_thumbnail(url=response["thumbnail_url"])
|
||||
# send the embed to the chat
|
||||
message = await bot.get_channel(channelID).send(embed=embed)
|
||||
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])
|
||||
result = dbcursor.fetchone()
|
||||
|
||||
dbcursor.execute("UPDATE VIDEOS SET messageID = %s, channelID = %s WHERE videoID = %s", [
|
||||
message.id, channelID, result['videoID']]) # update the database entry and set the channelID and the messageID
|
||||
await ctx.message.delete() # delete the command to make this monitor
|
||||
embed = nextcord.Embed(title=response["title"], description="", color=0xff0000, url="https://youtu.be/" + videoID)
|
||||
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("SELECT * FROM VIDEOS WHERE messageID = %s", [
|
||||
message.id]) # get the sql row for the check task
|
||||
await checkVideo(dbcursor.fetchone())
|
||||
dbcursor.close()
|
||||
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])
|
||||
await checkVideo(dbcursor.fetchone())
|
||||
await send_response(interaction, "Monitoring created for `" + videoID + "`.")
|
||||
command_logger.info("Monitor created: guild=%s video=%s message=%s", interaction.guild.id, videoID, message.id)
|
||||
except Exception:
|
||||
log_exception("Monitor command failed: %s", interaction_log_context(interaction))
|
||||
await send_response(interaction, "Failed to create the monitor.", ephemeral=True)
|
||||
finally:
|
||||
dbcursor.close()
|
||||
|
||||
@bot.command(pass_context=True, brief="Change Settings of the YouTube Monitor")
|
||||
@commands.check(checkRole) # check if the user is allowed to run this command
|
||||
@commands.check(checkIfPremium) #premium servers can use monitor
|
||||
async def monitorsettings(ctx, settingName=None, *value: str):
|
||||
|
||||
@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)
|
||||
# check if the config is created, if not create it
|
||||
dbcursor.execute("SELECT * FROM monitorConfig WHERE Server=" + str(ctx.guild.id))
|
||||
if(dbcursor.fetchone() == None):
|
||||
dbcursor.execute(
|
||||
"INSERT INTO monitorConfig (Server) VALUES (" + str(ctx.guild.id) + ")")
|
||||
try:
|
||||
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) + ")")
|
||||
|
||||
if(settingName == None): # if there is no setting name specified, print the help
|
||||
await ctx.send("```\nTo use this command you have to specify a settings name:\n * viewCounter (0 = on; 1 = off)\n * likeCounter (0 = on; 1 = off)\n * style (0 = field; 1 = footer)\n * showLastUpdate (0 = on; 1 = off)\n * pingMessage (default @here)\n\nTo get the current status just enter the name of the setting and to change it add as seccond parameter the value```")
|
||||
return
|
||||
if(setting_name == None):
|
||||
await send_response(interaction, "Use `/monitorsettings setting_name:<name> value:<value>`.\nAvailable settings: `viewCounter`, `likeCounter`, `style`, `showLastUpdate`, `pingMessage`.")
|
||||
return
|
||||
|
||||
if(len(value) == 0): # if the value is not specified, print the current value of the setting
|
||||
dbcursor.execute("SELECT * FROM monitorConfig WHERE Server=" + str(
|
||||
ctx.guild.id))
|
||||
result = dbcursor.fetchone() # select the server config
|
||||
if (settingName == "viewCounter"): # check if the setting is view counter
|
||||
status = "off" # if yes, convert the answer from the DB to "human format"
|
||||
if(result['showViewCounter']):
|
||||
status = "on"
|
||||
await ctx.send(settingName + ": " + status) # send the answer
|
||||
elif (settingName == "likeCounter"):
|
||||
status = "off"
|
||||
if(result['showLikeCounter']):
|
||||
status = "on"
|
||||
await ctx.send(settingName + ": " + status)
|
||||
elif (settingName == "showLastUpdate"):
|
||||
status = "off"
|
||||
if(result['showLastUpdate']):
|
||||
status = "on"
|
||||
await ctx.send(settingName + ": " + status)
|
||||
elif (settingName == "style"):
|
||||
status = "field"
|
||||
if(result['likeAndViewsAsField']):
|
||||
status = "footer"
|
||||
await ctx.send(settingName + ": " + status)
|
||||
if(value is None):
|
||||
dbcursor.execute("SELECT * FROM monitorConfig WHERE Server=" + str(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'])
|
||||
else:
|
||||
await send_response(interaction, "Unknown setting.", ephemeral=True)
|
||||
return
|
||||
|
||||
elif(settingName == "pingMessage"):
|
||||
message = ""
|
||||
for entries in value:
|
||||
message = message + entries + " "
|
||||
message = message[:-1] # remove the space at the end
|
||||
dbcursor.execute("UPDATE monitorConfig SET pingMessage='" +
|
||||
message + "' WHERE Server=" + str(ctx.guild.id))
|
||||
await ctx.send("New message on block change is: " + message)
|
||||
if(setting_name == "pingMessage"):
|
||||
dbcursor.execute("UPDATE monitorConfig SET pingMessage=%s WHERE Server=" + str(interaction.guild.id), [value])
|
||||
await send_response(interaction, "New message on block change is: " + value)
|
||||
return
|
||||
|
||||
else:
|
||||
state = "0"
|
||||
state = "1" if value == "1" else "0"
|
||||
tableName = ""
|
||||
if (settingName == "viewCounter") or (settingName == "likeCounter") or (settingName == "showLastUpdate"):
|
||||
if (value[0] == "1"):
|
||||
state = "1"
|
||||
if(settingName == "viewCounter"):
|
||||
tableName = "showViewCounter"
|
||||
elif(settingName == "likeCounter"):
|
||||
tableName = "showLikeCounter"
|
||||
elif(settingName == "showLastUpdate"):
|
||||
tableName = "showLastUpdate"
|
||||
elif (settingName == "style"):
|
||||
if (value[0] == "1"):
|
||||
state = "1"
|
||||
if(setting_name == "viewCounter"):
|
||||
tableName = "showViewCounter"
|
||||
elif(setting_name == "likeCounter"):
|
||||
tableName = "showLikeCounter"
|
||||
elif(setting_name == "showLastUpdate"):
|
||||
tableName = "showLastUpdate"
|
||||
elif(setting_name == "style"):
|
||||
tableName = "likeAndViewsAsField"
|
||||
|
||||
dbcursor.execute("UPDATE monitorConfig SET " + tableName +
|
||||
"=" + state + " WHERE Server=" + str(ctx.guild.id))
|
||||
await ctx.send("Updated " + settingName + ", new state is " + str(value[0]))
|
||||
dbcursor.close()
|
||||
if tableName == "":
|
||||
await send_response(interaction, "Unknown setting.", ephemeral=True)
|
||||
return
|
||||
|
||||
dbcursor.execute("UPDATE monitorConfig SET " + tableName + "=" + state + " WHERE Server=" + str(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))
|
||||
await send_response(interaction, "Failed to update monitor settings.", ephemeral=True)
|
||||
finally:
|
||||
dbcursor.close()
|
||||
|
|
|
|||
|
|
@ -2,6 +2,9 @@ import pymysql
|
|||
from config import *
|
||||
from random import choice
|
||||
from string import ascii_letters # used for the registration string generation
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger("discordyoutubemonitor.permissions")
|
||||
|
||||
dbconnection = pymysql.connect(host=mysqlHostname, user=mysqlUsername, password=mysqlPassword, database=mysqlDatabase, autocommit=True)
|
||||
|
||||
|
|
@ -11,9 +14,12 @@ dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
|||
def checkRole(ctx): # this function checks, if the user has the roles to run the command (admins are always permitted)
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
if(ctx.author.id == adminUserID):
|
||||
author = getattr(ctx, "user", None) or getattr(ctx, "author", None)
|
||||
if author is None:
|
||||
return False
|
||||
if(author.id == adminUserID):
|
||||
return True
|
||||
for roles in ctx.author.roles: # rotate through the roles the user has
|
||||
for roles in author.roles: # rotate through the roles the user has
|
||||
try:
|
||||
dbcursor.execute(
|
||||
"SELECT * FROM adminRoles WHERE Server=" + str(ctx.guild.id)) # get all videos
|
||||
|
|
@ -33,7 +39,7 @@ def checkRole(ctx): # this function checks, if the user has the roles to run th
|
|||
|
||||
dbcursor.close()
|
||||
# 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 ctx.message.author.guild_permissions.administrator
|
||||
return author.guild_permissions.administrator
|
||||
|
||||
|
||||
def checkIfMusikEnabled(ctx):
|
||||
|
|
@ -47,8 +53,9 @@ def checkIfMusikEnabled(ctx):
|
|||
# make a database cursor (to execute SQL commands)
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor.execute("SELECT * FROM PLAYER WHERE Server=" + str(ctx.guild.id))
|
||||
result = dbcursor.fetchone()
|
||||
dbcursor.close()
|
||||
return dbcursor.fetchone() != None
|
||||
return result != None
|
||||
|
||||
|
||||
def checkIfMusikNotEnabled(ctx):
|
||||
|
|
@ -56,22 +63,22 @@ def checkIfMusikNotEnabled(ctx):
|
|||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
# 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()
|
||||
dbcursor.close()
|
||||
return dbcursor.fetchone() == None
|
||||
return result == None
|
||||
|
||||
def checkIfPremium(ctx):
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor.execute("SELECT * FROM registeredServer WHERE Server=" + str(ctx.message.guild.id))
|
||||
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.message.guild.id) + ", '" + registerKey + "')") # make a database entry for the server with the key
|
||||
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
|
||||
print("register Key for " + ctx.message.guild.name +
|
||||
": " + registerKey) # print the key to the console
|
||||
logger.warning("Register key for %s (%s): %s", ctx.guild.name, ctx.guild.id, registerKey)
|
||||
dbcursor.close()
|
||||
return False
|
||||
else:
|
||||
|
|
|
|||
|
|
@ -1,195 +1,213 @@
|
|||
from radioTask import *
|
||||
|
||||
@bot.command(pass_context=True, brief="stops the music and disconnects the bot")
|
||||
@commands.check(checkRole) # check if the user is allowed to run this command
|
||||
@commands.check(checkIfMusikEnabled) # check if the radio is configured
|
||||
async def stop(ctx):
|
||||
|
||||
command_logger = logging.getLogger("discordyoutubemonitor.commands.radio")
|
||||
|
||||
|
||||
def require_music_enabled(interaction):
|
||||
require_role_access(interaction)
|
||||
if not checkIfMusikEnabled(interaction):
|
||||
raise PermissionError("Music is not configured on this server.")
|
||||
|
||||
|
||||
def require_music_disabled(interaction):
|
||||
require_role_access(interaction)
|
||||
if not checkIfMusikNotEnabled(interaction):
|
||||
raise PermissionError("Music is already configured on this server.")
|
||||
|
||||
|
||||
@bot.slash_command(description="Stop the music and disconnect the bot")
|
||||
async def stop(interaction: nextcord.Interaction):
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
global player
|
||||
|
||||
# disable the palyer in the database
|
||||
dbcursor.execute(
|
||||
"UPDATE PLAYER SET enabled=0 WHERE Server=" + str(ctx.guild.id))
|
||||
|
||||
try: # try to stop the player, if fails it was already stopped
|
||||
player[str(ctx.guild.id)].stop()
|
||||
await sleep(1) # wait one seccond to give him time to stop
|
||||
except:
|
||||
pass
|
||||
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
try:
|
||||
# disconnect the bot from the channel
|
||||
await player[str(ctx.guild.id)].disconnect()
|
||||
except:
|
||||
pass
|
||||
|
||||
# send message to the user
|
||||
dbcursor.close()
|
||||
await ctx.message.channel.send("The bot was stopped by <@" + str(ctx.message.author.id) + ">")
|
||||
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)
|
||||
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))
|
||||
await send_response(interaction, "Failed to stop the bot.", ephemeral=True)
|
||||
finally:
|
||||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.command(pass_context=True, brief="connects the bot to the music channel and starts the playback")
|
||||
@commands.check(checkRole) # check if the user is allowed to run this command
|
||||
@commands.check(checkIfMusikEnabled) # check if the radio is configured
|
||||
async def start(ctx):
|
||||
@bot.slash_command(description="Start the playback")
|
||||
async def start(interaction: nextcord.Interaction):
|
||||
global dbconnection, t
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor.execute("UPDATE PLAYER SET enabled=1 WHERE Server=" +
|
||||
str(ctx.guild.id)) # enable the player in the database
|
||||
|
||||
t[str(ctx.guild.id)] = Thread(target=nothing) # create a dummy task
|
||||
player[str(ctx.guild.id)] = dummyPlayer()
|
||||
# send a answer to the user
|
||||
await ctx.message.channel.send("The bot was started by <@" + str(ctx.message.author.id) + ">")
|
||||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.command(pass_context=True, brief="changes the voice Channel the bot is listening to")
|
||||
@commands.check(checkRole) # check if the user is allowed to run this command
|
||||
@commands.check(checkIfMusikEnabled) # check if the radio is configured
|
||||
async def changeChannel(ctx):
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
global player
|
||||
global start
|
||||
|
||||
try:
|
||||
channel = ctx.author.voice.channel # get the current voicechat the user is in
|
||||
except: # if we can't get the voice channel, the user is not in one ==> print an error
|
||||
await ctx.message.channel.send("To change the MusicBot Channel you have to connect to a channel and the run this command")
|
||||
require_music_enabled(interaction)
|
||||
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()
|
||||
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))
|
||||
await send_response(interaction, "Failed to start the bot.", ephemeral=True)
|
||||
finally:
|
||||
dbcursor.close()
|
||||
return
|
||||
|
||||
dbcursor.execute("UPDATE PLAYER SET PlayChannel=%s WHERE Server=%s",
|
||||
[channel.id, ctx.guild.id]) # update the channel in the database
|
||||
try: # try to stop the player (if fails it was already stopped)
|
||||
player[str(ctx.guild.id)].stop()
|
||||
except:
|
||||
pass
|
||||
await sleep(1) # wait one seccond to realy stop
|
||||
# disconnect the player from the current channel (the reconnect will be done automatic by the daemon)
|
||||
await player[str(ctx.guild.id)].disconnect()
|
||||
dbcursor.close()
|
||||
|
||||
|
||||
# with this command you can change the volume of the music bot
|
||||
@bot.command(brief="changes the volume (in percent) of the music bot")
|
||||
@commands.check(checkIfMusikEnabled) # check if the radio is configured
|
||||
async def volume(ctx, volume: int):
|
||||
global audioPlayer # import the global audio player
|
||||
if(volume < 0) or (volume > 100): # check if the volume is in a percent range
|
||||
await ctx.message.channel.send("Volume has to be between 0 and 100")
|
||||
else:
|
||||
audioPlayer[str(ctx.guild.id)].volume = volume / \
|
||||
100 # change the volume
|
||||
|
||||
|
||||
@bot.command(pass_context=True, brief="skips the current mix")
|
||||
@commands.check(checkRole) # check if the user is allowed to run this command
|
||||
@commands.check(checkIfMusikEnabled) # check if the radio is configured
|
||||
async def skip(ctx):
|
||||
global player
|
||||
# for skipping the current track, we need only stop the current one, the rest the daemon will do automatic
|
||||
player[str(ctx.guild.id)].stop()
|
||||
|
||||
|
||||
@bot.command(pass_context=True, brief="prints the current name of the track")
|
||||
@commands.check(checkIfMusikEnabled) # check if the radio is configured
|
||||
async def current(ctx):
|
||||
global currentTitle # import global variables
|
||||
global starttime
|
||||
ydl_opts = { # youtube-dl arguments (we need some data here, but don't use them)
|
||||
'format': 'bestaudio/best',
|
||||
'postprocessors': [{
|
||||
'key': 'FFmpegExtractAudio',
|
||||
'preferredcodec': 'mp3',
|
||||
'preferredquality': '192',
|
||||
}],
|
||||
}
|
||||
video_data = YoutubeDL(ydl_opts).extract_info("https://youtu.be/" + currentTitle[str(
|
||||
ctx.guild.id)], download=False) # download the details of the current playing Track
|
||||
embed = nextcord.Embed(title=video_data["title"], description="", url="https://youtu.be/" + currentTitle[str(
|
||||
ctx.guild.id)]) # make a embed to send to the user
|
||||
# set as image the video tumbnail
|
||||
embed.set_thumbnail(url=video_data["thumbnail"])
|
||||
embed.add_field(name="time", value=str(timedelta(seconds=round(
|
||||
time() - starttime[str(ctx.guild.id)])))) # add a field for the current time
|
||||
|
||||
await ctx.message.channel.send(embed=embed)
|
||||
|
||||
|
||||
@bot.command(pass_context=True, brief="Set the Music Player Channel and YouTube Playlist to use")
|
||||
@commands.check(checkRole) # check if the user is allowed to run this command
|
||||
@commands.check(checkIfMusikNotEnabled) # check if the radio is not enabled
|
||||
async def setupmusic(ctx, Channel: nextcord.VoiceChannel):
|
||||
@bot.slash_command(description="Change the voice channel the bot is listening to")
|
||||
async def changechannel(interaction: nextcord.Interaction):
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
# check if the Server is already configured
|
||||
dbcursor.execute("SELECT * FROM PLAYER WHERE Server=" + str(ctx.guild.id))
|
||||
if(dbcursor.fetchone() != None):
|
||||
dbcursor.execute("SELECT * FROM prefix WHERE Server=" +
|
||||
str(ctx.guild.id)) # get the current prefix
|
||||
result = dbcursor.fetchone()
|
||||
if(result == None):
|
||||
currentPrefix = prefix
|
||||
else:
|
||||
currentPrefix = result['prefix']
|
||||
# send error message with contact to admin user
|
||||
await ctx.send("Bot is already configured on this Server, please try to start it with " + currentPrefix + "start or contact me if you need future assistance (<@" + str(adminUserID) + ">)")
|
||||
|
||||
dbcursor.execute("INSERT INTO PLAYER (PlayChannel, Server, youtubeChannelID) VALUES (%s, %s, %s)",
|
||||
(Channel.id, ctx.guild.id, defaultPlaylistURL)) # save the Settings in the DB
|
||||
# create a dummy downloader task (to bypass failing later)
|
||||
t[str(ctx.guild.id)] = Thread(target=nothing)
|
||||
|
||||
# send the anser to the user
|
||||
await ctx.send("Setup complete, " + bot.user.name + " should now connect to <#" + str(Channel.id) + "> and start playing Music soon.")
|
||||
dbcursor.close()
|
||||
|
||||
@bot.command(pass_context=True, brief="restart the player (sometimes the bot hangs and you need this command)")
|
||||
@commands.check(checkRole)
|
||||
@commands.check(checkIfMusikEnabled)
|
||||
async def restart(ctx):
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
print("restarting bot on " + str(ctx.guild.id))
|
||||
global player
|
||||
await ctx.send("restarting music bot, please wait one moment")
|
||||
|
||||
# disable the palyer in the database
|
||||
dbcursor.execute(
|
||||
"UPDATE PLAYER SET enabled=0 WHERE Server=" + str(ctx.guild.id))
|
||||
|
||||
try: # try to stop the player, if fails it was already stopped
|
||||
player[str(ctx.guild.id)].stop()
|
||||
await sleep(1) # wait one seccond to give him time to stop
|
||||
except:
|
||||
pass
|
||||
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
try:
|
||||
# disconnect the bot from the channel
|
||||
await player[str(ctx.guild.id)].disconnect()
|
||||
except:
|
||||
pass
|
||||
await sleep(10) # wait 10 sec
|
||||
|
||||
dbcursor.execute("UPDATE PLAYER SET enabled=1 WHERE Server=" +
|
||||
str(ctx.guild.id)) # enable the player in the database
|
||||
t[str(ctx.guild.id)] = Thread(target=nothing) # create a dummy task
|
||||
player[str(ctx.guild.id)] = dummyPlayer()
|
||||
dbcursor.close()
|
||||
require_music_enabled(interaction)
|
||||
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)
|
||||
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()
|
||||
await send_response(interaction, "Playback channel updated to <#" + str(channel.id) + ">")
|
||||
except Exception:
|
||||
log_exception("Changechannel failed: %s", interaction_log_context(interaction))
|
||||
await send_response(interaction, "Failed to change the channel.", ephemeral=True)
|
||||
finally:
|
||||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.command(pass_context=True, brief="changes the playlist for the music bot")
|
||||
@commands.check(checkRole)
|
||||
@commands.check(checkIfMusikEnabled)
|
||||
@commands.check(checkIfPremium)
|
||||
async def changePlaylist(ctx, newPlaylistURL: str):
|
||||
@bot.slash_command(description="Change the volume in percent")
|
||||
async def volume(interaction: nextcord.Interaction, volume: int):
|
||||
global audioPlayer
|
||||
try:
|
||||
require_music_enabled(interaction)
|
||||
command_logger.info("Volume requested: %s volume=%s", interaction_log_context(interaction), volume)
|
||||
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
|
||||
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")
|
||||
async def skip(interaction: nextcord.Interaction):
|
||||
global player
|
||||
try:
|
||||
require_music_enabled(interaction)
|
||||
command_logger.info("Skip requested: %s", interaction_log_context(interaction))
|
||||
player[str(interaction.guild.id)].stop()
|
||||
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)
|
||||
|
||||
|
||||
@bot.slash_command(description="Print the currently playing track")
|
||||
async def current(interaction: nextcord.Interaction):
|
||||
global currentTitle
|
||||
global starttime
|
||||
try:
|
||||
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)]))))
|
||||
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")
|
||||
async def setupmusic(interaction: nextcord.Interaction, channel: nextcord.VoiceChannel):
|
||||
global dbconnection
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
dbcursor.execute("UPDATE PLAYER SET youtubeChannelID = %s WHERE Server = %s", [
|
||||
newPlaylistURL, ctx.guild.id])
|
||||
player[str(ctx.guild.id)].stop()
|
||||
await ctx.send("changed Playlist to `" + newPlaylistURL + "`")
|
||||
dbcursor.close()
|
||||
try:
|
||||
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) + ">)")
|
||||
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.")
|
||||
except Exception:
|
||||
log_exception("Setupmusic failed: %s", interaction_log_context(interaction))
|
||||
await send_response(interaction, "Failed to configure music playback.", ephemeral=True)
|
||||
finally:
|
||||
dbcursor.close()
|
||||
|
||||
|
||||
@bot.slash_command(description="Restart the player")
|
||||
async def restart(interaction: nextcord.Interaction):
|
||||
global dbconnection
|
||||
global player
|
||||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
try:
|
||||
require_music_enabled(interaction)
|
||||
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()
|
||||
except Exception:
|
||||
log_exception("Restart command failed: %s", interaction_log_context(interaction))
|
||||
await send_response(interaction, "Failed to restart the player.", ephemeral=True)
|
||||
finally:
|
||||
dbcursor.close()
|
||||
|
||||
|
||||
@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)
|
||||
try:
|
||||
require_music_enabled(interaction)
|
||||
if not checkIfPremium(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()
|
||||
await send_response(interaction, "changed Playlist to `" + new_playlist_url + "`")
|
||||
except Exception:
|
||||
log_exception("Changeplaylist failed: %s", interaction_log_context(interaction))
|
||||
await send_response(interaction, "Failed to change the playlist.", ephemeral=True)
|
||||
finally:
|
||||
dbcursor.close()
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
from monitorCommands import *
|
||||
|
||||
radio_logger = logging.getLogger("discordyoutubemonitor.radio")
|
||||
|
||||
async def checkForNextTrack():
|
||||
global dbconnection
|
||||
global audioPlayer # import global variables
|
||||
|
|
@ -11,6 +13,7 @@ async def checkForNextTrack():
|
|||
dbcursor = dbconnection.cursor(pymysql.cursors.DictCursor)
|
||||
|
||||
await bot.wait_until_ready() # wait until the bot is fully loaded
|
||||
radio_logger.info("Radio playback loop started")
|
||||
while(True):
|
||||
try:
|
||||
dbcursor.execute(
|
||||
|
|
@ -27,6 +30,7 @@ async def checkForNextTrack():
|
|||
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
|
||||
try:
|
||||
nextChannelTitle = nextTitle[str(result['Server'])]
|
||||
|
|
@ -39,7 +43,7 @@ async def checkForNextTrack():
|
|||
isPlaying = False
|
||||
|
||||
if not t[str(result['Server'])].is_alive() and nextChannelTitle == "" and not isfile("/downloadTemp/" + nextChannelTitle + ".mp3"):
|
||||
print("start download")
|
||||
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
|
||||
|
|
@ -49,14 +53,14 @@ async def checkForNextTrack():
|
|||
servername = result['Server']
|
||||
enabled = result['enabled']
|
||||
fileExist = isfile("/downloadTemp/" + nextChannelTitle + ".mp3")
|
||||
print(f"not playing on {servername}. Next file name: {nextChannelTitle} (file exist: {fileExist}) bot enabled on this server: {enabled}")
|
||||
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)
|
||||
print("playing " + currentTitle[str(result['Server'])] + ".mp3")
|
||||
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']))
|
||||
|
|
@ -65,7 +69,7 @@ async def checkForNextTrack():
|
|||
|
||||
audioPlayer[str(result['Server'])].volume = defaultVolume / 100
|
||||
except: # if a error occurs, print it to console and try to connect to the channel
|
||||
print_exc()
|
||||
log_exception("Radio loop iteration failed for guild=%s", result.get('Server'))
|
||||
try:
|
||||
if(result['enabled'] > 0):
|
||||
channel = bot.get_channel(result['PlayChannel'])
|
||||
|
|
@ -73,15 +77,15 @@ async def checkForNextTrack():
|
|||
player[str(result['Server'])] = await channel.connect()
|
||||
else:
|
||||
try:
|
||||
print(f"cant connect to {bot.get_guild(result['Server']).name}, channel not found")
|
||||
radio_logger.warning("Cannot connect to guild=%s channel=%s because the channel was not found", result['Server'], result['PlayChannel'])
|
||||
except:
|
||||
print(f"disabling player for {result['Server']}")
|
||||
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:
|
||||
print_exc()
|
||||
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):
|
||||
print(f"finished playing on channel {channel} with error {error}")
|
||||
radio_logger.info("Finished playing on channel %s with error %s", channel, error)
|
||||
player[str(channel)].stop()
|
||||
|
|
|
|||
74
app/setup.py
74
app/setup.py
|
|
@ -7,7 +7,7 @@ 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 print_exc # to print error to console (and not fail)
|
||||
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
|
||||
|
|
@ -24,8 +24,12 @@ from requests import get as getr
|
|||
|
||||
os.environ["PYTHONIOENCODING"] = "utf-8"
|
||||
|
||||
if(debugLog):
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
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 = {}
|
||||
|
|
@ -35,38 +39,59 @@ starttime = {}
|
|||
t = {}
|
||||
apikeyID = 0
|
||||
|
||||
print("Bot using nextcord.py " + str(nextcord.__version__))
|
||||
logger.info("Bot using nextcord.py %s", nextcord.__version__)
|
||||
|
||||
print("connecting to mysql backend")
|
||||
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)
|
||||
print("connection successful, starting clear of download cache")
|
||||
logger.info("MySQL connection successful, checking download cache")
|
||||
|
||||
|
||||
if not os.path.isdir("/downloadTemp"):
|
||||
mkdir("/downloadTemp")
|
||||
|
||||
print("download cache cleared, generating bot object")
|
||||
logger.info("Download cache ready, generating bot object")
|
||||
|
||||
async def determine_prefix(bot, message):
|
||||
try: # check if message is from a guild (not via PM)
|
||||
dbcursor.execute("SELECT * FROM prefix WHERE Server=" + str(
|
||||
message.guild.id))
|
||||
result = dbcursor.fetchone() # get the prefix from the Database
|
||||
if(result == None):
|
||||
# check if we got data, if yes use this prefix, if not use the default from the config
|
||||
currentPrefix = prefix
|
||||
else:
|
||||
currentPrefix = result['prefix']
|
||||
return currentPrefix
|
||||
except:
|
||||
return prefix # if message is PM use always the default
|
||||
intents = nextcord.Intents.default()
|
||||
intents.guilds = True
|
||||
intents.guild_messages = True
|
||||
intents.guild_voice_states = True
|
||||
intents.members = True
|
||||
intents.message_content = False
|
||||
|
||||
bot = commands.Bot(command_prefix=determine_prefix,
|
||||
case_insensitive=True) # configure the bot
|
||||
bot = commands.Bot(command_prefix=commands.when_mentioned, case_insensitive=True, intents=intents)
|
||||
|
||||
print("bot object generated, generating dummy player")
|
||||
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
|
||||
|
|
@ -77,7 +102,8 @@ 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()
|
||||
|
||||
print("dummy player generated")
|
||||
logger.info("Dummy player state generated")
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue