Python tweepy.TweepError() Examples
The following are 30
code examples of tweepy.TweepError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
tweepy
, or try the search function
.
Example #1
Source File: tweets.py From Trusty-cogs-archive with MIT License | 6 votes |
def _add(self, ctx, account, channel:discord.Channel=None): """Adds a twitter account to the specified channel""" api = await self.authenticate() try: for status in tw.Cursor(api.user_timeline, id=account).items(1): user_id = str(status.user.id) screen_name = status.user.screen_name last_id = status.id except tw.TweepError as e: print("Whoops! Something went wrong here. \ The error code is " + str(e) + account) await self.bot.say("That account does not exist! Try again") return if channel is None: channel = ctx.message.channel added = await self.add_account(channel, user_id, screen_name) if added: await self.bot.say("{0} Added to {1}!".format(account, channel.mention)) else: await self.bot.say("{} is already posting or could not be added to {}".format(account, channel.mention))
Example #2
Source File: twitter.py From CloudBot with GNU General Public License v3.0 | 6 votes |
def twitter_url(match, conn): # Find the tweet ID from the URL tweet_id = match.group(1) # Get the tweet using the tweepy API tw_api = container.api if tw_api is None: return try: tweet = tw_api.get_status(tweet_id, tweet_mode=get_tweet_mode(conn)) except tweepy.TweepError as e: if e.api_code in IGNORE_ERRORS: return raise user = tweet.user return format_tweet(tweet, user)
Example #3
Source File: oscrtwitter.py From NoobSec-Toolkit with GNU General Public License v2.0 | 6 votes |
def twitSearch(t_api): t_query = raw_input('Enter search: ') t_res = tweepy.Cursor(t_api.search, q=t_query, count=10, result='recent', include_entities=True).items() while True: try: tweet = t_res.next() print tweet.user.screen_name.encode('utf-8'), ':', \ tweet.created_at, ':', tweet.text.encode('utf-8') print # print an extra line...just for readability sleep(5) # sleep so it is human readable except tweepy.TweepError: # if tweepy encounters an error, sleep for fifteen minutes..this will # help against API bans. sleep(60 * 15) except KeyboardInterrupt: return
Example #4
Source File: bot.py From twitterbot with MIT License | 6 votes |
def post_tweet(self, text, reply_to=None, media=None): kwargs = {} args = [text] if media is not None: cmd = self.api.update_with_media args.insert(0, media) else: cmd = self.api.update_status try: self.log('Tweeting "{}"'.format(text)) if reply_to: self.log("-- Responding to status {}".format(self._tweet_url(reply_to))) kwargs['in_reply_to_status_id'] = reply_to.id else: self.log("-- Posting to own timeline") tweet = cmd(*args, **kwargs) self.log('Status posted at {}'.format(self._tweet_url(tweet))) return True except tweepy.TweepError as e: self._log_tweepy_error('Can\'t post status', e) return False
Example #5
Source File: tipcheck.py From NanoTipBot with GNU General Public License v3.0 | 6 votes |
def unregistered_user_reminder(day_difference, dm_text): """ Check for unregistered users day_difference away from the current day and send a DM with the provided dm_text """ db_call = ("SELECT user_id, system " "FROM users " "WHERE register = 0 " "AND DATE(created_ts) BETWEEN DATE_SUB(NOW(), INTERVAL {} DAY) " "AND DATE_SUB(NOW(), INTERVAL {} DAY)").format(day_difference, (day_difference - 1)) try: unregistered_users = get_db_data(db_call) except Exception as e: logging.info(e) raise e logging.info("unregistered_users: {}".format(unregistered_users)) for user in unregistered_users: try: send_dm(user[0], dm_text, user[1]) logging.info("{}: User {} reminded after {} days.".format(str(datetime.now()), user[0], day_difference)) except tweepy.TweepError as e: logging.info("{}: Tweepy Error: {}".format(datetime.now(), e)) except Exception as e: logging.info("{}: Exception: {}".format(datetime.now(), e)) raise e
Example #6
Source File: social.py From NanoTipBot with GNU General Public License v3.0 | 6 votes |
def send_reply(message, text): if check_mute(message['sender_id'], message['system']): logger.info("{}: User has muted bot.".format(datetime.now())) return if message['system'] == 'twitter': text = '@{} '.format(message['sender_screen_name']) + text try: api.update_status(text, message['id']) except tweepy.TweepError as e: logger.info("{}: Send Reply Tweepy Error: {}".format(datetime.now(), e)) elif message['system'] == 'telegram': try: telegram_bot.sendMessage(chat_id=message['chat_id'], reply_to_message_id=message['id'], text=text) except Exception as e: logger.info("{}: Send reply telegram error3 {}".format(datetime.now(), e))
Example #7
Source File: tweets.py From Trusty-cogs-archive with MIT License | 6 votes |
def _del(self, ctx, account, channel:discord.Channel=None): """Removes a twitter account to the specified channel""" account = account.lower() api = await self.authenticate() if channel is None: channel = ctx.message.channel try: for status in tw.Cursor(api.user_timeline, id=account).items(1): user_id = str(status.user.id) except tw.TweepError as e: print("Whoops! Something went wrong here. \ The error code is " + str(e) + account) await self.bot.say("That account does not exist! Try again") return removed = await self.del_account(channel, user_id) if removed: await self.bot.say("{} has been removed from {}".format(account, channel.mention)) else: await self.bot.say("{0} doesn't seem to be posting in {1}!" .format(account, channel.mention))
Example #8
Source File: booster.py From booster with ISC License | 6 votes |
def loop_search(self): while True: try: query = random.choice(config.settings.keywords) for item in self.api.search(q='#' + query, count=50, lang='en', result_type='recent'): if not item.user.following and not item.favorited: try: self.api.create_favorite(item.id) self.api.create_friendship(item.user.screen_name) print('[+] - Followed a booster twitter!') except tweepy.TweepError as ex: print('[!] - Unknown error occured in the search loop! ({ex!s})') time.sleep(60*60) except tweepy.TweepError as ex: debug.error('Error occured in the search loop!', ex) finally: time.sleep(60*15)
Example #9
Source File: tweepy_pool.py From smappPy with GNU General Public License v2.0 | 6 votes |
def _call_with_throttling_per_method(self, method_name, *args, **kwargs): api_struct = self._pick_api_with_shortest_waiting_time_for_method(method_name) now = datetime.now() throttle_time = api_struct[1].get(method_name, datetime.min) time_since_throttle = (now - throttle_time).seconds to_wait = self.time_to_wait - time_since_throttle + 1 if to_wait > 0: logger.debug("<{1}>: Rate limits exhausted, waiting {0} seconds".format( to_wait, now.strftime('%H:%M:%S'))) time.sleep(to_wait) try: return api_struct[0].__getattribute__(method_name)(*args, **kwargs) except TweepError as e: error_dict = parse_tweepy_error(e) if error_dict["code"] in [RATE_LIMIT_ERROR, TOO_MANY_REQUESTS, OVER_CAP_ERROR]: api_struct[1][method_name] = now logger.debug("Received limit message: {0}".format(error_dict["message"])) return self._call_with_throttling_per_method(method_name, *args, **kwargs) else: raise(e)
Example #10
Source File: api.py From twitter_bot_utils with GNU General Public License v3.0 | 6 votes |
def media_upload(self, filename, *args, **kwargs): """ :reference: https://dev.twitter.com/rest/reference/post/media/upload :reference https://dev.twitter.com/rest/reference/post/media/upload-chunked :allowed_param: """ f = kwargs.pop('file', None) mime, _ = mimetypes.guess_type(filename) size = getfilesize(filename, f) if mime in IMAGE_MIMETYPES and size < self.max_size_standard: return self.image_upload(filename, file=f, *args, **kwargs) elif mime in CHUNKED_MIMETYPES: return self.upload_chunked(filename, file=f, *args, **kwargs) else: raise TweepError("Can't upload media with mime type %s" % mime)
Example #11
Source File: booster.py From booster with ISC License | 6 votes |
def loop_follow(self): while True: try: followers = self.api.followers_ids(self.me.screen_name) friends = self.api.friends_ids(self.me.screen_name) non_friends = [friend for friend in followers if friend not in friends] print(f'[~] - Following back {len(non_friends)} supporters...') for follower in non_friends: self.api.create_friendship(follower) print('[+] - Followed back a follower!') if config.settings.message: self.api.send_direct_message(screen_name=follower, text=self.message) time.sleep(60*60) except tweepy.TweepError as ex: print(f'[!] - Error occured in the follow loop! ({ex!s})') finally: time.sleep(60*15)
Example #12
Source File: twitter_tags.py From digihel with MIT License | 6 votes |
def twitter_search(query): """ Search Twitter for the given query and result results :param query: :type query: :return: :rtype: """ tweepy_api = get_tweepy_api() if not tweepy_api: return None try: results = list(get_cached_with_mtime( cache_key='twitter_%s' % slugify(query), max_mtime=TWEET_CACHE_REFRESH_AGE, getter=lambda: tweepy_api.search(q=query, rpp=100, result_type='recent'), default=[], )) except tweepy.TweepError as error: print('Tweepy responded with error: ' + str(error)) return None for result in results: result.html = render_tweet_html(result) return results
Example #13
Source File: cli.py From twitter_bot_utils with GNU General Public License v3.0 | 6 votes |
def post(arguments): '''Post text to a given twitter account.''' twitter = api.API(arguments) params = {} if arguments.update == '-': params['status'] = sys.stdin.read() else: params['status'] = arguments.update if arguments.media_file: medias = [twitter.media_upload(m) for m in arguments.media_file] params['media_ids'] = [m.media_id for m in medias] try: logging.getLogger(arguments.screen_name).info('status: %s', params['status']) if not arguments.dry_run: twitter.update_status(**params) except tweepy.TweepError as e: logging.getLogger(arguments.screen_name).error(e.message)
Example #14
Source File: read_tweepy.py From locality-sensitive-hashing with MIT License | 6 votes |
def get(self): resp = self.get_args() rqst = self.request verifier = rqst.get('oauth_verifier') this_app = AppOpenLSH.get_or_insert('KeyOpenLSH') auth = tweepy.OAuthHandler(this_app.twitter_consumer_key, this_app.twitter_consumer_secret) auth.set_request_token(self.session['request_token_key'], self.session['request_token_secret']) try: auth.get_access_token(verifier) self.session['auth.access_token.key'] = auth.access_token.key self.session['auth.access_token.secret'] = auth.access_token.secret this_app.twitter_access_token(auth.access_token.key, auth.access_token.secret) self.session['tw_logged_in'] = True self.session['tweets'] = [] frameinfo = getframeinfo(currentframe()) logging.debug('file %s, line %s auth %s %s', frameinfo.filename, frameinfo.lineno+1, auth.access_token.key, auth.access_token.secret) except tweepy.TweepError: logging.error('Error! Failed to get access token.') self.redirect('/')
Example #15
Source File: sentiment.py From danlp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def lookup_tweets(tweet_ids, api): import tweepy full_tweets = [] tweet_count = len(tweet_ids) try: for i in range(int(tweet_count/100)+1): # Catch the last group if it is less than 100 tweets end_loc = min((i + 1) * 100, tweet_count) full_tweets.extend( api.statuses_lookup(id_=tweet_ids[i * 100:end_loc], tweet_mode='extended', trim_user=True) ) return full_tweets except tweepy.TweepError: print("Failed fetching tweets")
Example #16
Source File: tweets.py From Trusty-cogs with MIT License | 5 votes |
def get_twitter_user(self, username: str) -> tw.User: try: api = await self.authenticate() fake_task = functools.partial(api.get_user, username) task = self.bot.loop.run_in_executor(None, fake_task) user = await asyncio.wait_for(task, timeout=10) except asyncio.TimeoutError: raise except tw.error.TweepError: raise return user
Example #17
Source File: sentiment.py From danlp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def construct_twitter_api_connection(): if not('TWITTER_CONSUMER_KEY' in os.environ and 'TWITTER_CONSUMER_SECRET' in os.environ and 'TWITTER_ACCESS_TOKEN' in os.environ and 'TWITTER_ACCESS_SECRET' in os.environ): sys.exit("The Twitter API keys was not found." "\nTo download tweets you need to set the following environment " "variables: \n- 'TWITTER_CONSUMER_KEY'\n- 'TWITTER_CONSUMER_SECRET'" "\n- 'TWITTER_ACCESS_TOKEN'\n- 'TWITTER_ACCESS_SECRET' " "\n\nThe keys can be obtained from " "https://developer.twitter.com") twitter_consumer_key = os.environ.get('TWITTER_CONSUMER_KEY') twitter_consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET') twitter_access_token = os.environ.get('TWITTER_ACCESS_TOKEN') twitter_access_secret = os.environ.get('TWITTER_ACCESS_SECRET') auth = tweepy.OAuthHandler(twitter_consumer_key, twitter_consumer_secret) auth.set_access_token(twitter_access_token, twitter_access_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) try: api.verify_credentials() except twe<epy.TweepError: sys.exit("Could not establish connection to the Twitter API, have you provieded the correct keys?") return api
Example #18
Source File: twitter.py From picdescbot with MIT License | 5 votes |
def send(self, picture): "Send a tweet. `picture` is a `Result` object from `picdescbot.common`" retries = 0 status = None filename = picture.url.split('/')[-1] data = picture.download_picture() try: while retries < 3 and not status: if retries > 0: self.log.info('retrying...') data.seek(0) try: text = f"{picture.caption}\n\n{picture.source_url}" status = self.api.update_with_media(filename=filename, status=text, file=data) except tweepy.TweepError as e: self.log.error("Error when sending tweet: %s" % e) retries += 1 if retries >= 3: raise else: time.sleep(5) finally: data.close(really=True) return status.id
Example #19
Source File: 04_UserDataTwitter.py From Python with MIT License | 5 votes |
def get_followers(screen_name): print('Getting Follower list of ',screen_name) followers = [] followers_screenNames = [] users = tweepy.Cursor(api.followers, screen_name='@'+screen_name, wait_on_rate_limit=True,count=200) for user in users.items(): try: followers.append(user) followers_screenNames.append(user.screen_name) except tweepy.TweepError as e: print("Going to sleep:", e) # time.sleep(60) print('Fetched number of followers for '+screen_name+' : ',len(followers)) return followers,followers_screenNames
Example #20
Source File: Sentiment_Analysis_Crypto_Historic.py From Cryptocurrency-Trading-Bots-Python-Beginner-Advance with MIT License | 5 votes |
def get_tweets(self, query, count = 10): ''' Main function to fetch tweets and parse them. ''' # empty list to store parsed tweets tweets = [] try: # call twitter api to fetch tweets fetched_tweets = self.api.search(q = query, count = count) # parsing tweets one by one for tweet in fetched_tweets: # empty dictionary to store required params of a tweet parsed_tweet = {} # saving text of tweet parsed_tweet['text'] = tweet.text # saving sentiment of tweet parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text) # appending parsed tweet to tweets list if tweet.retweet_count > 0: # if tweet has retweets, ensure that it is appended only once if parsed_tweet not in tweets: tweets.append(parsed_tweet) else: tweets.append(parsed_tweet) # return parsed tweets return tweets except tweepy.TweepError as e: # print error (if any) print("Error : " + str(e))
Example #21
Source File: jobtweets.py From jobtweets with MIT License | 5 votes |
def get_tweets(self, query, count = 10): ''' Main function to fetch tweets and parse them. ''' tweets = [] try: fetched_tweets = self.api.search(q = query, count = count) for tweet in fetched_tweets: parsed_tweet = {} parsed_tweet['text'] = tweet.text parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text) if tweet.retweet_count > 0: if parsed_tweet not in tweets: tweets.append(parsed_tweet) else: tweets.append(parsed_tweet) return tweets except tweepy.TweepError as e: print("Error : " + str(e))
Example #22
Source File: jobs.py From jobtweets with MIT License | 5 votes |
def get_tweets(self, query, count = 10): ''' Main function to fetch tweets and parse them. ''' tweets = [] try: fetched_tweets = self.api.search(q = query, count = count) for tweet in fetched_tweets: parsed_tweet = {} parsed_tweet['text'] = tweet.text parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text) if tweet.retweet_count > 0: if parsed_tweet not in tweets: tweets.append(parsed_tweet) else: tweets.append(parsed_tweet) return tweets except tweepy.TweepError as e: print("Error : " + str(e))
Example #23
Source File: jobopportunities.py From jobtweets with MIT License | 5 votes |
def get_tweets(self, query, count = 10): ''' Main function to fetch tweets and parse them. ''' tweets = [] try: fetched_tweets = self.api.search(q = query, count = count) for tweet in fetched_tweets: parsed_tweet = {} parsed_tweet['text'] = tweet.text parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text) if tweet.retweet_count > 0: if parsed_tweet not in tweets: tweets.append(parsed_tweet) else: tweets.append(parsed_tweet) return tweets except tweepy.TweepError as e: print("Error : " + str(e))
Example #24
Source File: tweets.py From Trusty-cogs with MIT License | 5 votes |
def get_tweets( self, ctx: commands.context, username: str, count: Optional[int] = 10, replies: bool = True ) -> None: """ Display a users tweets as a scrollable message defaults to 10 tweets """ msg_list = [] api = await self.authenticate() try: fake_task = functools.partial( self._get_twitter_statuses, api=api, username=username, count=count, replies=replies, ) task = self.bot.loop.run_in_executor(None, fake_task) msg_list = await asyncio.wait_for(task, timeout=30) except asyncio.TimeoutError: msg = _("Timedout getting tweet list") await ctx.send(msg) except tw.TweepError as e: msg = _("Whoops! Something went wrong here. The error code is ") + f"{e} {username}" await ctx.send(msg) return if len(msg_list) > 0: await self.tweet_menu(ctx, msg_list, page=0, timeout=30) else: await ctx.send(_("No tweets available to display!"))
Example #25
Source File: tweets.py From Trusty-cogs with MIT License | 5 votes |
def _get_twitter_statuses( self, api: tw.API, username: str, count: int, replies: bool ) -> List[tw.Status]: cnt = count if count and count > 25: cnt = 25 msg_list = [] try: for status in tw.Cursor(api.user_timeline, id=username).items(cnt): if status.in_reply_to_screen_name is not None and not replies: continue msg_list.append(status) except tw.TweepError: raise return msg_list
Example #26
Source File: tweets.py From Trusty-cogs with MIT License | 5 votes |
def get_user(self, ctx: commands.context, username: str) -> None: """Get info about the specified user""" try: user = await self.get_twitter_user(username) except asyncio.TimeoutError: await ctx.send(_("Looking up the user timed out.")) return except tw.error.TweepError: await ctx.send(_("{username} could not be found.").format(username=username)) return profile_url = "https://twitter.com/" + user.screen_name description = str(user.description) for url in user.entities["description"]["urls"]: if str(url["url"]) in description: description = description.replace(url["url"], str(url["expanded_url"])) emb = discord.Embed( colour=discord.Colour(value=int(user.profile_link_color, 16)), url=profile_url, description=str(description), timestamp=user.created_at, ) emb.set_author(name=user.name, url=profile_url, icon_url=user.profile_image_url) emb.set_thumbnail(url=user.profile_image_url) emb.add_field(name="Followers", value=user.followers_count) emb.add_field(name="Friends", value=user.friends_count) if user.verified: emb.add_field(name="Verified", value="Yes") footer = "Created at " emb.set_footer(text=footer) if ctx.channel.permissions_for(ctx.me).embed_links: await ctx.send("<" + profile_url + ">", embed=emb) else: await ctx.send(profile_url)
Example #27
Source File: hiring.py From jobtweets with MIT License | 5 votes |
def get_tweets(self, query, count = 10): ''' Main function to fetch tweets and parse them. ''' tweets = [] try: fetched_tweets = self.api.search(q = query, count = count) for tweet in fetched_tweets: parsed_tweet = {} parsed_tweet['text'] = tweet.text parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text) if tweet.retweet_count > 0: if parsed_tweet not in tweets: tweets.append(parsed_tweet) else: tweets.append(parsed_tweet) return tweets except tweepy.TweepError as e: print("Error : " + str(e))
Example #28
Source File: booster.py From booster with ISC License | 5 votes |
def loop_unfollow(self): try: followers = self.api.followers_ids(self.me.screen_name) friends = self.api.friends_ids(self.me.screen_name) non_friends = [friend for friend in friends if friend not in followers] non_friends.reverse() print(f'[~] - Unfollowing {len(non_friends)} unsupporting friends...') for friend in non_friends: self.api.destroy_friendship(friend) print('[+] - Unfollowed an unsupporting friend!') time.sleep(60*30) except tweepy.TweepError as ex: debug.error('Error occured in the unfollow loop!', ex)
Example #29
Source File: booster.py From booster with ISC License | 5 votes |
def loop_favorite(self): while True: try: for tweet in tweepy.Cursor(self.api.home_timeline, exclude_replies=True).items(50): if tweet.user.screen_name != self.me.screen_name: if not tweet.favorited: if random.choice((True, False, False, False, False)): self.api.create_favorite(tweet.id) print('[+] - Favorited a friends tweet!') time.sleep(60*60) except tweepy.TweepError as ex: print(f'[!] - Error occured in the favorite loop! ({ex!s})') finally: time.sleep(60*15)
Example #30
Source File: booster.py From booster with ISC License | 5 votes |
def loop_boost(self): while True: try: if 'boost_tweet' in locals(): self.api.destroy_status(boost_tweet.id) boost_tweet = self.api.update_status('RT for followers! #' + ' #'.join(random.sample(config.settings.keywords, len(config.settings.keywords)))) print('[+] - Reposted boost tweet.') except tweepy.TweepError as ex: print(f'[!] - Error occured in the boost loop ({ex!s})') finally: time.sleep(60*5)