require 'discordrb' require 'uri' require 'optparse' require 'shellwords' def parse_songs_from_string(mpd,message) urls = URI.extract(message) if urls.length != 0 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 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.command :initialize do |event| event.respond("loading last 20 songs from channel") channel = bot.channel(options[:channel_id]) messages = channel.history(20) messages.each do |msg| parse_songs_from_string(mpd,msg.content) end end bot.message(in: options[:channel_id],contains: "youtube.com") do |event| parse_songs_from_string(mpd,event.content) end bot.run