Search

twitter search hashtag or username from bash

twitter search hashtag or username from bash

#!/bin/bash
#
# Search for the latest tweets
#
# This script is based in part on a solution proposed by Mike Bounds
# in the twitter discussion forum: https://dev.twitter.com/discussions/14460
##################
# Modified to fix searching for hashtags # and usernames @ by Greg Fenton
# http://labby.co.uk
##################
set -o errexit

screen_name=gregoryfenton
query="#candy4greg OR @gregoryfenton"
query=`echo "$query" | sed 's/%/%25/g' | sed 's/ /%20/g' | sed 's/@/%40/g' | sed 's/=/%3D/g' | sed 's/#/%23/g'`
since=
tweet_count=1 # the number of tweets you want to retrieve
consumer_key=
consumer_secret=
oauth_token=
oauth_secret=

timestamp=`date +%s`
nonce=`date +%s%T555555555 | openssl base64 | sed -e s'/[+=/]//g'`

unsorted="count=${tweet_count}
oauth_consumer_key=${consumer_key}
oauth_token=${oauth_token}
oauth_nonce=${nonce}
oauth_version=1.0
oauth_signature_method=HMAC-SHA1
oauth_timestamp=${timestamp}
screen_name=${screen_name}
q=${query}
since_id=${since}"
sorted=`echo "$unsorted" | sort | tr '\n' "~" | sed 's/%/%25/g' | sed 's/~/%26/g' | sed 's/@/%40/g' | sed 's/=/%3D/g' | sed 's/#/%23/g' | sed 's/...$//'`
signature_base_string="GET&https%3A%2F%2Fapi.twitter.com%2F1.1%2Fsearch%2Ftweets.json&${sorted}"
signature_key="${consumer_secret}&${oauth_secret}"
oauth_signature=`echo -n ${signature_base_string} | openssl dgst -sha1 -hmac ${signature_key} -binary | openssl base64 | sed -e s'/+/%2B/' -e s'/\//%2F/' -e s'/=/%3D/'`

header="Authorization: OAuth oauth_consumer_key=\"${consumer_key}\", oauth_nonce=\"${nonce}\", oauth_signature=\"${oauth_signature}\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"${timestamp}\", oauth_token=\"${oauth_token}\", oauth_version=\"1.0\""

result=`curl --silent --get 'https://api.twitter.com/1.1/search/tweets.json' --data "count=${tweet_count}&q=${query}&screen_name=${screen_name}&since_id=${since}" --header "Content-Type: application/x-www-form-urlencoded" --header "${header}"`
echo $result

The end result needs to be parsed as it is in JSON format, but I will leave that for another post.

Related posts

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.