Skip to content

Commit 7113aa1

Browse files
hiromaraigue
authored andcommitted
first commit
0 parents  commit 7113aa1

File tree

8 files changed

+1008
-0
lines changed

8 files changed

+1008
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
*.yml
2+
*.log

LICENSE.txt

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
twbot2.rb Copyright (c) 2010-, Maraigue
2+
3+
All rights reserved.
4+
5+
Redistribution and use in source and binary forms, with or without
6+
modification, are permitted provided that the following conditions
7+
are met:
8+
9+
Redistributions of source code must retain the above copyright
10+
notice, this list of conditions and the following disclaimer.
11+
Redistributions in binary form must reproduce the above copyright
12+
notice, this list of conditions and the following disclaimer in the
13+
documentation and/or other materials provided with the distribution.
14+
Neither the name of the Maraigue nor the names of its contributors
15+
may be used to endorse or promote products derived from this
16+
software without specific prior written permission.
17+
18+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21+
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22+
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23+
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24+
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25+
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27+
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28+
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29+
POSSIBILITY OF SUCH DAMAGE.

README.md

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
## About twbot2.rb
2+
3+
**twbot2.rb** is a Twitter bot framework combined with OAuth token manager.
4+
5+
Since version 0.21, the program was remade to be used non-Twitter-bot Twitter program, where twbot2.rb works as only an OAuth token manager.
6+
7+
## Example
8+
9+
We have only to define what the bot tweets as the following format:
10+
11+
$ cat greeting_bot.rb
12+
13+
require "./twbot2"
14+
TwBot.create("config-file.yml", "log-file.log").cui_menu do
15+
# Define what the bot tweets here
16+
tweet_list = ["Good morning", "Good afternoon", "Good evening"]
17+
[tweet_list[rand(tweet_list.size)]] # return as an array
18+
end
19+
20+
To add the content to be tweeted to the configuration file, call with the parameter "load".
21+
22+
$ ruby greeting_bot.rb load
23+
24+
Running mode 'load'...
25+
[2000-00-00 00:00:00 +0000]
26+
[cui_menu:mode=load]
27+
28+
To post a tweet stored in "load" mode, call with the parameter "load".
29+
30+
$ ruby greeting_bot.rb post
31+
32+
Running mode 'post'...
33+
[2000-00-00 00:00:00 +0000]
34+
[cui_menu:mode=post]<Error in updating> A String (user name) or Hash
35+
(parameters) is required as the argument (NilClass given)
36+
* Perhaps you have not finished authentication. Try 'greeting_bot.rb init' to
37+
register the default user.
38+
ArgumentError: A String (user name) or Hash (parameters) is required as the
39+
argument (NilClass given)
40+
* Perhaps you have not finished authentication. Try 'greeting_bot.rb init' to
41+
register the default user.
42+
(snipped)
43+
44+
However, it fails since no user is registered in the configuration file yet. So let's initialize the configuration file with a default user.
45+
46+
$ ruby greeting_bot.rb init
47+
48+
Running mode 'init'...
49+
============================================================
50+
Here I help you register your bot account to the setting file.
51+
Please prepare a browser to retrieve OAuth tokens.
52+
53+
Input the screen name of your bot account.
54+
============================================================
55+
User name >h_hiro_
56+
============================================================
57+
To retrieve OAuth token of user "h_hiro_":
58+
(1) Log in Twitter with a browser for user "h_hiro_".
59+
(2) Access the URL below with same browser:
60+
https://api.twitter.com/oauth/authorize?oauth_token=****
61+
(3) Check the application name is "twbot2.rb" and
62+
click "Allow" link in the browser.
63+
(4) Input the shown number (PIN number).
64+
To cancel, input nothing and press enter key.
65+
============================================================
66+
PIN number >*******
67+
User "h_hiro_" is successfully registered.
68+
Default user is set to @h_hiro_.
69+
[2000-00-00 00:00:00 +0000]
70+
[cui_menu:mode=init]
71+
72+
Then try again "post" mode. A tweet will be appear in Twitter.
73+
74+
$ ruby greeting_bot.rb post
75+
76+
Running mode 'post'...
77+
[Updated!] Good afternoon
78+
[2000-00-00 00:00:00 +0000]
79+
[cui_menu:mode=post](A tweet has been posted)
80+
81+
For more details, see the Wiki (https://github.com/maraigue/twbot2.rb/wiki).

greeting_bot.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
require "./twbot2"
2+
TwBot.create("config-file.yml", "log-file.log").cui_menu do
3+
# Define what the bot talks here
4+
tweet_list = ["Good morning", "Good afternoon", "Good evening"]
5+
[tweet_list[rand(tweet_list.size)]] # return as an array
6+
end

twbot2-apiaccess.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#!/usr/bin/env ruby
2+
# -*- coding: utf-8 -*-
3+
4+
require "./twbot3"
5+
6+
# Example: show the name of the authenticated user
7+
#
8+
# To run the example,
9+
# - First try "ruby twbot3.rb run". The content in the block
10+
# (extracting authenticated user) will be conducted and probably
11+
# results in the message you are not authenticated.
12+
# - Then try "ruby twbot3.rb init". A dialog will appear to
13+
# authenticate you. (You need a browser)
14+
# - Finally try "ruby twbot3.rb run" again. A message you have
15+
# been authenticated will be shown.
16+
17+
TwBot.create("config-apiaccess.yml", "error-apiaccess.log").cui_menu do
18+
# Define what to do in the block for TwBot#cui_menu.
19+
json_src = auth_http.get("/1.1/account/verify_credentials.json").body
20+
data = JSON.load(json_src)
21+
puts "You are authenticated as @#{data["screen_name"]}."
22+
end

twbot2-countreplies.rb

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#!/usr/bin/env ruby
2+
# -*- coding: utf-8 -*-
3+
4+
# =============================================================
5+
# An example of Twitter bot by twbot2
6+
# (old style; also available in version 0.20)
7+
#
8+
# In the old style, the messages to be tweetes should be
9+
# defined in 'load_data' method in the class inheriting
10+
# 'TwBot'.
11+
# Messages should be returned as an array of strings.
12+
# (Array entries may be 'Array's or 'Hash'es; see the document)
13+
#
14+
# This example is to fetch mentions to the bot and tweet the
15+
# number of new mentions.
16+
# =============================================================
17+
18+
$: << File.dirname(__FILE__)
19+
20+
require "twbot2"
21+
require "rubygems"
22+
require "json"
23+
24+
class ReplyCounter < TwBot
25+
def load_data
26+
# ---------- fetch replies ----------
27+
28+
# downloading the JSON
29+
response = auth_http.get("/1.1/statuses/mentions_timeline.json")
30+
json = JSON.load(response.body)
31+
32+
# extracting only message IDs
33+
mentions_ids = json.elements.map{ |x| x["id"] }
34+
35+
# ---------- exclude old replies ----------
36+
37+
# If you create a new key in the Hash @config,
38+
# this will be kept automatically in the config file.
39+
@config['last_id'] ||= 0
40+
41+
# keeping the newest ID among the downloaded mentions
42+
new_last_id = mentions_ids.first
43+
44+
# excluding the IDs representing old messages
45+
mentions_ids.reject!{ |m_id| m_id < @config['last_id'] }
46+
47+
# renewing the newest ID
48+
@config['last_id'] = new_last_id
49+
50+
# ---------- return the message to be posted ----------
51+
# (as an array)
52+
["#{mentions_ids.size} new replies found!"]
53+
end
54+
end
55+
56+
self_path = File.dirname(__FILE__)
57+
ARGV.each do |mode|
58+
ReplyCounter.new mode, "#{self_path}/config-countreplies.yml", "#{self_path}/error-countreplies.log"
59+
end

twbot2-rsspost.rb

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#!/usr/bin/env ruby
2+
# -*- coding: utf-8 -*-
3+
4+
# =============================================================
5+
# An example of Twitter bot by twbot2
6+
# (new style; available since version 0.21)
7+
#
8+
# In the new style, the messages to be tweetes should be
9+
# defined in the block attached to twbot2_instance#cui_menu
10+
# method.
11+
# Messages should be returned as an array of strings.
12+
# (Array entries may be 'Array's or 'Hash'es; see the document)
13+
#
14+
# Note that TwBot.new runs a bot code (because of backward
15+
# compatibility; see also the example twbot2-countreplies.rb).
16+
# To only create an instance, call TwBot.create method.
17+
#
18+
# This example is to fetch an RSS and tweet the new entries.
19+
# To run this program, use commands like these:
20+
# ruby twbot2-rsspost.rb init # Authenticate user to post the tweets
21+
# ruby twbot2-rsspost.rb load # Load RSS and add messages to the list
22+
# ruby twbot2-rsspost.rb post # Post one message in the list
23+
# ruby twbot2-rsspost.rb post post # Post two messages in the list
24+
# ruby twbot2-rsspost.rb load post # Load RSS and add messages to the list,
25+
# # and post one message in the list
26+
# =============================================================
27+
28+
RSS_URL = "http://d.hatena.ne.jp/maraigue/rss"
29+
30+
require "cgi"
31+
require "open-uri"
32+
require "./twbot3"
33+
34+
SELFDIR = File.dirname(__FILE__)
35+
TwBot.create("#{SELFDIR}/config-rsspost.yml", "#{SELFDIR}/error-rsspost.log").cui_menu do
36+
# Download RSS
37+
buf = nil
38+
open(RSS_URL){ |file| buf = file.read }
39+
40+
result = []
41+
@config["already_retrieved"] ||= ""
42+
newest_entry = false
43+
44+
# Retrieve entries in RSS
45+
# (It is better to use REXML library; this program omits it
46+
# for simpleness.)]
47+
buf.scan(/<item.*?>.*?<\/item>/m).each do |entry|
48+
# Extract titles and URLs of entries from downloaded RSS
49+
title = nil
50+
entry.scan(/<title>(.*?)<\/title>/){|tmp| title = CGI.escapeHTML(tmp[0])}
51+
link = nil
52+
entry.scan(/<link>(.*?)<\/link>/){|tmp| link = CGI.escapeHTML(tmp[0])}
53+
54+
# Ignore entries already retrieved by this program
55+
#
56+
# NOTE: @config["..."] values are kept for the next running
57+
# of the program.
58+
break if link == @config["already_retrieved"]
59+
60+
# Adds a message to the list to be tweeted later.
61+
#
62+
# Because RSS stores entries from newer one, to post messages in the
63+
# original order, the message have to be added to the bottom of the
64+
# array 'result'.
65+
result.unshift(TwBot."[AUTO POST] #{link} #{title}") if title && link
66+
67+
# Keep the URL of the newest entry in the data retrieved now
68+
unless newest_entry
69+
newest_entry = true
70+
@config["already_retrieved"] = link
71+
end
72+
end
73+
74+
75+
# Set logged message
76+
@logmsg = "(#{result.size} post added)"
77+
78+
# Return the result
79+
#
80+
# NOTE: the returned value must be an array of tweets when a bot
81+
# is constructed (called by 'ruby SCRIPTNAME.rb load')
82+
result
83+
end

0 commit comments

Comments
 (0)