Use Ruby to write a tutorial on accessing the Twitter command line application,
Introduction
Twitter has become a leader in social networks. Twitter only allows users to publish content of no more than 140 characters. Who can think of it? This inconspicuous small website is now worth more than billion US dollars and has millions of users, A large number of applications have been built on the Twitter platform, and new developers are constantly preparing to invest in this wave.
This article is not intended to introduce Twitter (in fact, it is not necessary ). Instead, this article describes how to access the Twitter platform to build outstanding command line applications. Twitter supports various programming languages, including C ++ and Java? , Perl, Ruby, PHP, and Python. There are a large number of libraries or packages for each language to help you do a lot of work.
This article describes how to use Ruby to access Twitter. You should have a certain understanding of Ruby, but even if you do not have this knowledge, it is easy to quickly master Ruby.
Install Twitter gem
Some gems can be used to access Twitter from Ruby (see references for more information ). For this article, I chose twitter, a Ruby package compiled by John Nunemaker. Installing gem is very simple:
Bash $ gem install twitter
This command is used to install the Twitter client on your machine. If you have a customized gem installation folder, you must first call rubygems from the script and then call twitter. The procedure is as follows:
require 'rubygems'require 'twitter'
First Twitter script
Now you are ready to build the first application, which is used to detect the location of the person you are interested in. First, create a script to get the names of other people and tell you their current location. Listing 1 shows the relevant code.
Listing 1. tracking user locations
require 'rubygems'require 'twitter'def track ARGV.each do |name| puts name + " => " + Twitter.user("#{name}").location endend
Track
What operations have this code performed? If you are new to Ruby, you need to explain that ARGV is an array that provides scripts to access command line parameters. The Twitter. user API returns information about the person you are interested in. You can call the following script to obtain the current location of Lady Gaga, Ashton Kutcher, and oprawinfrey:
bash$ ./location_tracker.rb ladygaga aplusk Oprahladygaga => New York, NYaplusk => Los Angeles, CaliforniaOprah => Chicago, IL
Search for users on Twitter and learn about authentication information
Now, let's search for some 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, the user ID cannot be guessed normally. Therefore, you must provide the user name search function. The following code is used to search all users whose names match Arpan:
require 'rubygems'require 'twitter'names = Twitter.user_search("Arpan")
However, this code does not work properly. The Error Log shown in Listing 2 shows you where the problem occurs.
Listing 2. Unable to perform user search
Twitter::Unauthorized: GET https://api.twitter.com/1/users/search.json?q=Arpan%20Sen: 401: Could not authenticate you. from D:/Ruby/lib/ruby/gems/1.8/gems/twitter-1.6.2/lib/faraday/response/raise_http_4xx.rb:12:in `on_complete' from D:/Ruby/lib/ruby/gems/1.8/gems/faraday-0.7.4/lib/faraday/response.rb:9:in `call' from D:/Ruby/lib/ruby/gems/1.8/gems/faraday-0.7.4/lib/faraday/response.rb:62:in `on_complete'
From this code, we can see that you must pass Twitter authentication before you can perform other operations. The authentication here does not require you to log on and enter a password; it means to authenticate your script (called an application on Twitter. Keep this difference in mind. Visit http://dev.twitter.com/and use the normal account number and password to access the website. Twitter requires you to provide the application name, description, and placeholder website of the application. After providing this information, you must provide the following four items for script authentication:
- User key)
- User secret token (Consumer secret token)
- User OAuth key
- User OAuth secret token
Now, inside the Ruby code, you need to use these options to populate the Twitter. configure object. Listing 3 shows the relevant code.
Listing 3. configuring 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"end
Note that the entries in listing 3 are fictitious: You need to fill your content in the script. After successful authentication, 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"endusers = Twitter.user_search(ARGV[0])users.each do |user| print "\n" + user.name + " => " print user.location unless user.location.nil?end
Now, save the script as search_for.rb, and call the script in the form of./search_for.rb Arpan in the command line, you will get the user name shown in listing 5.
Listing 5. Code output in Listing 4
Arpan Jhaveri => New YorkArpan Boddishv =>Arpan Peter => Bangalore,IndiaArpan Podduturi => NYCArpan Kumar De => IIT KharagpurArpan Shrestha => Kathmandu, NepalArpan Divanjee => Mumbai,IndiaArpan Bajaj => Bay Area, CA
You may expect more results. The name Arpan (Indian name) is not uncommon. Why are there so few search results? Finally, you will find that user_search uses an optional parameter (a Ruby hash table). You can also specify options that can generate more results. Therefore, You Can slightly modify the code in listing 5, pass the optional hash parameter (#), and pre-fill its value. For example, if you want to fill in 15 results on a page, you can use the code in Listing 6.
Listing 6. display 15 search entries on each page
require 'rubygems'require 'twitter'#.. authentication code hereusers = Twitter.user_search(ARGV[0], {:per_page => 15})#... same as Listing 10
Can 100 entries be displayed on each page? No. Twitter. user_search allows up to 20 entries per page. Listing 7 shows how to display 20 entries on each page.
Listing 7. 20 entries are displayed on each page
#... usual authentication stuffpagecount = 0while pagecount < 10 u = Twitter.user_search("#{ARGV[0]}", {:per_page => 20, :page => pagecount}) u.each do |user| print "\n" + user.name + " => " + user.screen_name print " => " + user.location unless user.location.nil? end unless u.size < 20 pagecount += 1end
It looks much better now. You can search users by preference name and user's screen name. Let's do something more interesting. Let's search for people who live in New York who like Ruby named Nick. You can get the name and location from user_search, but how do you deal with Ruby-like search requirements? This introduces the next thing to learn: create a custom search client.
Use Twitter: Search
Use the Twitter: Search Class to create a custom Search client. Listing 8 shows the relevant code.
Listing 8. Learning to use Twitter: Search Class
#... user authentication pagecount = 0while pagecount < 10 u = Twitter.user_search("#{ARGV[0]}", {:per_page => 20, :page => pagecount}) u.each do |w| if w.location == "New York" results = Twitter::Search.new.from(w.screen_name).containing("ruby").fetch puts w.screen_name if results.size > 10 end end unless u.size < 20 pagecount += 1end
What happened here? The code first creates a Search client using Twitter: Search. new. Next, the search client is required to obtain all the tweets from the corresponding users including ruby. Finally, the Code returns a set of results. If Ruby is mentioned more than 10 times in tweet, this person is defined as a person who prefers Ruby.
Let's try to get a set of tweet for the hash mark # ruby. The specific implementation is as follows:
#... user authentication coderesults = search.hashtag("ruby").fetchresults.each do |r| puts r.text + " from " + r.from_userend
However, more content can be implemented. For hash tags like ruby, you want to get hundreds of entries, right? In this case, you can use the search client to conveniently retrieve the next page from the search client. The code in listing 9 shows ten page tweets about Ruby.
Listing 9. Displaying Multiple pages
More search options
The search client allows you to achieve better functions, such as using a specific language or tweet from a certain place (such as Germany. You can even search for the tweet that mentions a specific user or the tweet that matches a specific condition. For example, search for all tweets about Ruby but not Rails? Try the following code:
search.containing("ruby").not_containing("rails").fetch
Of course, you can concatenate data like the following:
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 you have mastered the essentials!
Speed Limit
For Twitter, you need to know an important thing, namely speed limitation. Twitter attaches great importance to this issue. Speed limit means that Twitter only allows your scripts to perform a limited number of queries per hour. You may have discovered that explicit authentication is not required for some applications, but authentication is required for other applications. For applications that do not contain the OAuth tag, the maximum number of calls per hour is 150. For applications with this tag, 350 calls can be executed every hour. For the latest Twitter speed limit information, see reference resources. To learn about the current restrictions of script authentication, add the following code:
puts Twitter.rate_limit_status
The output result is as follows:
<#Hashie::Mash hourly_limit=350 remaining_hits=350 reset_time="Sat Aug 13 21:48:59 +0000 2011" reset_time_in_seconds=1313272139>
If you want to obtain more specific results, use the code to view the following content:
Twitter.rate_limit.status.remaining_hits
The following output disables authentication. Note that you have used up 50% of the available limits:
<#Hashie::Mash hourly_limit=150 remaining_hits=77 reset_time="Sat Aug 13 21:13:50 +0000 2011" reset_time_in_seconds=1313270030>
Update the status of Twitter and re-publish tweet and other content.
The search function has come to an end. Now you need to use a script to update the tweet status. You only need one line of code (of course, you need to include the authentication code in the script ):
#... authentication codeTwitter.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 function is a natural extension of Twitter. It is very easy to send messages to another user:
#... authentication codeTwitter.direct_message_create("username", "Hi")
You can choose to use the user's screen name or digital ID to send messages. Another interesting feature of Twitter is that it can quickly view 20 recently sent and received messages:
#... authentication codeTwitter.direct_messages_sent.each do | s | puts "Sent to: " + s.recipient_screen_name puts "Text: " + s.textend
We sometimes need to emphasize the importance of some tweet. A good way is to re-release the tweet. The last 20 tweets are shown below:
#... authentication codeTwitter.retweets_of_me.each do |rt| print rt.text puts " retweet count = " + rt.retweet_count.to_send
Of course, it would be better to know who is re-releasing the tweet, but it cannot be obtained 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 obtain this ID. Listing 10 shows the related code:
Listing 10. Who is posting a new tweet to me?
#... authentication codeTwitter.retweets_of_me.each do |rt| print rt.text print " retweeted by " Twitter.retweeters_of(rt.id).each do |user| puts user.screen_name endend
Use Twitter to implement interesting Functions
You can use your script to do many interesting things. For example, if you are very concerned about what is happening on Twitter, you can get the top 10 Trends:
Twitter.trends.each do | trend | puts trend.nameend
Twitter.com can only report the top 10 trends. For more information, see references. Generally, you may only care about the local trend. You only need to provide the location where-on-earth ID (WOEID), Twitter can provide this information. The following shows how to obtain the current trend of India:
Twitter.local_trends(12586534 ).each do | trend | puts trend #local_trends returns Stringend
It is also easy for users to get Twitter recommendations. First, check the following script:
Twitter.suggestions("technology").users.each do | user | puts user.screen_nameend
I checked the output of this Code carefully. The first 10 results indicate that the code can work properly. Twitter provides different types of user interest. You can obtain this information by calling Twitter. suggestions (simply put Twitter. suggestions in the script. Each category has a short name, called slug in Twitter. You need to pass it to Twitter. suggestions to get Twitter recommendation users. Listing 11 shows the related output.
Listing 11. The first few users recommended in the technical category
Gruber
Dannysullivan
AlecJRoss
Timoreilly
Padmasree
Tedtalks
OpenGov
Twitter
BBCClick
Woot
Anildash
Laughingsquid
Digiphile
Jennydeluxe
Biz
ForbesTech
Chadfowler
Leolaporte
This article will show you how to find the most popular fans of sport in Tendulkar (the best cricket player. First, the consumer in ID is sachin_rt (you can use Twitter on related topics. user ("sachin_rt "). follower_count: view the number of followers and use Twitter. user ("sachin_rt "). verified ).
Now, you can use Twitter. follower_ids ("sachin_rt") to get the number of fans of "login in. By default, you will receive 5000 users, which is sufficient for you to complete the following work. Make sure that you have read the Twitter documentation and read the Twitter API resources for friends and followers to learn how to get a complete list of followers. The following is a sample code:
#... authenticate yourselfputs Twitter.follower_ids("sachin_rt").ids.size
Finally, sort some of the 5000 users according to follower_count:
#... authenticate yourselfputs Twitter.follower_ids("sachin_rt").ids[0..49].sort!{|a, b| \ Twitter.user(a).followers_count <=> \ Twitter.user(b).followers_count}.reverse.first.name
After sort ,"! "Indicates that the array (and no new array is returned) is modified for the content called by the sort pair. The code in curly braces ({}) is a comparison function. This explains another reason for using Ruby: 20 lines of C ++ code can be implemented in one line of code.
Conclusion
It is very interesting to write command line scripts for Twitter and give you an insight into features that Twitter does not yet provide. In addition, whether it is to search for specific users that meet your requirements (from local technical staff to topic experts in the field) or to search for exciting new tweets, can be easily implemented through the command line. Before finishing this article, I need to give the last two tips: first, Twitter is very concerned about the speed limit per hour, so it is best to cache the search results to your code. Second, keep an eye on Twitter's rest api resources, which lists all the APIs of your Twitter client. Most importantly, enjoy Twitter!