stevetunes/main.rb
2021-12-19 17:53:07 -05:00

101 lines
2.2 KiB
Ruby

require 'discordrb'
require 'uri'
require 'optparse'
require 'shellwords'
options = {}
OptionParser.new do |opt|
opt.on("-t", "--token DISCORD_BOT_TOKEN") {|o| options[:bot_token] = o}
opt.on("-c", "--channel CHANNEL_ID") {|o| options[:channel_id] = Integer(o)}
end.parse!
if options.length == 0
puts "Need to specifiy token and channel"
exit
end
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)"
exit
end
puts "starting mpd if not already running"
system("systemctl start mpd") unless `ps aux | grep mpd` != ""
system("mpc clear")
system("mpc add /")
system("mpc repeat")
mpd = true
end
bot = Discordrb::Commands::CommandBot.new token: options[:bot_token], prefix: '!radio '
bot.command :start do |event|
system("mpc play")
event.respond("starting radio")
end
bot.command :stop do |event|
system("mpc stop")
event.respond("stoping radio")
end
bot.command :reload do |event|
event.respond("reloading queue")
system("mpc stop")
system("mpc clear")
system("mpc update")
system("mpc add /")
nil
end
bot.command :pause do |event|
event.respond("pausing playback")
system("mpc toggle")
nil
end
bot.command :skip do |event|
event.respond("skipping")
system("mpc next")
nil
end
bot.message(in: options[:channel_id],contains: "youtube.com") do |event|
urls = URI.extract(event.content)
if urls != ""
puts "Found #{urls}; downloading"
urls.each do |url|
res = `youtube-dl --ignore-errors --output \"spool/%(title)s.%(ext)s\" --extract-audio --audio-format mp3 #{url}`
if res
puts "Downloaded #{url}"
else
puts "error downloading #{url}"
end
end
if mpd
puts "telling mpd to refresh"
new_songs = Dir["spool/*.mp3"]
system("mv spool/*.mp3 tracks/")
system("mpc update")
new_songs.each do |song|
s = song.split("/")[1]
res = system("mpc add #{Shellwords.shellescape(s)}")
if res
puts "added #{s} to mpd"
else
puts "error adding #{s} to mpd"
end
end
end
end
end
bot.run