Skip to content

Instantly share code, notes, and snippets.

@edsu
Last active August 20, 2017 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edsu/b5b4c6c3511f1085a07bbc9f21c8a06b to your computer and use it in GitHub Desktop.
Save edsu/b5b4c6c3511f1085a07bbc9f21c8a06b to your computer and use it in GitHub Desktop.
This is a test of searching in extended tweets for hashtags near the end of the message. It demonstrates how searches for hashtags with the # prefix will not return all the tweets that contain that hashtag, but will without the # prefix.
#!/usr/bin/env python
"""
This is a test of searching in extended tweets for hashtags near the end of
the message. It demonstrates how searches for hashtags with the # prefix will
not return all the tweets that contain that hashtag, but will without the
# prefix.
You'll need to set the CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN and
ACCESS_TOKEN_SECRET environment variables to talk to the Twitter API.
1. Creates a tweet that has a length of 137 characters that includes a unique hashtag at the end.
2. Retweet the tweet, which will prepend "RT: {username}" and push the hashtag over the 140 character mark (extended tweet).
3. Sleep for 20 seconds to wait for Twitter to update their search index.
4. Print out the number of search results with and without the '#' prefix.
"""
from __future__ import print_function
import os
import time
import tweepy
# get twitter keys and set up the twitter client
e = os.environ.get
auth = tweepy.OAuthHandler(e("CONSUMER_KEY"), e("CONSUMER_SECRET"))
auth.set_access_token(e("ACCESS_TOKEN"), e("ACCESS_TOKEN_SECRET"))
twitter = tweepy.API(auth)
# create a (hopefully) unique hashtag to use
t = 't' + str(int(time.time()))
# tweet a message 137 characters in length
msg = 'test ' * 25 + '#' + t
tweet = twitter.update_status(msg)
time.sleep(1)
# retweet the tweet which will cause your username to be added as
# a prefix and will push the text over the traditional 140 character limit
retweet = twitter.retweet(tweet.id)
# wait for twitter to update their search index
time.sleep(20)
# print out search results with/without hashtag
print("searching for %s: %s results" % (t, len(twitter.search(t))))
print("searching for %s: %s results" % ("#" + t, len(twitter.search("#" + t))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment