-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
210 lines (174 loc) · 6.71 KB
/
main.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
from config import *
import os.path
import json
from time import gmtime, strftime, sleep
from datetime import datetime
from send_mail import *
from settings import *
# custom logger
bot_username = 'gitcommitshow'
logfile_name = bot_username + ".log"
errorfile_name = "errors.log"
now = datetime.now()
timestr = now.strftime("%Y-%m-%d %H:%M:%S")
def log(message):
"""Log message to logfile."""
file_exists = os.path.isfile(logfile_name)
if file_exists:
with open(logfile_name, 'a+') as f:
t = strftime("%d %b %Y %H:%M:%S", gmtime())
f.write("\n" + t + " " + message)
else:
with open(logfile_name, 'a+') as f:
t = strftime("%d %b %Y %H:%M:%S", gmtime())
f.write("\n" + t + " " + message)
def ErrorLog(message):
file_exists = os.path.isfile(logfile_name)
if file_exists:
with open(errorfile_name, 'a+') as f:
t = strftime("%d %b %Y %H:%M:%S", gmtime())
f.write("\n" + t + " " + message)
else:
with open(errorfile_name, 'a+') as f:
t = strftime("%d %b %Y %H:%M:%S", gmtime())
f.write("\n" + t + " " + message)
"""
# Log message to logfile.
path = os.path.realpath(os.path.join(
os.getcwd(), os.path.dirname(__file__)))
with open(os.path.join(path, errorfile_name), 'a+') as f:
t = strftime("%d %b %Y %H:%M:%S", gmtime())
f.write("\n" + t + " " + message)
"""
class MyStreamListener(tweepy.StreamListener):
def __init__(self, api):
self.api = api
self.me = api.me()
def on_status(self, tweet):
name = tweet.user.name
uname = tweet.user.screen_name
tweet_id = tweet.id
'''
Referenced in issue#974 and issue#617
https://github.com/tweepy/tweepy/issues/617#issuecomment-142439777
https://github.com/tweepy/tweepy/issues/974#issuecomment-493283899
'''
if hasattr(tweet, 'retweeted_status'):
try:
text = tweet.retweeted_status.extended_tweet["full_text"]
except:
text = tweet.retweeted_status.text
else:
try:
text = tweet.extended_tweet["full_text"]
except AttributeError:
text = tweet.text
#text = tweet.text
if tweet.in_reply_to_status_id is not None or \
tweet.user.id == self.me.id:
return
print('-'*20)
print("\n" + name + ' said ' + text + "\n")
print('-'*20)
if FAVORITE:
if not tweet.favorited:
try:
tweet.user.follow()
tweet.favorite()
except tweepy.error.TweepError as e:
ErrorLog("[FAVORITE ERROR] " + str(e))
if MAIL:
sub = "[FAVORITE ERROR] {0}".format(name)
tweet_url = "https://twitter.com/{0}/status/{1}".format(
uname, tweet_id)
mess = tweet_url + "\n"
mess += str(e)
body = "{0} \n\nOccured at {1}".format(mess, timestr)
mail(sub, body)
if FOLLOW:
if not tweet.user.following:
try:
tweet.user.follow()
except tweepy.error.TweepError as e:
ErrorLog("[FOLLOW ERROR] " + str(e))
if MAIL:
sub = "[FOLLOW ERROR] {0}".format(name)
tweet_url = "https://twitter.com/{0}/status/{1}".format(
uname, tweet_id)
mess = tweet_url + "\n"
mess += str(e)
body = "{0} \n\nOccured at {1}".format(mess, timestr)
mail(sub, body)
if RETWEET:
if not tweet.retweeted:
try:
tweet.retweet()
except tweepy.error.TweepError as e:
ErrorLog("[RETWEET ERROR] " + str(e))
if MAIL:
sub = "[RETWEET ERROR] {0}".format(name)
tweet_url = "https://twitter.com/{0}/status/{1}".format(
uname, tweet_id)
mess = tweet_url + "\n"
mess += str(e)
body = "{0} \n\nOccured at {1}".format(mess, timestr)
mail(sub, body)
log(name + ' said ' + text + "\n")
# Twitter bot sleep time settings in seconds. Use large delays so that you account will not banned
sleep(DELAY) # 300 seconds = 5 minutes
def on_timeout(self):
sub = "[TwCrawler] TIMEOUT Error"
body = "Occured at {0}".format(timestr)
mail(sub, body)
return True
def on_error(self, status_code):
if MAIL:
if status_code == 104:
code = int(status_code)
sub = "[TwCrawler] TIMEOUT Error {0}".format(code)
body = "Occured at {0}".format(timestr)
mail(sub, body)
else:
code = int(status_code)
sub = "[TwCrawler] Error {0}".format(code)
body = "Occured at {0}".format(timestr)
mail(sub, body)
return True
# def on_error(self, status):
# print("Error detected")
# lists the first 20 tweets in my timeline
def timeline():
timeline = api.home_timeline()
for tweet in timeline:
name = tweet.user.name
text = tweet.text
log(name + ' said ' + text + "\n")
errorMsg = "Check logs"
def main(keywords):
global errorMsg
# initialize api
api = create_api()
# timeline()
tweets_listener = MyStreamListener(api)
while True:
try:
# verify = False disables the SSL Verification. Not at all suggested.
# stream = tweepy.Stream(api.auth, tweets_listener, verify = False, timeout=600)
stream = tweepy.Stream(api.auth, tweets_listener, timeout=600)
# added async=True - opens a new thread and stops the stream from dying
stream.filter(track=keywords, is_async=False)
except tweepy.error.TweepError as e:
if 'Failed to send request:' in e.reason:
print("Time out error caught.")
sleep(180)
continue
except Exception as e:
e = str(e)
errorMsg = 'I just caught the exception {0}'.format(e)
print(errorMsg)
if MAIL:
sub = "[TwCrawler] GitCommitShow Error"
body = "Error {0} \n\nOccurred at {1}".format(errorMsg, timestr)
mail(sub, body)
if __name__ == "__main__":
main(HASHTAG_LIST)