Skip to content

Instantly share code, notes, and snippets.

@cg505
Last active May 14, 2016 17:29
Show Gist options
  • Select an option

  • Save cg505/ceb03e0faa520011760c91f3e20591d3 to your computer and use it in GitHub Desktop.

Select an option

Save cg505/ceb03e0faa520011760c91f3e20591d3 to your computer and use it in GitHub Desktop.
mc webhook setup
make a fifo for the server:
mkfifo serverin
run the server:
tail -f serverin | java -jar minecraft_server.jar nogui | tee serverout
run the webhook client:
ruby mcwh.rb -h "<slack webhook url>" -l serverout
run the webhook server:
RACK_ENV='production' ruby mcwh_serve.rb
require 'socket'
require 'uri'
require 'rest-client'
class MinecraftIrcBot
def initialize(options)
@uri = options[:hook]
@mclog = IO.popen("tail -f -n0 '#{options[:log]}'", "r")
end
def say(msg, usr=nil)
puts msg
payload = {}
if usr
payload = { 'text' => msg, 'username' => usr }
else
payload = { 'text' => msg }
end
RestClient.post @uri, payload.to_json, :content_type => :json, :accept => :json
end
def run
loop do
read, write, error = IO.select([@mclog])
if read.include? @mclog
msg = @mclog.gets
msg.gsub!(/^\[\d{2}:\d{2}:\d{2}\] /, '')
# puts msg
case msg.strip
when /^\[Server thread\/INFO\]: ([a-z0-9]*) joined the game/i
say("#{$1} has joined")
when /^\[Server thread\/INFO\]: ([a-z0-9]*) left the game/i
say("#{$1} has left")
when /^\[Server thread\/INFO\]: <([a-z0-9]*)> (.*)$/i
say($2, "#{$1} [mc]")
end
end
end
end
end
def parse
require 'optparse'
options = {}
optparse = OptionParser.new do |opts|
opts.banner = "Usage: #{$0} options"
opts.on("-h", "--hook WEBHOOK", "webhook URL") do |v|
options[:hook] = v
end
opts.on("-l", "--log LOG", "minecraft servers's log file for reading") do |v|
options[:log] = v
end
end
begin
optparse.parse!
required = [:hook, :log]
required.each do |arg|
raise OptionParser::MissingArgument, arg if options[arg].nil?
end
rescue OptionParser::InvalidOption, OptionParser::MissingArgument
puts $!.to_s
puts optparse
exit 1
end
options
end
def run
options = parse
bot = MinecraftIrcBot.new(options)
bot.run
end
run
require 'sinatra'
PIPE = "serverin"
TOKEN = "<insert outgoing-webhook token>"
post '/' do
if params['token'] && params['token'] == TOKEN && params['user_name'] != 'slackbot'
msg = params['user_name'] + ": " + params['text']
say_to_minecraft(msg)
end
end
def say_to_minecraft(msg)
msg = "say #{msg}"
puts msg
File.open(PIPE, "w") do |console|
console.puts msg
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment