:::: MENU ::::

Script: Get Twitter user_ids

Twitter’s Streaming API requires user_id for just about any user function, but only screen_names are easy to find. The documentation for the Twitter and Twitter4r gems has the wrong syntax for the user.lookup method. So, I wrote a little script that accepts a list of screen_names and gets the associated user_ids. The original version is below, and you can get the latest version from my lab repos on Github: https://github.com/casmlab

First some legalese:
Unless otherwise specified, all CaSM Lab code, including everything in this repository, is distributed under the Apache 2.0 license with the following boilerplate message:

Copyright 2011 Illinois Institute of Technology — Libby Hemphill (libby.hemphill@iit.edu)

Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

usage:

ruby get_user_ids.rb input_file output_file

code:

require 'rubygems'
gem "twitter4r"
require 'twitter'
# config info like Twitter username and ID, OAuth credentials
require File.join(File.expand_path(File.dirname(__FILE__)), ".", "constants.rb") 

input_file = ARGV[0]
output_file = ARGV[1]

# test files for testing
# input_file = File.join(File.expand_path(File.dirname(__FILE__)), ".", "input_test.txt")
# output_file = File.join(File.expand_path(File.dirname(__FILE__)), ".", "output_test.csv")

# configure the Twitter client with your info from constants.rb
Twitter::Client.configure do |conf|
   conf.oauth_consumer_token = CONSUMER_KEY
   conf.oauth_consumer_secret = CONSUMER_SECRET
end

client = Twitter::Client.new(:oauth_access =>
 { 	:key 	=> OAUTH_TOKEN,
	:secret => OAUTH_TOKEN_SECRET
 })

# loop through the screen_names array collecting user_ids
# put those user_ids into output_file

counter = 0
not_found = 0
puts "starting screen name lookup"
begin
  screen_names = IO.readlines(input_file)
  of = File.open(output_file,"w+")
  screen_names.each do |name|
    begin
      counter+=1
      user = client.user(name.chomp) # chomp removes any carriage breaks
      of.puts """ + user.screen_name + "", " + user.id.to_s
    rescue Twitter::NotFoundError
      not_found+=1
      of.puts """ + name.chomp + "", "not found""
    end
  end
rescue => err
  puts "Exception: #{err}"
end
puts "looked up " + counter.to_s + " screen names; " + not_found.to_s + " weren't found."
of.close

So, what do you think ?

You must be logged in to post a comment.