1
0
Fork 0
mirror of https://gitlab.jonasled.de/jonasled/discordbot synced 2024-10-03 07:48:58 +02:00

documentation

This commit is contained in:
Jonas Leder 2020-04-10 21:00:30 +02:00
parent 0ec2bd00db
commit f0ec1426f4

87
bot.py
View file

@ -58,10 +58,10 @@ async def on_ready():
@bot.event
async def on_message(message):#this will run on every message
if (message.guild == None) and "time" in message.content:
current_time = datetime.now().strftime("%H:%M:%S")
await message.author.send("Current time: " + current_time)
return
if (message.guild == None) and "time" in message.content: #this is for fun, if the user sends the bot private a message with time in it, send him the current time
current_time = datetime.now().strftime("%H:%M:%S")#get the time as string
await message.author.send("Current time: " + current_time)#send the current time to the user as DM
return#don't execute the rest (will fail in the next step)
print(str(message.author) + " sent: " + str(message.content) + ", latency: " + str(bot.latency) + " ms, Bot: " + str(message.author.bot)) #print some information about the message to the console
if(message.author.bot) or (message.author.id == bot.user.id): #check if the bot has written the message, if yes stop parsing it
@ -391,85 +391,84 @@ async def result(ctx, id):#this function prints the result of a poll
@bot.command(brief="adds a song to the playlist")
async def play(ctx, songURL : str):
global player
global player#import the global variables needed
global playerServer
global downloadQue
try:
channel = ctx.author.voice.channel#get the current voicechat the user is in
except:
except:#if we can't get the voice channel, the user is not in one ==> print an error
await ctx.message.channel.send("To use the music bot you have to be in a voice chat")
return
if(player == None):
if(player == None):#if the music player is currently not connected to a server
await channel.connect()#connect to this chat
player = ctx.voice_client #save the voice client for later use
playerServer = ctx.message.guild.id#save the music bot server id to variable
if(playerServer != ctx.message.guild.id):#check if the music bot is at the moment on this server
if(playerServer != ctx.message.guild.id):#check if the music bot is at the moment on this server, if not print a error message
await ctx.message.channel.send("The Bot is currently connected to a different channel, please wait until he is finished there")
return
r = get("https://www.youtube.com/oembed?format=json&url=" + songURL)
if(r.status_code != 200):
r = get("https://www.youtube.com/oembed?format=json&url=" + songURL)#check if video exists and get the title
if(r.status_code != 200):#if youtube doesn't respond with 200, there was an error finding the song
await ctx.message.channel.send("Can't find the song")
return
await ctx.message.channel.send("Adding `" + loads(r.text)["title"] + "` to que.")
downloadQue.append([loads(r.text)["html"].split("src=")[1][1:].split("\"")[0], loads(r.text)["title"]])
await ctx.message.channel.send("Adding `" + loads(r.text)["title"] + "` to que.")#print the user a status message
downloadQue.append([loads(r.text)["html"].split("src=")[1][1:].split("\"")[0], loads(r.text)["title"]])#add the title + the url to the download que
@bot.command(brief="skipps the current song in playlist")
async def skip(ctx):
global player
player.stop()
await ctx.message.channel.send("Skipped current song")
global player# import the global variable
player.stop()#stop the player (daemon think song enden ==> plays next one)
await ctx.message.channel.send("Skipped current song")#print the status to the console
@bot.command(brief="Prints the current music que")
async def que(ctx):
global titleQue
message = "**Musicbot Que:**\n **[current]** " + titleQue[0]
global titleQue#import the global variable
message = "**Musicbot Que:**\n **[current] " + titleQue[0] + " **"#prepare the message and add the current playing first in bold
for entries in titleQue[1:]:
for entries in titleQue[1:]: #scroll through the entries and add all songs to the resonse
message = message + "\n" + entries
await ctx.message.channel.send(message)
await ctx.message.channel.send(message)#send the prepared message
async def checkForNextSong():
global player
async def checkForNextSong():#background task, that runns every seccond and checks if the song ended
global player#import the global variables
global playerQue
global playerServer
global playing
global titleQue
while True:
if(player != None) and not player.is_playing() and (len(playerQue) > 0):
if(playing):
playerQue.remove(playerQue[0])
if(player != None) and not player.is_playing() and (len(playerQue) > 0):#check if the player is active and the song ended
if(playing):#check if the player played previously
remove(playerQue[0])#delete the last mp3 file
playerQue.remove(playerQue[0])#remove the first entry from the que and the first title
titleQue.remove(titleQue[0])
playing = False
if(len(playerQue) == 0):
print("que is empty")
playing = False#set playing to false
if(len(playerQue) == 0):#if the que is empty leave the voicechat and cleat the player variable
await player.disconnect()
player = None
playerServer = None
playerServer = None#allow everyone to invite the music bot
else:
playing = True
print("playing next song")
playing = True#set playing to true and play the next file
player.play(discord.FFmpegPCMAudio(playerQue[0]))
await sleep(1)
await sleep(1)#sleep 1 seccond and allo the bot to run different tasks
async def downloadAudioFiles():
global downloadQue
global downloadQue#import the global variables
global titleQue
while True:
if(len(downloadQue) > 0):
thread = Thread(target=backgroundDownloader, args=(downloadQue[0],))
thread.start()
downloadQue.remove(downloadQue[0])
while True:#run forever
if(len(downloadQue) > 0):#check if files ready to download
thread = Thread(target=backgroundDownloader, args=(downloadQue[0],))#if yes make a background task to download it
thread.start()#run the background task
downloadQue.remove(downloadQue[0])#remove the currently downloading file from the que
await sleep(1)
await sleep(1)#sleep 1 seccond and allo the bot to run different tasks
def backgroundDownloader(downloadQue):
global playerQue
global playerQue#import the global variables
global fileIndex
ydl_opts = { #youtube-dl arguments
'format': 'worstaudio/worst',
@ -480,12 +479,12 @@ def backgroundDownloader(downloadQue):
}],
'outtmpl': str(fileIndex) +'.%(ext)s',
}
with YoutubeDL(ydl_opts) as ydl:
fileIndex = fileIndex + 1 #add 1 to the file index counter (used to find the mp3 files easy later and that there are no files with the same name)
with YoutubeDL(ydl_opts) as ydl:#download the song with the arguments from up
ydl.download([downloadQue[0]])
playerQue.append(str(fileIndex) + ".mp3")
titleQue.append(downloadQue[1])
fileIndex = fileIndex + 1
playerQue.append(str(fileIndex) + ".mp3")#add the file to the que
titleQue.append(downloadQue[1])#add the title to the que (for que list)
bot.loop.create_task(checkForNextSong())
bot.loop.create_task(checkForNextSong())#start the music bot tasks in background
bot.loop.create_task(downloadAudioFiles())
bot.run(token, bot=botAccount)#start the bot with the options in config.py