Use Ruby to write a tutorial on a command line application that accesses Twitter _ruby topics

Source: Internet
Author: User
Tags hash oauth unique id ruby on rails

Brief introduction

Twitter is now the leader in social networking. Twitter only allows users to post no more than 140 characters, and who would have guessed that the previously insignificant small web site is now worth more than 1 billion of billions of dollars, has millions of users, has built a lot of apps on Twitter, and that new developers are ready to invest in the wave.

This article does not intend to introduce Twitter (in fact, it is not necessary). Instead, this article describes how to access the Twitter platform to build excellent command-line applications. Twitter supports a variety of programming languages, including C + +, Java, Perl, Ruby, PHP, and Python. For each language, there are a large number of libraries or packages that can help you do a lot of work.

This article describes how to use Ruby to access Twitter. You should know more about Ruby, but even if you don't have this knowledge, it's easy to get a grip on ruby quickly.

Install Twitter Gem

Some gems can be used to access Twitter from Ruby (see Resources for more information). For this article, I chose to use Twitter, a Ruby wrapper written by John Nunemaker. Installing the gem is simple:

bash$ Gem Install Twitter

This command is used to install the Twitter client on your machine. If you have a custom Gem installation folder, you first need to call RubyGems from the script and then call Twitter. The following shows the specific process:

Require ' RubyGems '
require ' Twitter '

The first Twitter script

You are now ready to build your first application, which detects the location of people you care about. Start by creating a script that gets the names of other people and tells you where they are now. Listing 1 shows the relevant code.
Listing 1. Track User Location

Require ' RubyGems '
require ' Twitter '

def track
 Argv.each do |name|
  Puts name + "=>" + Twitter.user ("#{name}"). Location


What does this piece of code do? If you've just touched Ruby, you need to explain that ARGV is an array that provides scripting access to command-line arguments. The Twitter.user API returns information about people who are interested in where you are. Call the following script to get the current location of Lady Gaga, Ashton Kutcher, and Oprah Winfrey:

bash$/location_tracker.rb ladygaga aplusk Oprah ladygaga =>
New York, NY
aplusk => Los Angeles, Californ IA
Oprah => Chicago, IL

Implement user search on Twitter and get a sense of authentication

Now, let's search for some of the existing users on Twitter. If you can guess the user's Twitter ID, you can use the following command line:

Require ' RubyGems '
require ' Twitter '
puts ' User exists ' if Twitter.user? ( Argv[0])

However, in general, you cannot guess the user's ID. Therefore, you need to provide the ability to search for user names. This needs to be implemented with the following code that will search for all users with the name matching Arpan:

Require ' RubyGems '
require ' Twitter '
names = Twitter.user_search ("Arpan")

However, this code does not work correctly. The error log shown in Listing 2 tells you where the problem occurs.
Listing 2. Unable to perform user search

20sen:401:could not Authenticate you.
  From d:/ruby/lib/ruby/gems/1.8/gems/twitter-1.6.2/lib/faraday/response/r
aise_http_4xx.rb:12:in ' On_ Complete ' from
b:9:in '
b:62:in ' On_complete '

As you can see from this code, you first need to authenticate with Twitter before you can perform other actions. The authentication here does not require you to log in and enter a password, but to authenticate your script (called an application in Twitter). Keep this difference in mind, then visit Http:// and log in with your usual account number and password. Twitter will ask you to provide the application name, description, and Application placeholder (placeholder) Web site. After you provide this information, you must also provide the following four content to implement script authentication:

    1. User key (Consumer key)
    2. User Secret token (Consumer secret token)
    3. User OAuth Key
    4. User OAuth Secret Token

Now, within the Ruby code, you need to populate the Twitter.configure object with these options. Listing 3 shows the relevant code.
Listing 3. Configure Scripts for authentication

Twitter.configure do |config|
 Config.consumer_key = "Mt4atgbekvnrrpv8gqkynq"
 Config.consumer_secret = " biqx47fxa938sysclmxqcthithjuttrdt3v6hjd6s "
 config.oauth_token =" 22652054-yj6o38bswhwtx9jnspafhszghxvcvnq "
 Config.oauth_token_secret = "O9juqugxevf3qdzmgpuqs0gmznrecfgq12jks"

Note that the entry in Listing 3 is fictitious: you need to populate your script with your own content. After successfully completing the certification, you can search for the person named Arpan (see Listing 4 below).
Listing 4. Search for users on Twitter

Require ' RubyGems '
require ' Twitter '

twitter.configure do |config|
 Config.consumer_key = "Mt4atgbekvnrrpv8gqkynq"
 Config.consumer_secret = " biqx47fxa938sysclmxqcthithjuttrdt3v6hjd6s "
 config.oauth_token =" 22652054-yj6o38bswhwtx9jnspafhszghxvcvnq "
 Config.oauth_token_secret = "O9juqugxevf3qdzmgpuqs0gmznrecfgq12jks"

