Class: Twitter::Client

Inherits:
Object
  • Object
show all
Includes:
ClassUtilMixin
Defined in:
lib/vendor/twitter/lib/twitter/client.rb,
lib/vendor/twitter/lib/twitter/config.rb,
lib/vendor/twitter/lib/twitter/extras.rb,
lib/vendor/twitter/lib/twitter/console.rb,
lib/vendor/twitter/lib/twitter/client/auth.rb,
lib/vendor/twitter/lib/twitter/client/base.rb,
lib/vendor/twitter/lib/twitter/client/user.rb,
lib/vendor/twitter/lib/twitter/client/graph.rb,
lib/vendor/twitter/lib/twitter/client/blocks.rb,
lib/vendor/twitter/lib/twitter/client/search.rb,
lib/vendor/twitter/lib/twitter/client/status.rb,
lib/vendor/twitter/lib/twitter/client/account.rb,
lib/vendor/twitter/lib/twitter/client/profile.rb,
lib/vendor/twitter/lib/twitter/client/timeline.rb,
lib/vendor/twitter/lib/twitter/client/favorites.rb,
lib/vendor/twitter/lib/twitter/client/messaging.rb,
lib/vendor/twitter/lib/twitter/client/friendship.rb

Overview

Used to query or post to the Twitter REST API to simplify code.

Constant Summary collapse

@@defaults =
{ :host => 'twitter.com',
               :port => 443,
               :protocol => :ssl,
               :search_host => 'search.twitter.com',
               :search_port => 80,
               :search_protocol => :http,
               :proxy_host => nil,
               :proxy_port => nil,
               :user_agent => "default",
               :application_name => 'Twitter4R',
               :application_version => Twitter::Version.to_version,
               :application_url => 'http://twitter4r.rubyforge.org',
               :source => 'twitter4r',
}
@@config =
Twitter::Config.new(@@defaults)
{
  :users => 'http://twitter.com/statuses/featured.json'
}
@@AUTHENTICATION_URIS =
{
  :verify => '/account/verify_credentials',
}
@@USER_URIS =
{
	:info => '/users/show',
	:friends => '/statuses/friends.json',
	:followers => '/statuses/followers.json',
}
@@GRAPH_URIS =
{
  :friends => '/friends/ids',
  :followers => '/followers/ids',
}
@@BLOCK_URIS =
{
  :add => '/blocks/create',
  :remove => '/blocks/destroy',
}
@@SEARCH_URIS =
{
  :basic => "/search.json",
}
@@STATUS_URIS =
{
	:get => '/statuses/show.json',
	:post => '/statuses/update.json',
	:delete => '/statuses/destroy.json',
	:reply => '/statuses/update.json',
}
@@ACCOUNT_URIS =
{
  :rate_limit_status => '/account/rate_limit_status',
}
@@PROFILE_URIS =
{
  :info => '/account/update_profile',
  :colors => '/account/update_profile_colors',
  :device => '/account/update_delivery_device',
}
@@TIMELINE_URIS =
{
  :public => '/statuses/public_timeline.json',
  :friends => '/statuses/friends_timeline.json',
  :friend => '/statuses/friends_timeline.json',
  :user => '/statuses/user_timeline.json',
  :me => '/statuses/user_timeline.json',
  :replies => '/statuses/replies.json',
}
@@FAVORITES_URIS =

Why Twitter.com developers can’t correctly document their API, I do not know!

{
  :add => '/favourings/create',
  :remove => '/favourings/destroy',
}
@@MESSAGING_URIS =
{
  :received => '/direct_messages.json',
  :sent => '/direct_messages/sent.json',
  :post => '/direct_messages/new.json',
  :delete => '/direct_messages/destroy',
}
@@FRIENDSHIP_URIS =
{
  :add => '/friendships/create',
  :remove => '/friendships/destroy',
}

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ClassUtilMixin

included

Class Method Details

.configure {|@@config| ... } ⇒ Object

Yields to given block to configure the Twitter4R API.

Yields:

  • (@@config)

Raises:



71
72
73
74
# File 'lib/vendor/twitter/lib/twitter/config.rb', line 71

