real world fixes

This commit is contained in:
stryan 2021-12-19 19:04:55 -05:00
parent d1175cbe2f
commit 1a37af5aa9

54
main.rb
View File

@ -1,13 +1,34 @@
require 'discordrb'
require 'video_info'
require 'uri'
require 'optparse'
require 'shellwords'
def parse_songs_from_string(mpd,message)
def sanity_check_video(url)
if !url.include?("youtube")
return false
end
video = VideoInfo.new(url)
title = video.title
title.slice! " - YouTube Music"
if video.duration > 1200
puts "skipping #{url} since it's over 20 minutes"
return false
elsif File.exists?("tracks/#{title}.mp3") || File.exists?("spool/#{title}.mp3")
puts "#{url} already downloaded, not downloading again"
return false
end
return true
end
def parse_songs_from_string(message)
urls = URI.extract(message)
if urls.length != 0
puts "Found #{urls}; downloading"
urls.each do |url|
if sanity_check_video(url)
res = `youtube-dl --ignore-errors --output \"spool/%(title)s.%(ext)s\" --extract-audio --audio-format mp3 #{url}`
if res
puts "Downloaded #{url}"
@ -15,9 +36,17 @@ def parse_songs_from_string(mpd,message)
puts "error downloading #{url}"
end
end
if mpd
puts "telling mpd to refresh"
end
end
nil
end
def update_mpd()
new_songs = Dir["spool/*.mp3"]
if new_songs.length <= 0
return true
end
puts "telling mpd to refresh"
system("mv spool/*.mp3 tracks/")
system("mpc update")
new_songs.each do |song|
@ -30,9 +59,6 @@ def parse_songs_from_string(mpd,message)
end
end
end
end
nil
end
options = {}
OptionParser.new do |opt|
@ -49,7 +75,6 @@ puts "creating spool and tracks directories"
system("mkdir -p spool")
system("mkdir -p tracks")
mpd = false
if File.exists?("/usr/bin/mpd")
if !File.exists?("/usr/bin/mpc")
puts "Bailing since mpd exists but not mpc (which is needed to control mpd)"
@ -59,8 +84,8 @@ if File.exists?("/usr/bin/mpd")
system("systemctl start mpd") unless `ps aux | grep mpd` != ""
system("mpc clear")
system("mpc add /")
system("mpc shuffle")
system("mpc repeat")
mpd = true
end
bot = Discordrb::Commands::CommandBot.new token: options[:bot_token], prefix: '!radio '
@ -81,6 +106,7 @@ bot.command :reload do |event|
system("mpc clear")
system("mpc update")
system("mpc add /")
event.respond("queue reloaded")
nil
end
@ -96,19 +122,27 @@ bot.command :skip do |event|
nil
end
bot.command :shuffle do |event|
system("mpc shuffle")
event.respond("shuffled queue")
nil
end
bot.command :initialize do |event|
event.respond("loading last 50 messages from channel")
channel = bot.channel(options[:channel_id])
messages = channel.history(50)
messages.each do |msg|
parse_songs_from_string(mpd,msg.content)
parse_songs_from_string(msg.content)
end
update_mpd()
event.respond("done loading")
end
bot.message(in: options[:channel_id],contains: "youtube.com") do |event|
parse_songs_from_string(mpd,event.content)
parse_songs_from_string(event.content)
update_mpd()
end
bot.run