-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.py
executable file
·190 lines (159 loc) · 7.31 KB
/
index.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
#!/usr/bin/env python3
import logging
import sys
import cv2
import time
import os.path
from PIL import Image
import imageUtils
import videoUtils
import numpy
import requests
import tweepy
import config as cf
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
dirname = os.path.dirname(__file__)
def processTweet(tweet, username, replyTo, bold):
logger.info('Process tweet')
hasMedia = False
if hasattr(tweet, 'extended_entities') and 'media' in tweet.extended_entities:
logger.info('Tweet has video')
for media in tweet.extended_entities['media']:
hasMedia = True
fileName = media['id_str']
if 'video_info' in media:
for media in media['video_info']['variants']:
if media['content_type'] == 'video/mp4':
videoUrl = media['url']
break
video = requests.get(videoUrl, allow_redirects=True)
open(os.path.join(dirname, f'processed/{fileName}.mp4'), 'wb').write(video.content)
pathToVideo, hasSeenTheLightInVideo = videoUtils.processVideo(
os.path.join(dirname, f'processed/{fileName}.mp4'),
fileName,
os.path.join(dirname, f'processed'),
bold
)
media_ids = []
if hasSeenTheLightInVideo:
res = api.media_upload(filename=pathToVideo)
media_ids.append(res.media_id)
try:
api.update_status(
status='I have seen the light! @' + username,
in_reply_to_status_id=replyTo,
media_ids=media_ids
)
except:
e = sys.exc_info()[1]
print(e)
logger.error(e)
return hasMedia
else:
try:
api.update_status(
status='I cannot see the light in this video. @' + username,
in_reply_to_status_id=replyTo
)
except:
e = sys.exc_info()[0]
logger.error(e)
logger.info(tweet.entities)
if hasattr(tweet, 'entities') and 'media' in tweet.entities:
hasMedia = True
seenTheLight = False
media_ids = []
logger.info('has images')
for image in tweet.entities['media']:
fileName = image['id_str']
mediaUrl = image['media_url_https']
response = requests.get(mediaUrl).content
nparr = numpy.frombuffer(response, numpy.uint8)
image = cv2.imdecode(nparr,cv2.IMREAD_UNCHANGED)
if mediaUrl.lower().find('jpg') != -1 or mediaUrl.lower().find('png') != -1:
newImage, hasSeenTheLightInImage = imageUtils.processImage(image, bold)
if hasSeenTheLightInImage:
cv2.imwrite(os.path.join(dirname, f'processed/' + fileName + '.jpg'), newImage)
logger.info(f'Success, reply to {tweet.id_str}')
res = api.media_upload(filename=os.path.join(dirname, f'processed/{fileName}.jpg'),)
media_ids.append(res.media_id)
seenTheLight = True
else:
logger.info(f'No highlights detected {tweet.id_str}')
else:
logger.info(f'Not supported format for {mediaUrl}')
if seenTheLight:
try:
api.update_status(
status='I have seen the light! @' + username,
in_reply_to_status_id=replyTo,
media_ids=media_ids
)
except:
e = sys.exc_info()[0]
logger.error(e)
else:
try:
api.update_status(
status='I cannot see the light in this picture. @' + username,
in_reply_to_status_id=replyTo
)
except:
e = sys.exc_info()[0]
logger.error(e)
return hasMedia
def checkMentions(api, keywords, sinceId):
logger.info(f'Retrieving mentions since {sinceId}')
newSinceId = sinceId
for tweet in tweepy.Cursor(api.mentions_timeline, since_id=sinceId).items():
newSinceId = max(tweet.id, newSinceId)
username = tweet.user.screen_name
replyTo = tweet.id
if any(keyword in tweet.text.lower() for keyword in keywords):
try:
logger.info(f'Answering to {tweet.user.name} {tweet.id_str}')
bold = '/bold' in tweet.text.lower()
if bold:
logger.info('Bold image requested')
# check if actual tweet has media
tweet = api.get_status(tweet.id, include_entities=True, tweet_mode='extended')
replyTweet = None
quotedTweet = None
hasMedia = processTweet(tweet, username, replyTo, bold)
# check if tweet is in reply to
if hasMedia is False and hasattr(tweet, 'in_reply_to_status_id'):
logger.info('original tweet has no media, proceed to check if replied tweet exists', tweet.in_reply_to_status_id)
replyTweet = api.get_status(tweet.in_reply_to_status_id, include_entities=True, tweet_mode='extended')
if replyTweet is not None:
logger.info('reply tweet exists')
hasMedia = processTweet(replyTweet, username, replyTo, bold)
# check if tweet has quote
if hasMedia is False and hasattr(tweet, 'quoted_status_id'):
logger.info('reply tweet has no media, proceed to check if quoted tweet exists', tweet.quoted_status_id)
quotedTweet = api.get_status(tweet.quoted_status_id, include_entities=True, tweet_mode='extended')
if quotedTweet is not None:
logger.info('quotet tweet exists')
processTweet(quotedTweet, username, replyTo, bold)
except:
e = sys.exc_info()[0]
logger.error(e)
with open(os.path.join(dirname, 'errors.txt'), 'a') as saveFile:
saveFile.write(f'Failed answering to {tweet.user.name} {tweet.id_str} \n')
saveFile.write(e)
return newSinceId
auth = tweepy.OAuthHandler(cf.credentials['consumer_key'], cf.credentials['consumer_secret'])
auth.set_access_token(cf.credentials['access_token'], cf.credentials['access_token_secret'])
api = tweepy.API(auth)
if not os.path.isfile(os.path.join(dirname, 'sinceId.txt')):
with open(os.path.join(dirname, 'sinceId.txt'), 'w') as saveFile:
saveFile.write('1')
while True:
with open(os.path.join(dirname, 'sinceId.txt'), 'r') as readFile:
sinceId = readFile.read()
sinceId = int(sinceId)
sinceId = checkMentions(api, ['light', 'sparkles', 'luz', 'licht', 'illumin', 'show me the', 'do the thing'], sinceId)
with open(os.path.join(dirname, 'sinceId.txt'), 'w') as saveFile:
saveFile.write(str(sinceId))
logger.info('Waiting...')
time.sleep(60)