-
Notifications
You must be signed in to change notification settings - Fork 9
/
twitter_streaming.py
76 lines (59 loc) · 2.03 KB
/
twitter_streaming.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import os
import sys
import time
import json
import datetime
from pymongo import MongoClient
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
# MongoDB
client = MongoClient()
db = client["cryto_trading_bot"]
db.bitcoin_tweets.ensure_index("id", unique=True, dropDups=True)
collection = db.bitcoin_tweets
# Keywords
keywords = ['$btc', '#btc', 'btc', '$bitcoin', '#bitcoin', 'bitcoin']
# Only grab tweets in english
language = ['en']
# Twitter API stuff
consumer_key = "e6nP2qftfJlcbvbrrL0JlWPHn"
consumer_secret = "SXVyBdbNyhohxO1EQGBKq8QlY83e17FUWvaeQJtWhvCzcDnpu3"
access_token = "2397402739-vu0AUKOY49clNceFSbrGk4Onn7peL0XzCQvLAgP"
access_token_secret = "esHGDDtvAm2jLSoyemApDGmI29ZLODfSLienoLgl1a4rJ"
class StdOutListener(StreamListener):
def on_data(self, data):
t = json.loads(data)
tweet_id = t['id_str']
username = t['user']['screen_name']
followers = t['user']['followers_count']
text = t['text']
hashtags = t['entities']['hashtags']
timestamp = t['created_at']
language = t['lang']
created = datetime.datetime.strptime(timestamp, '%a %b %d %H:%M:%S +0000 %Y')
tweet = {'id':tweet_id,
'username':username,
'followers':followers,
'text':text,
'hashtags':hashtags,
'language':language,
'created':created
}
os.system('clear')
if collection.find_one({'id': { "$eq": tweet_id}}):
print ('Tweet already exists!')
else:
print("New tweet! " + tweet_id)
collection.save(tweet)
return True
def on_error(self, status):
print status
return True
if __name__ == '__main__':
while True:
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
stream.filter(track=keywords, languages=language)