stevetunes/main.rb

141 lines
2.8 KiB
Ruby

#!/usr/bin/ruby
require 'discordrb'
require 'video_info'
require 'uri'
require 'optparse'
require 'shellwords'
require './mpc_shim'
require './util'
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)}
opt.on("-h", "--host MPD_HOST") {|o| options[:host] = o}
end.parse!
if ENV.has_key? "DISCORD_BOT_TOKEN"
options[:bot_token] = ENV["DISCORD_BOT_TOKEN"]
end
if ENV.has_key? "CHANNEL_ID"
options[:channel_id] = Integer(ENV["CHANNEL_ID"])
end
if ENV.has_key? "MPD_HOST"
options[:host] = ENV["MPD_HOST"]
end
if options.length == 0
puts "Need to specifiy token and channel"
exit
end
mpc = MpcShim.new(options[:host])
puts "creating spool and tracks directories"
`mkdir -p spool`
`mkdir -p tracks`
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
if mpc.running?
puts "starting mpd if not already running"
`systemctl start mpd` unless `ps aux | grep mpd` != ""
mpc.reset
end
end
bot = Discordrb::Commands::CommandBot.new token: options[:bot_token], prefix: '!radio '
bot.command :start do |event|
if mpc.running?
mpc.play
else
mpc.start
mpc.reset
mpc.play
end
event.respond("starting radio")
end
bot.command :stop do |event|
mpc.stop
event.respond("stoping radio")
end
bot.command :reload do |event|
event.respond("reloading queue")
mpc.stop
mpc.clear
mpc.update
mpc.add
event.respond("queue reloaded")
nil
end
bot.command :pause do |event|
event.respond("pausing playback")
mpc.toggle
nil
end
bot.command :skip do |event|
event.respond("skipping")
mpc.next()
nil
end
bot.command :shuffle do |event|
mpc.shuffle()
event.respond("shuffled queue")
nil
end
bot.command :nowplaying do |event|
event.respond(mpc.nowplaying)
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(msg.content)
end
update_mpd(mpc)
event.respond("done loading")
end
bot.message(in: options[:channel_id],contains: "youtube.com") do |event|
parse_songs_from_string(event.content)
update_mpd(mpc)
end
puts("logging into discord")
bot.run(true)
puts("starting main loop")
timer = 30
bot.online
bot.listening = ""
loop do
sleep timer
if !mpc.playing?
bot.online
current = mpc.nowplaying
status = bot.listening=current
if status != current
puts("tried to update listening status but got #{status} back")
elsif status == ""
puts("tried to update listening status but have empty now playing")
end
else
bot.listening = ""
bot.idle
end
end