Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
return
media = None
image = findImage(entry)
image_file = downloadImage(image)
if image_file:
print(f"IMAGE: {image}")
if self.api:
media = [self.api.media_upload(image_file).media_id]
os.remove(image_file)
print(f"TWEET: {tweet_body}\n")
if self.api:
try:
self.api.update_status(tweet_body, media_ids=media)
except tweepy.error.TweepError as e:
if e.api_code == 187:
print("ERROR: Tweet refused as duplicate\n")
else:
print(f"ERROR: Tweet refused, {e.reason}\n")
sys.exit(1)
self.addToPosted(entry.id)
self.n_tweeted += 1
if self.api:
time.sleep(self.wait_time)
else:
counter += self._set_following(twf.screen_name)
# Remove friend from list
try:
last_friends.remove(twf.screen_name)
except ValueError:
pass
# end try
# end for
# Commit and wait
self._session.commit()
time.sleep(60)
# end for
finished = True
except tweepy.error.RateLimitError:
# Rate limit reached, wait 5 minutes
time.sleep(300)
pass
# end try
# end while
# Update status of friends not follower/following
# anymore
for name in last_friends:
if follower:
self._set_follower(screen_name=name, follower=False)
else:
self._set_following(screen_name=name, following=False)
# end if
deleted += 1
# end for
jsono["top_friend_timezones"] = friends_timezone
if args.json is not False:
print(json.dumps(jsono))
export_write()
if args.save:
save_file.seek(-1, os.SEEK_END) # drop last ,
save_file.truncate()
save_file.write("]")
save_file.close()
if __name__ == '__main__':
try:
main()
except tweepy.error.TweepError as e:
cprint("[\033[91m!\033[0m] Twitter error: %s" % e)
except Exception as e:
cprint("[\033[91m!\033[0m] Error: %s" % e)
def clean(self):
# if we are updating an existing TwitterUser
# AND is_active=False
if self.id is not None and self.is_active is False:
return
# else proceed with further logic because:
# either we are creating rather than updating
# OR we are updating with active=True
# get an api
try:
api = authenticated_api(username=settings.TWITTER_DEFAULT_USERNAME)
except tweepy.error.TweepError as e:
raise ValidationError('Could not connect to Twitter \
API using configured credentials. \
Error: %s' % e)
if api is None:
raise ValidationError('Could not connect to Twitter \
API using configured credentials.')
# we're activating an existing TwitterUser
if self.id is not None:
try:
user_status = api.get_user(id=self.uid)
except tweepy.error.TweepError as e:
raise ValidationError('Twitter returned the following \
error: %s' % e.message)
# if we're creating a new TwitterUser, then look up by name
LOGGER.info('Processing Tweets for search: "{0}"...'.format(search))
try:
recent_tweets = tweepy.Cursor(api.search, q=search).items(MAX_SEARCH_ITEMS)
for recent_tweet in recent_tweets:
tweet_indicators = parse_tweet(recent_tweet)
if len(tweet_indicators) > 0:
indicator_list.extend(tweet_indicators)
if THROTTLE_REQUESTS:
LOGGER.info('Waiting a moment...')
time.sleep(WAIT_SECONDS)
except tweepy.error.TweepError as ex:
LOGGER.error('Failed to query Twitter: {0}'.format(str(ex)))
if ex.api_code == 429:
LOGGER.info('Waiting a moment...')
time.sleep(WAIT_SECONDS)
else:
return []
except Exception as ex:
LOGGER.error('Failed to query Twitter: {0}'.format(str(ex)))
return []
return indicator_list
twitter_user = api.get_user(screen_name=twitter_handle)
twitter_json = twitter_user._json
success = True
status += 'TWITTER_RETRIEVE_SUCCESSFUL-TWITTER_HANDLE ' + str(twitter_handle) + " "
twitter_handle_found = True
twitter_user_id = twitter_user.id # Integer value. id_str would be the String value
else:
twitter_json = {}
success = False
status += 'TWITTER_RETRIEVE_NOT_SUCCESSFUL-MISSING_VARIABLE '
twitter_handle_found = False
except tweepy.RateLimitError as rate_limit_error:
success = False
status += 'TWITTER_RATE_LIMIT_ERROR '
handle_exception(rate_limit_error, logger=logger, exception_message=status)
except tweepy.error.TweepError as error_instance:
success = False
status += twitter_handle + " " if positive_value_exists(twitter_handle) else ""
status += str(twitter_user_id) + " " if positive_value_exists(twitter_user_id) else " "
error_tuple = error_instance.args
for error_dict in error_tuple:
for one_error in error_dict:
status += '[' + one_error['message'] + '] '
handle_exception(error_instance, logger=logger, exception_message=status)
try:
if positive_value_exists(twitter_json.get('profile_banner_url')):
# Dec 2019, https://developer.twitter.com/en/docs/accounts-and-users/user-profile-images-and-banners
banner = twitter_json.get('profile_banner_url') + '/1500x500'
twitter_json['profile_banner_url'] = banner
except Exception as e:
status += "FAILED_PROFILE_BANNER_URL " + str(e) + " "
def safe_tweet(twitter, status, dupe_ok=True):
LOG.debug('posting %r', status)
try:
twitter.update_status(status=status)
except tweepy.error.TweepError as e:
LOG.debug('failed: %s', e.reason)
if dupe_ok and e.api_code == 187:
return False
raise RuntimeError('API failure: {}'.format(e.reason))
return True
foafs=[]
for m in mi: foafs.append(m)
if isinstance(foafs,tuple): foafs,junk=foafs
except tweepy.error.TweepError,e:
report(e)
else:
if friend.followers_count>maxf:
foafs=[]
else:
try:
#foafs=api.followers_ids(friend.id)
mi=tweepy.Cursor(api.followers_ids,id=friend.id).items()
foafs=[]
for m in mi: foafs.append(m)
if isinstance(foafs,tuple): foafs,junk=foafs
except tweepy.error.TweepError,e:
report(e)
extrafriends=diffset(foafs,membersid)
#being naughty - changing .status to record no. of foafs/no. in community
if hasattr(members[id], 'status'):
members[id].status=0.7+0.3*len(extrafriends)/M
report("...weight: "+str(members[id].status))
for foaf in extrafriends:
f.write(str(friend.id)+','+str(foaf)+'\n')
self.logger.debug(
"Fetching latest tweet by {}".format(tw_user.screen_name))
tweets = bot.tw.user_timeline(
screen_name=tw_user.screen_name,
count=1,
tweet_mode='extended')
else:
# get the fresh tweets
self.logger.debug(
"Fetching new tweets from {}".format(tw_user.screen_name))
tweets = bot.tw.user_timeline(
screen_name=tw_user.screen_name,
since_id=tw_user.last_tweet_id,
tweet_mode='extended')
updated_tw_users.append(tw_user)
except tweepy.error.TweepError as e:
sc = e.response.status_code
if sc == 429:
self.logger.debug("- Hit ratelimit, breaking.")
break
if sc == 401:
users_to_cleanup.append((tw_user, 'PROTECTED'))
self.logger.debug("- Protected tweets here. Cleaning up this user")
continue
if sc == 404:
users_to_cleanup.append((tw_user, 'NOTFOUND'))
self.logger.debug("- 404? Maybe screen name changed? Cleaning up this user")
continue
self.logger.debug(