当前位置: 首页>>代码示例>>Python>>正文


Python tweepy.TweepError方法代码示例

本文整理汇总了Python中tweepy.TweepError方法的典型用法代码示例。如果您正苦于以下问题:Python tweepy.TweepError方法的具体用法?Python tweepy.TweepError怎么用?Python tweepy.TweepError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tweepy的用法示例。


在下文中一共展示了tweepy.TweepError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _add

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import TweepError [as 别名]
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)) 
开发者ID:TrustyJAID,项目名称:Trusty-cogs-archive,代码行数:23,代码来源:tweets.py

示例2: get

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import TweepError [as 别名]
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('/') 
开发者ID:singhj,项目名称:locality-sensitive-hashing,代码行数:26,代码来源:read_tweepy.py

示例3: post

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import TweepError [as 别名]
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) 
开发者ID:fitnr,项目名称:twitter_bot_utils,代码行数:23,代码来源:cli.py

示例4: media_upload

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import TweepError [as 别名]
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) 
开发者ID:fitnr,项目名称:twitter_bot_utils,代码行数:20,代码来源:api.py

示例5: _del

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import TweepError [as 别名]
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)) 
开发者ID:TrustyJAID,项目名称:Trusty-cogs-archive,代码行数:22,代码来源:tweets.py

示例6: send_reply

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import TweepError [as 别名]
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)) 
开发者ID:mitche50,项目名称:NanoTipBot,代码行数:19,代码来源:social.py

示例7: unregistered_user_reminder

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import TweepError [as 别名]
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 
开发者ID:mitche50,项目名称:NanoTipBot,代码行数:27,代码来源:tipcheck.py

示例8: post_tweet

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import TweepError [as 别名]
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 
开发者ID:thricedotted,项目名称:twitterbot,代码行数:26,代码来源:bot.py

示例9: twitter_url

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import TweepError [as 别名]
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) 
开发者ID:TotallyNotRobots,项目名称:CloudBot,代码行数:22,代码来源:twitter.py

示例10: twitSearch

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import TweepError [as 别名]
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 
开发者ID:krintoxi,项目名称:NoobSec-Toolkit,代码行数:22,代码来源:oscrtwitter.py

示例11: _call_with_throttling_per_method

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import TweepError [as 别名]
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) 
开发者ID:SMAPPNYU,项目名称:smappPy,代码行数:24,代码来源:tweepy_pool.py

示例12: loop_follow

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import TweepError [as 别名]
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) 
开发者ID:acidvegas,项目名称:booster,代码行数:19,代码来源:booster.py

示例13: loop_search

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import TweepError [as 别名]
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) 
开发者ID:acidvegas,项目名称:booster,代码行数:19,代码来源:booster.py

示例14: twitter_search

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import TweepError [as 别名]
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 
开发者ID:City-of-Helsinki,项目名称:digihel,代码行数:26,代码来源:twitter_tags.py

示例15: get_followers

# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import TweepError [as 别名]
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 
开发者ID:Ajinkya-Sonawane,项目名称:Python,代码行数:17,代码来源:04_UserDataTwitter.py


注:本文中的tweepy.TweepError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。