def configure(&block)
  raise ArgumentError, "Block must be provided to configure" unless block_given?
  yield @@config
end

.from_config(config_file, env = 'test') ⇒ Object

Helper method mostly for irb shell prototyping.

Reads in login/password Twitter credentials from YAML file found at the location given by config_file that has the following format:

envname:
  login: mytwitterlogin
  password: mytwitterpassword

Where envname is the name of the environment like ‘test’, ‘dev’ or ‘prod’. The env argument defaults to ‘test’.

To use this in the shell you would do something like the following examples:

twitter = Twitter::Client.from_config('config/twitter.yml', 'dev')
twitter = Twitter::Client.from_config('config/twitter.yml')


24
25
26
27
# File 'lib/vendor/twitter/lib/twitter/console.rb', line 24

def from_config(config_file, env = 'test')
  yaml_hash = YAML.load(File.read(config_file))
  self.new yaml_hash[env]
end

Instance Method Details

#account_info(type = :rate_limit_status) ⇒ Object

Provides access to the Twitter rate limit status API.

You can find out information about your account status. Currently the only supported type of account status is the :rate_limit_status which returns a Twitter::RateLimitStatus object.

Example:

 = client.
puts .remaining_hits


15
16
17
18
19
20
21
22
23
# File 'lib/vendor/twitter/lib/twitter/client/account.rb', line 15

def (type = :rate_limit_status)
  connection = create_http_connection
  connection.start do |connection|
    response = http_connect do |conn|
      create_http_get_request(@@ACCOUNT_URIS[type])
    end
    bless_models(Twitter::RateLimitStatus.unmarshal(response.body))
  end
end

#authenticate?(login, password) ⇒ Boolean

Example:

client.authenticate?("osxisforlightweights", "l30p@rd_s^cks!")

Returns:

  • (Boolean)


12
13
14
# File 'lib/vendor/twitter/lib/twitter/client/auth.rb', line 12

def authenticate?(, password)
   verify_credentials(, password)
end

#block(action, value) ⇒ Object

Provides access to the Twitter Block API.

You can add and remove blocks to users using this method.

action can be any of the following values:

  • :add - to add a block, you would use this action value

  • :remove - to remove a block use this.

The value must be either the user screen name, integer unique user ID or Twitter::User object representation.

Examples:

screen_name = 'dictionary'
client.block(:add, 'dictionary')
client.block(:remove, 'dictionary')
id = 1260061
client.block(:add, id)
client.block(:remove, id)
user = Twitter::User.find(id, client)
client.block(:add, user)
client.block(:remove, user)

Raises:



28
29
30
31
32
33
34
# File 'lib/vendor/twitter/lib/twitter/client/blocks.rb', line 28

def block(action, value)
  raise ArgumentError, "Invalid friend action provided: #{action}" unless @@BLOCK_URIS.keys.member?(action)
  value = value.to_i unless value.is_a?(String)
  uri = "#{@@BLOCK_URIS[action]}/#{value}.json"
  response = http_connect {|conn| create_http_get_request(uri) }
  bless_model(Twitter::User.unmarshal(response.body))
end

#favorite(action, value) ⇒ Object

Provides access to the Twitter add/remove favorite API.

You can add and remove favorite status using this method.

action can be any of the following values:

  • :add - to add a status to your favorites, you would use this action value

  • :remove - to remove an status from your existing favorites list use this.

The value must be either the status object to add or remove or the integer unique status ID.

Examples:

id = 126006103423
client.favorite(:add, id)
client.favorite(:remove, id)
status = Twitter::Status.find(id, client)
client.favorite(:add, status)
client.favorite(:remove, status)

Raises:



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/vendor/twitter/lib/twitter/client/favorites.rb', line 41

def favorite(action, value)
  raise ArgumentError, "Invalid favorite action provided: #{action}" unless @@FAVORITES_URIS.keys.member?(action)
  value = value.to_i.to_s unless value.is_a?(String)
  uri = "#{@@FAVORITES_URIS[action]}/#{value}.json"
  case action
  when :add
    response = http_connect {|conn| create_http_post_request(uri) }
  when :remove
    response = http_connect {|conn| create_http_delete_request(uri) }
  end
  bless_model(Twitter::Status.unmarshal(response.body))
end

#favorites(options = nil) ⇒ Object

Provides access to the Twitter list favorites API.

You can access the authenticated [Twitter] user’s favorites list using this method.

By default you will receive the last twenty statuses added to your favorites list. To get a previous page you can provide options to this method. For example,

statuses = client.favorites(:page => 2)

The above one-liner will get the second page of favorites for the authenticated user.



16
17
18
19
20
21
# File 'lib/vendor/twitter/lib/twitter/client/favorites.rb', line 16

def favorites(options = nil)
  def uri_suffix(opts); opts && opts[:page] ? "?page=#{opts[:page]}" : ""; end
  uri = '/favorites.json' + uri_suffix(options)
  response = http_connect {|conn|	create_http_get_request(uri) }
  bless_models(Twitter::Status.unmarshal(response.body))
end

Provides access to the Featured Twitter API.

Currently the only value for type accepted is :users, which will return an Array of blessed Twitter::User objects that represent Twitter’s featured users.



19
20
21
22
23
# File 'lib/vendor/twitter/lib/twitter/extras.rb', line 19

def featured(type)
  uri = @@FEATURED_URIS[type]
  response = http_connect {|conn| create_http_get_request(uri) }
  bless_models(Twitter::User.unmarshal(response.body))
end

#friend(action, value) ⇒ Object

Provides access to the Twitter Friendship API.

You can add and remove friends using this method.

action can be any of the following values:

  • :add - to add a friend, you would use this action value

  • :remove - to remove an existing friend from your friends list use this.

The value must be either the user to befriend or defriend’s screen name, integer unique user ID or Twitter::User object representation.

Examples:

screen_name = 'dictionary'
client.friend(:add, 'dictionary')
client.friend(:remove, 'dictionary')
id = 1260061
client.friend(:add, id)
client.friend(:remove, id)
user = Twitter::User.find(id, client)
client.friend(:add, user)
client.friend(:remove, user)

Raises:



28
29
30
31
32
33
34
# File 'lib/vendor/twitter/lib/twitter/client/friendship.rb', line 28

def friend(action, value)
  raise ArgumentError, "Invalid friend action provided: #{action}" unless @@FRIENDSHIP_URIS.keys.member?(action)
  value = value.to_i unless value.is_a?(String)
  uri = "#{@@FRIENDSHIP_URIS[action]}/#{value}.json"
  response = http_connect {|conn| create_http_post_request(uri) }
  bless_model(Twitter::User.unmarshal(response.body))
end

#graph(action, value = nil) ⇒ Object

Provides access to the Twitter Social Graphing API.

You can retrieve the full graph of a user’s friends or followers in one method call.

action can be any of the following values:

  • :friends - retrieves ids of all friends of a given user.

  • :followers - retrieves ids of all followers of a given user.

The value must be either the user screen name, integer unique user ID or Twitter::User object representation.

Examples:

screen_name = 'dictionary'
client.graph(:friends, 'dictionary')
client.graph(:followers, 'dictionary')
id = 1260061
client.graph(:friends, id)
client.graph(:followers, id)
user = Twitter::User.find(id, client)
client.graph(:friends, user)
client.graph(:followers, user)

Raises:



28
29
30
31
32
33
34
35
36
# File 'lib/vendor/twitter/lib/twitter/client/graph.rb', line 28

def graph(action, value = nil)
  raise ArgumentError, "Invalid friend action provided: #{action}" unless @@GRAPH_URIS.keys.member?(action)
  id = value.to_i unless value.nil? || value.is_a?(String)
  id ||= value
  id ||= @login
  uri = "#{@@GRAPH_URIS[action]}.json"
  response = http_connect {|conn| create_http_get_request(uri, :id => id) }
  JSON.parse(response.body)
end

#inspectObject



3
4
5
6
# File 'lib/vendor/twitter/lib/twitter/client/base.rb', line 3

def inspect
  s = old_inspect
  s.gsub!(/@password=".*?"/, '@password="XXXX"')
end

#message(action, value, user = nil) ⇒ Object

Provides access to Twitter’s Messaging API for sending and deleting direct messages to other users.