users = Twitter.user_search ( Argv[0])
Users.each do |user|
 print "\ n" + + "=>" 
 print user.location unless user.location.nil?

Now, after you save the script as SEARCH_FOR.RB and invoke the script in the./search_for.rb arpan form on the command line, you will get the user name shown in Listing 5.
Listing 5. The code output for listing 4

Arpan jhaveri => New York
arpan boddishv => arpan
Peter => bangalore,india arpan podduturi
=> C4/>arpan Kumar De => IIT Kharagpur arpan Shrestha => Kathmandu. Nepal arpan Divanjee => mumbai,india
    arpan Bajaj => Bay area, CA


You may expect to get more results. Arpan's name (Indian name) is not uncommon, so why are there so few search results? Finally, you'll find that User_search uses an optional parameter (a Ruby hash table), and you can also specify options to produce more results. Therefore, you can modify the code in Listing 5 slightly, passing the optional hash parameter (#) and populating its value. For example, if you want to populate a page with 15 results, you can use the code in Listing 6.
Listing 6. Display 15 search entries on each page

Require ' RubyGems '
require ' Twitter '

. Authentication code here
users = Twitter.user_search (argv[0), {:p er_page =>})
# ... same as Listing 10

Is it possible to display 100 entries in each page? No, Twitter.user_search allows the maximum number of entries to be displayed per page is 20. Listing 7 shows how to display 20 entries in each page.
Listing 7. Display 20 entries per page

# ... usual authentication stuff

PageCount = 0
while PageCount <
 u = Twitter.user_search ("#{argv[0]}", { :p er_page =>,:p age => PageCount})
 U.each do |user| 
 print "\ n" + + "=>" + user.screen_name
 print "=>" + user.location unless?
 End unless U.size <
 PageCount + + 1

It looks a lot better now. You can now search for users based on their preferences and their screen names, so let's do something more interesting. Let's search for people who live in New York who like Ruby, named Nick. You can get names and locations from User_search, but how do you handle search requirements like Ruby? This introduces the next content that needs to be learned: creating custom search clients.
Using the Twitter::search class

Create a custom search client using the Twitter::search class. Listing 8 shows the relevant code.
Listing 8. Learn to use the Twitter::search class

# ... user authentication 
PageCount = 0
while PageCount <
 u = Twitter.user_search ("#{argv[0]}", {:p er_ Page =>,:p age => PageCount})
 U.each do |w| 
 if w.location = = "New York"
  results = (W.screen_name). containing ("Ruby"). Fetch
  puts W.screen_name if results.size > ten
 unless u.size <
 PageCount + + 1

What's going on here? The code first creates a search client using Next, the search client is asked to obtain all tweets from the appropriate user containing Ruby. Finally, the code returns a set of results, and if you mention Ruby more than 10 times in a tweet, define that person as someone who likes Ruby.

Let's try to get a set of tweets for the hash tag #ruby. The following is a specific implementation:

# ... user authentication code
results = Search.hashtag ("Ruby"). Fetch Results.each do
 Puts R.text + ' from ' + R.from_user end

However, more can be achieved. For hash tags like Ruby, you want to get hundreds of entries, don't you? In this case, it is also convenient to use a search client because you can easily retrieve the next page from the search client. The code in Listing 9 shows 10 pages of tweets about Ruby.
Listing 9. Show multiple pages

More Search Options

Search clients can enable you to achieve better features, such as using specific languages or tweets from somewhere (such as Germany). You can even search for tweets that refer to a particular user, or a search that matches a specific condition. For example, search all tweets that mention Ruby but don't mention Rails? Try the following code:

Search.containing ("Ruby"). Not_containing ("rails"). Fetch

Of course, you can do this in tandem as follows:

Search.containing ("Ruby"). Not_containing ("rails"). Mentioning ("username"). from ("Place-id")

The search phrase is very intuitive. For example, enter the following code:

Search.phrase ("Ruby on Rails"). Fetch

Now that you have mastered the basics!
Speed Limit

One important thing you need to know about Twitter, the speed limit, is that Twitter attaches great importance to this issue. Speed limits mean that Twitter only allows your scripts to perform a limited number of queries per hour. You may have found that you do not need explicit authentication for some applications, but for other applications, authentication is required. For applications that do not contain OAuth tags, the current maximum limit is 150 calls per hour, and 350 calls per hour for applications with this tag. For the latest information about the Twitter rate limit, check the reference resources. To learn the current limitations of your script authentication, add the following code:

Puts Twitter.rate_limit_status

The following are the output results:

< #Hashie:: Mash hourly_limit=350 remaining_hits=350 reset_time= "Sat Aug 21:48:
+0000" Reset_time_in_ Seconds=1313272139>

If you want more specific results, see the following in code:


Authentication is disabled for the following output. Note that you have run out of 50% of the available limits:

< #Hashie:: Mash hourly_limit=150 remaining_hits=77 reset_time= "Sat Aug 21:13:5
0 +0000" Reset_time_in_ Seconds=1313270030>

Update Twitter's status and redistribute tweets and other content

The search function is temporarily closed. Now you need to use a script to update the status of the tweet. Just one line of code (and, of course, you need to include the authentication code in the script):

# ... authentication code
twitter.update (ARGV [0])

Save the code as UPDATE.RB and call it from the command line in the form of Ruby Update.rb "Hello World from Ruby Script." Now, your Twitter page has been updated! The dialog feature is a natural extension of Twitter, and sending messages to another user is very simple:

# ... authentication code
twitter.direct_message_create ("username", "Hi")

You can choose to send a message using the user's screen name or digital ID. Another interesting feature of Twitter is that you can quickly see the last 20 messages sent and recently received:

# ... authentication code Twitter.direct_messages_sent.each do
| s | 
 Puts "Sent to:" + s.recipient_screen_name
 puts "Text:" + s.text

We sometimes need to emphasize the importance of some tweets, a good way is to redistribute tweets. The last 20 tweets that were republished are shown below:

# ... authentication code Twitter.retweets_of_me.each do
 Print Rt.text
 puts "retweet count =" + rt.retweet_count.to_s

Of course, it would be better to know who was republishing the tweet, but it was not possible to get the information directly from the Retweets_of_me API. Instead, you need to use the retweeters_of API. Note that each tweet has a unique ID, and retweeters_of needs to get this ID. Listing 10 shows the relevant code:
Listing 10. Who's posting the tweet to me again?

# ... authentication code Twitter.retweets_of_me.each do
 Print Rt.text
 print ' retweeted by ' 
 twitter.retweeters_of ( Each do |user|
 Puts User.screen_name

Use Twitter to achieve interesting features

You can do a lot of interesting things with your own scripts. For example, if you are concerned about what is happening on Twitter today, you can get the top 10 trends:

Twitter.trends.each do | Trend | 
 Puts end can only report the first 10 trends. For more information, refer to the reference resources. Typically, you may only care about trends in your location. Just provide the location of the Where-on-earth ID (Woeid), and Twitter can provide this information. Here I show how to get the current trends in India:

Twitter.local_trends (12586534). each do | Trend | 
 Puts trend #local_trends returns String end

It's also easy to get Twitter-recommended users. First look at the following script:

Twitter.suggestions ("Technology"). Users.each do | user | 
 Puts User.screen_name end

I have checked the output of this code carefully. The first 10 results mean that the code works correctly. Twitter provides categories that are of interest to different users, and you can get this information by calling Twitter.suggestions (just put the twitter.suggestions in a script). Each category has a short name, called Slug in Twitter, that you need to pass to twitter.suggestions and then get the Twitter-recommended user. Listing 11 shows the associated output.
Listing 11. Top users recommended in the technology category


This article will finally explain how to find the most popular fan of Sachin Tendulkar (the best cricket player). First, the Sachin ID is sachin_rt (you can use Twitter.user ("Sachin_rt") on related topics. Follower_count View the number of fans and use Twitter.user ("Sachin_rt "). Verified to confirm his status).

Now, use Twitter.follower_ids ("Sachin_rt") to get the number of Sachin fans. By default, you will get 5,000 users, which is enough to support you in doing the work below. Make sure you've read the Twitter documentation and consulted the Twitter API resource for friends and followers to learn how to get a complete list of fans. Here is a code example:

# ... authenticate yourself
puts Twitter.follower_ids ("Sachin_rt"). Ids.size

Finally, according to Follower_count, some of the 5,000 users are sorted:

# ... authenticate yourself
puts Twitter.follower_ids ("Sachin_rt"). ids[0..49].sort!{| A, b| \ 
 Twitter.user (a). Followers_count <=>
 Twitter.user (b). Followers_count}

After sort, "!" means that the sort modifies the array (and no new array is returned), and the code in the curly braces ({}) is the comparison feature. This explains another reason to use Ruby: the ability to implement 20 of lines of C + + code in one line of code.


Writing command-line scripts for Twitter is fun and gives you insight into the functionality that Twitter has yet to offer. In addition, whether you search for specific users who meet your criteria (from local technicians to subject matter experts in the field) or search for exciting new tweets, you can easily implement them through the command line. Before I end this article, I need to give the last two tips: First, Twitter is very concerned about rate limits per hour, so it's a good idea to cache search results in your code. Second, keep an eye on Twitter's REST API resources, which list all the APIs for your Twitter client. The most important thing is to enjoy the fun of Twitter!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.