Class: WikiBot::Bot

Inherits:
Object
  • Object
show all
Defined in:
lib/wikibot.rb

Defined Under Namespace

Classes: LoginError

Constant Summary collapse

@@version =

WikiBot version

"0.2.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(username, password, options = {}) ⇒ Bot

Returns a new instance of Bot.



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
# File 'lib/wikibot.rb', line 42

def initialize(username, password, options = {})
  @cookies = OpenHash.new
  @api_hits = 0
  @page_writes = 0

  api = options[:api] || "http://en.wikipedia.org/w/api.php"
   = options[:auto_login] || false
  @readonly = options[:readonly] || false
  @debug = options[:debug] || false

  @config = {
    :username   => username,
    :password   => password,
    :api        => api,
    :logged_in  => false
  }.to_openhash

  # Set up cURL:
  @curl = Curl::Easy.new do |c|
    c.headers["User-Agent"] = "Mozilla/5.0 Curb/Taf2/0.2.8 WikiBot/#{@config.username}/#{@@version}"
    #c.enable_cookies        = true
    #c.cookiejar             = @@cookiejar
   end

   if 
end

Instance Attribute Details

#api_hitsObject (readonly)

How many times the API was queried



37
38
39
# File 'lib/wikibot.rb', line 37

def api_hits
  @api_hits
end

#configObject (readonly)

cattr_accessor :cookiejar # Filename where cookies will be stored



36
37
38
# File 'lib/wikibot.rb', line 36

def config
  @config
end

#debugObject

In debug mode, no writes will be made to the wiki



39
40
41
# File 'lib/wikibot.rb', line 39

def debug
  @debug
end

#page_writesObject

How many write operations were performed



38
39
40
# File 'lib/wikibot.rb', line 38

def page_writes
  @page_writes
end

#readonlyObject

Writes will not be made



40
41
42
# File 'lib/wikibot.rb', line 40

def readonly
  @readonly
end

Instance Method Details

#category(name) ⇒ Object



202
203
204
# File 'lib/wikibot.rb', line 202

def category(name)
  WikiBot::Category.new(self, name)
end

#edit_token(page = "Main Page") ⇒ Object



173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/wikibot.rb', line 173

def edit_token(page = "Main Page")
  return nil unless logged_in?
  @config.edit_token ||= begin
    data = {
      :action     => :query, 
      :prop       => :info,
      :intoken    => :edit,
      :titles     => page 
    }

    query_api(:get, data).query.pages.page.edittoken
  end
end

#format_date(date) ⇒ Object



206
207
208
209
210
211
# File 'lib/wikibot.rb', line 206

def format_date(date)
  # Formats a date into the Wikipedia format
  time = date.strftime("%H:%M")
  month = date.strftime("%B")
  "#{time}, #{date.day} #{month} #{date.year} (UTC)"
end

#logged_in?Boolean

Returns:

  • (Boolean)


133
134
135
# File 'lib/wikibot.rb', line 133

def logged_in?
  @config.logged_in 
end

#loginObject

Raises:



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/wikibot.rb', line 137

def 
  return if logged_in?

  data = {
    :action     => :login, 
    :lgname     => @config.username,
    :lgpassword => @config.password
  }

  response = query_api(:post, data).

  if response.result == "NeedToken"
    data = {
      :action     => :login, 
      :lgname     => @config.username,
      :lgpassword => @config.password,
      :lgtoken    => response.token
    }

    response = query_api(:post, data).
  end

  raise LoginError, response.result unless response.result == "Success"

  @config.cookieprefix = response.cookieprefix 
  @config.logged_in = true
end

#logoutObject



165
166
167
168
169
170
171
# File 'lib/wikibot.rb', line 165

def logout
  return unless logged_in?

  query_api(:post, { :action => :logout })
  @config.logged_in = false
  @config.edit_token = nil
end

#page(name) ⇒ Object



198
199
200
# File 'lib/wikibot.rb', line 198

def page(name)
  WikiBot::Page.new(self, name)
end

#query_api(method, raw_data = {}) ⇒ Object



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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/wikibot.rb', line 69

def query_api(method, raw_data = {})
  # Send a query to the API and handle the response
  url = @config.api
  raw_data = raw_data.to_openhash

  raw_data[:format] = :xml if raw_data.format.nil?

  # Setup cookie headers for the request
  @curl.headers["Cookie"] = @cookies.inject([]) do |memo, pair|
    key, val = pair
    memo.push(CGI::escape(key) + "=" + CGI::escape(val))
  end.join("; ") unless @cookies.nil?

  response_xml = {}

  while true
    if method == :post
      data = raw_data.to_post_fields
    elsif method == :get
      url = url.chomp("?") + "?" + raw_data.to_querystring
      data = nil
    end

    @curl.url = url
    @curl.headers["Expect"] = nil # MediaWiki will give a 417 error if Expect is set

    if @debug
      @curl.on_debug do |type, data|
         p data
      end
    end
    
    # If Set-Cookie headers are given in the response, set the cookies
    @curl.on_header do |data|
      header, text = data.split(":").map(&:strip)
      if header == "Set-Cookie"
        parts = text.split(";")
        cookie_name, cookie_value = parts[0].split("=")
        @cookies[cookie_name] = cookie_value
      end
      data.length
    end

    params = ["http_#{method}".to_sym]
    params.push(*data) unless data.nil? or (data.is_a? Array and data.empty?)
    @curl.send(*params)
    @api_hits += 1

    raise CurbError.new(@curl) unless @curl.response_code == 200
    
    xml = XmlSimple.xml_in(@curl.body_str, {'ForceArray' => false})
    raise APIError.new(xml['error']['code'], xml['error']['info']) if xml['error']

    response_xml.deep_merge! xml
    if xml['query-continue']
      raw_data.merge! xml['query-continue'][xml['query-continue'].keys.first]
    else
      break
    end
  end

  response_xml.to_openhash
end

#statsObject

Get wiki stats



188
189
190
191
192
193
194
195
196
# File 'lib/wikibot.rb', line 188

def stats
  data = {
    :action       => :query,
    :meta         => :siteinfo,
    :siprop       => :statistics
  }

  query_api(:get, data).query.statistics
end