Guest User

Untitled

a guest
Apr 26th, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. import time
  2.  
  3. import redis
  4. import tweetstream
  5.  
  6. from datetime import datetime
  7.  
  8. try:
  9. import simplejson as json
  10. except:
  11. import json
  12.  
  13.  
  14. class FilterRedis(object):
  15.  
  16. key = "tweets"
  17. r = redis.Redis()
  18. r.connect()
  19. num_tweets = 20
  20. trim_threshold = 100
  21.  
  22. def __init__(self):
  23. self.trim_count = 0
  24.  
  25.  
  26. def push(self, data):
  27. self.r.push(self.key, data, True)
  28.  
  29. self.trim_count += 1
  30. if self.trim_count >= self.trim_threshold:
  31. self.r.ltrim(self.key, 0, self.num_tweets)
  32. self.trim_count = 0
  33.  
  34.  
  35. def tweets(self, limit=15, since=0):
  36. data = self.r.lrange(self.key, 0, limit - 1)
  37. return [json.loads(x) for x in data if int(json.loads(x)['received_at']) > since]
  38.  
  39.  
  40. if __name__ == '__main__':
  41. fr = FilterRedis()
  42.  
  43. words = ["why", "how", "when", "lol", "feeling"]
  44.  
  45. username = "your twitter username"
  46. password = "password for twitter account"
  47.  
  48. with tweetstream.TrackStream(username, password, words) as stream:
  49. for tweet in stream:
  50. if 'text' not in tweet: continue
  51. if '@' in tweet['text'] or not tweet['text'].endswith('?'):
  52. continue
  53. fr.push(json.dumps( {'id':tweet['id'],
  54. 'text':tweet['text'],
  55. 'username':tweet['user']['screen_name'],
  56. 'userid':tweet['user']['id'],
  57. 'name':tweet['user']['name'],
  58. 'profile_image_url':tweet['user']['profile_image_url'],
  59. 'received_at':time.time()}
  60. )
  61. )
  62. print tweet['user']['screen_name'],':', tweet['text'].encode('utf-8')
Add Comment
Please, Sign In to add comment