action can be:

  • :post - to send a new direct message, value, to user given.

  • :delete - to delete direct message with message ID value.

value should be:

  • String when action is :post. Will be the message text sent to given user.

  • Integer or Twitter::Message object when action is :delete. Will refer to the unique message ID to delete. When passing in an instance of Twitter::Message that Status will be

user should be:

  • Twitter::User, Integer or String object when action is :post. The Integer must be the unique ID of the Twitter user you wish to send the direct message to and any Strings passed in must be the screen name of the user you wish to send the direct message to.

  • totally ignore when action is :delete. It has no purpose in this use case scenario.

Examples: The example below sends the message text ‘Are you coming over at 6pm for the BBQ tonight?’ to user with screen name ‘myfriendslogin’…

@twitter.message(:post, 'Are you coming over at 6pm for the BBQ tonight?', 'myfriendslogin')

The example below sends the same message text as above to user with unique integer ID of 1234567890… the example below sends the same message text as above to user represented by user object instance of Twitter::User

@twitter.message(:post, 'Are you coming over at 6pm for the BBQ tonight?', user)
message = @twitter.message(:post, 'Are you coming over at 6pm for the BBQ tonight?', 1234567890)

the example below delete’s the message send directly above to user with unique ID 1234567890…

@twitter.message(:delete, message)

Or the following can also be done…

@twitter.message(:delete, message.id)

In both scenarios (action is :post or :delete) a blessed Twitter::Message object is returned that represents the newly posted or newly deleted message.

An ArgumentError will be raised if an invalid action is given. Valid actions are:

  • :post

  • :delete

An ArgumentError is also raised when no user argument is supplied when action is :post.

Raises:



65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/vendor/twitter/lib/twitter/client/messaging.rb', line 65

def message(action, value, user = nil)
  raise ArgumentError, "Invalid messaging action: #{action}" unless [:post, :delete].member?(action)
  raise ArgumentError, "User argument must be supplied for :post case" if action.eql?(:post) and user.nil?
  uri = @@MESSAGING_URIS[action]
  user = user.to_i if user and user.is_a?(Twitter::User)
  case action
  when :post
    response = http_connect({:text => value, :user => user, :source => @@config.source}.to_http_str) {|conn| create_http_post_request(uri) }
  when :delete
    response = http_connect {|conn| create_http_delete_request(uri, :id => value.to_i) }
  end
  message = Twitter::Message.unmarshal(response.body)
  bless_model(message)
end

#messages(action, options = {}) ⇒ Object

Provides access to Twitter’s Messaging API for received and sent direct messages.

Example:

received_messages = @twitter.messages(:received)

An ArgumentError will be raised if an invalid action is given. Valid actions are:

  • :received

  • :sent

Raises:



20
21
22
23
24
25
# File 'lib/vendor/twitter/lib/twitter/client/messaging.rb', line 20

def messages(action, options = {})
  raise ArgumentError, "Invalid messaging action: #{action}" unless [:sent, :received].member?(action)
  uri = @@MESSAGING_URIS[action]
  response = http_connect {|conn|	create_http_get_request(uri, options) }
  bless_models(Twitter::Message.unmarshal(response.body))
end

#my(action, options = {}) ⇒ Object

Syntactic sugar for queries relating to authenticated user in Twitter’s User API

Where action is one of the following:

  • :info - Returns user instance for the authenticated user.

  • :friends - Returns Array of users that are authenticated user’s friends

  • :followers - Returns Array of users that are authenticated user’s followers

Where options is a Hash of options that can include:

  • :page - optional. Retrieves the next set of friends. There are 100 friends per page. Default: 1.

  • :lite - optional. Prevents the inline inclusion of current status. Default: false.

  • :since - optional. Only relevant for :friends action. Narrows the results to just those friends added after the date given as value of this option. Must be HTTP-formatted date.

An ArgumentError will be raised if an invalid action is given. Valid actions are:

  • :info

  • :friends

  • :followers

Raises:



58
59
60
61
62
63
64
# File 'lib/vendor/twitter/lib/twitter/client/user.rb', line 58

