1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
## Twitter bot in ruby using xmpp4r-simple (Jabber).
## Erik Kastner <kastner@gmail.com>

## twitter_bot.rb
#!/usr/bin/env ruby

require 'rubygems'
require 'xmpp4r-simple'
require 'twitter'
require 'syslog'

class TwitterBot < Jabber::Simple
  
  TWITTER_JABBER = "twitter@twitter.com"
  
  def self.log(message)
    Syslog.open($0, Syslog::LOG_PID | Syslog::LOG_CONS) { |s| s.warning message }
  end
  
  def initialize(twitter_username, twitter_password, jabber_account, jabber_password)
    @twitter = Twitter::Base.new(twitter_username, twitter_password)
    super(jabber_account, jabber_password)
  end
  
  def log(message)
    TwitterBot.log(message)
  end
  
  def say(message)
    deliver(TWITTER_JABBER, message)
  end
  
  def direct_message(to, message)
    deliver(TWITTER_JABBER, "d #{to} #{message}")
  end
  
  def user(id_or_screen_name)
    @twitter.user(id_or_screen_name)
  end
end

## my_bot.rb
#!/usr/bin/env ruby

$:.unshift("../")
require 'rubygems'
require 'simple-daemon'
require 'lib/twitter_bot'
require 'activerecord'
require "yaml"

# require 'ruby-debug'

WORKING_DIR = "/tmp/bingo-bot/"
DEBUG = true

class MyBot < TwitterBot
  def initialize(twitter_username, twitter_password, jabber_account, jabber_password)
    super
    @bot_name = twitter_username
  end
  
  def go
    received_messages { |message| deal_with(message.body) }
  end
  
  def deal_with(message)
    log(message) if DEBUG
    case message
    when /^(.*):\s*@#{@bot_name}:?\s*(.*)\s*$/i # @ reply
      user, command = $1, $2
      log("@reply from #{user} / #{command}") if DEBUG
      handle_reply(user, command)
    when /Direct from (.*):\n([^\n]+)\n/
      user, command = $1, $2
      log("#{user} / #{command}") if DEBUG
      handle_dm(user, command)
    end
  end
  
  def end
    disconnect
  end
end

class BotRunner < SimpleDaemon::Base
  `mkdir -p #{WORKING_DIR}` # just make sure the working dir exists
  SimpleDaemon::WORKING_DIRECTORY = WORKING_DIR
  
  def self.start
    TwitterBot.log("start up") if DEBUG
    initialize_envrionment

    @bot = MyBot.new(@bot_settings["twitter_user"], @bot_settings["twitter_pass"], @bot_settings["jabber_acct"], @bot_settings["jabber_pass"])
    loop do
      begin
        @bot.go
      rescue => e
        TwitterBot.log(e.inspect) if DEBUG
      end
      sleep(2)
    end
  end

  def self.stop
    @bingo.end
  end  
end

def initialize_envrionment
  raise "Missing file #{ENV["HOME"]}/bot.yml" unless File.exists?("#{ENV["HOME"]}/bot.yml")

  @bot_settings = YAML::load_file("#{ENV["HOME"]}/bot.yml")
end

BotRunner.daemonize