def my(action, options = {})
  raise ArgumentError, "Invalid user action: #{action}" unless @@USER_URIS.keys.member?(action)
  params = options.merge(:id => @login)
  response = http_connect {|conn| create_http_get_request(@@USER_URIS[action], params) }
  users = Twitter::User.unmarshal(response.body)
  bless_models(users)
end

#old_inspectObject



2
# File 'lib/vendor/twitter/lib/twitter/client/base.rb', line 2

alias :old_inspect :inspect

#profile(action, attributes) ⇒ Object

Provides access to the Twitter Profile API.

You can update profile information. You can update the types of profile information:

  • :info (name, email, url, location, description)

  • :colors (background_color, text_color, link_color, sidebar_fill_color,

sidebar_border_color)

  • :device (set device to either “sms”, “im” or “none”)

Example:

user = client.profile(:info, :location => "University Library")
puts user.inspect


20
21
22
23
24
25
26
27
28
# File 'lib/vendor/twitter/lib/twitter/client/profile.rb', line 20

def profile(action, attributes)
  connection = create_http_connection
  connection.start do |connection|
    response = http_connect(attributes.to_http_str) do |conn|
      create_http_post_request(@@PROFILE_URIS[action])
    end
    bless_models(Twitter::User.unmarshal(response.body))
  end
end

#search(options = {}) ⇒ Object

Provides access to Twitter’s Search API.

Example:

# For keyword search
iterator = @twitter.search(:q => "coworking")
while (tweet = iterator.next)
  puts tweet.text
end

An ArgumentError will be raised if an invalid action is given. Valid actions are:

  • :received

  • :sent



20
21
22
23
24
25
26
# File 'lib/vendor/twitter/lib/twitter/client/search.rb', line 20

def search(options = {})
#    raise ArgumentError, "Invalid messaging action: #{action}"
  uri = @@SEARCH_URIS[:basic]
  response = http_connect(nil, false, :search) {|conn|	create_http_get_request(uri, options) }
  json = JSON.parse(response.body)
  bless_models(Twitter::Status.unmarshal(JSON.dump(json["results"])))
end

#status(action, value = nil) ⇒ Object

Provides access to individual statuses via Twitter’s Status APIs

action can be of the following values:

  • :get to retrieve status content. Assumes value given responds to :to_i message in meaningful way to yield intended status id.

  • :post to publish a new status

  • :delete to remove an existing status. Assumes value given responds to :to_i message in meaningful way to yield intended status id.

  • :reply to reply to an existing status. Assumes value given is Hash which contains :in_reply_to_status_id and :status

value should be set to:

  • the status identifier for :get case

  • the status text message for :post case

  • none necessary for :delete case

Examples:

twitter.status(:get, 107786772)
twitter.status(:post, "New Ruby open source project Twitter4R version 0.2.0 released.")
twitter.status(:delete, 107790712)

An ArgumentError will be raised if an invalid action is given. Valid actions are:

  • :get

  • :post

  • :delete

Raises:



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/vendor/twitter/lib/twitter/client/status.rb', line 32

def status(action, value = nil)
  return self.timeline_for(action, value || {}) if :replies == action
  raise ArgumentError, "Invalid status action: #{action}" unless @@STATUS_URIS.keys.member?(action)
  return nil unless value
  uri = @@STATUS_URIS[action]
  response = nil
  case action
  when :get
	response = http_connect {|conn|	create_http_get_request(uri, :id => value.to_i) }
  when :post
	response = http_connect({:status => value, :source => @@config.source}.to_http_str) {|conn| create_http_post_request(uri) }
  when :delete
	response = http_connect {|conn| create_http_delete_request(uri, :id => value.to_i) }
  when :reply
    return nil if (!value.is_a?(Hash) || !value[:status] || !value[:in_reply_to_status_id])
    response = http_connect(value.merge(:source => @@config.source).to_http_str) {|conn| create_http_post_request(uri) }
  end
  bless_model(Twitter::Status.unmarshal(response.body))
end

#timeline_for(type, options = {}, &block) ⇒ Object

Provides access to Twitter’s Timeline APIs

Returns timeline for given type.

type can take the following values:

  • public

  • friends or friend

  • user or me

:id is on key applicable to be defined in </tt>options</tt>:

  • the id or screen name (aka login) for :friends

  • the id or screen name (aka login) for :user

  • meaningless for the :me case, since twitter.timeline_for(:user, 'mylogin') and twitter.timeline_for(:me) are the same assuming ‘mylogin’ is the authenticated user’s screen name (aka login).

Examples:

# returns the public statuses since status with id of 6543210
twitter.timeline_for(:public, id => 6543210)
# returns the statuses for friend with user id 43210
twitter.timeline_for(:friend, :id => 43210)
# returns the statuses for friend with screen name (aka login) of 'otherlogin'
twitter.timeline_for(:friend, :id => 'otherlogin')
# returns the statuses for user with screen name (aka login) of 'otherlogin'
twitter.timeline_for(:user, :id => 'otherlogin')

options can also include the following keys:

  • :id is the user ID, screen name of Twitter::User representation of a Twitter user.

  • :since is a Time object specifying the date-time from which to return results for. Applicable for the :friend, :friends, :user and :me cases.

  • :count specifies the number of statuses to retrieve. Only applicable for the :user case.

  • since_id is the status id of the public timeline from which to retrieve statuses for :public. Only applicable for the :public case.

You can also pass this method a block, which will iterate through the results of the requested timeline and apply the block logic for each status returned.

Example:

twitter.timeline_for(:public) do |status|
  puts status.user.screen_name, status.text
end

twitter.timeline_for(:friend, :id => 'myfriend', :since => 30.minutes.ago) do |status|
  puts status.user.screen_name, status.text
end

timeline = twitter.timeline_for(:me) do |status|
  puts status.text
end

An ArgumentError will be raised if an invalid type is given. Valid types are:

  • :public

  • :friends

  • :friend

  • :user

  • :me

Raises:



64
65
66
67
68
69
70
71
# File 'lib/vendor/twitter/lib/twitter/client/timeline.rb', line 64

def timeline_for(type, options = {}, &block)
  raise ArgumentError, "Invalid timeline type: #{type}" unless @@TIMELINE_URIS.keys.member?(type)
  uri = @@TIMELINE_URIS[type]
  response = http_connect {|conn| create_http_get_request(uri, options) }
  timeline = Twitter::Status.unmarshal(response.body)
  timeline.each {|status| bless_model(status); yield status if block_given? }
  timeline
end

#uri_suffix(opts) ⇒ Object



17
# File 'lib/vendor/twitter/lib/twitter/client/favorites.rb', line 17

def uri_suffix(opts); opts && opts[:page] ? "?page=#{opts[:page]}" : ""; end

#user(id, action = :info, options = {}) ⇒ Object

Provides access to Twitter’s User APIs

Returns user instance for the id given. The id can either refer to the numeric user ID or the user’s screen name.

For example,

@twitter.user(234943) #=> Twitter::User object instance for user with numeric id of 234943
@twitter.user('mylogin') #=> Twitter::User object instance for user with screen name 'mylogin'

Where options is a Hash of options that can include:

  • :page - optional. Retrieves the next set of friends. There are 100 friends per page. Default: 1.

  • :lite - optional. Prevents the inline inclusion of current status. Default: false.

  • :since - optional. Only relevant for :friends action. Narrows the results to just those friends added after the date given as value of this option. Must be HTTP-formatted date.

An ArgumentError will be raised if an invalid action is given. Valid actions are:

  • :info

  • :friends

Note: You should not use this method to attempt to retrieve the authenticated user’s followers. Please use any of the following ways of accessing this list:

followers = client.my(:followers)

OR

followers = client.my(:info).followers

Raises:



33
34
35
36
37
38
39
# File 'lib/vendor/twitter/lib/twitter/client/user.rb', line 33

def user(id, action = :info, options = {})
  raise ArgumentError, "Invalid user action: #{action}" unless @@USER_URIS.keys.member?(action)
  id = id.to_i if id.is_a?(Twitter::User)
  params = options.merge(:id => id)
  response = http_connect {|conn| create_http_get_request(@@USER_URIS[action], params) }
  bless_models(Twitter::User.unmarshal(response.body))
end