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


Python Tweet.get_or_create方法代码示例

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


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

示例1: run

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import get_or_create [as 别名]
    def run(self):
        self.logger.debug("Fetching tweets...")
        # fetch the tw users' tweets
        tw_users = (TwitterUser.select()
                               .join(Subscription)
                               .group_by(TwitterUser)
                               .order_by(TwitterUser.last_fetched))

        for tw_user in tw_users:
                
            try:
                if tw_user.last_tweet_id == 0:
                    # get just the latest tweet
                    self.logger.debug(
                        "Fetching latest tweet by {}".format(tw_user.screen_name))
                    tweets = self.bot.tw.user_timeline(
                        screen_name=tw_user.screen_name,
                        count=1)
                else:
                    # get the fresh tweets
                    self.logger.debug(
                        "Fetching new tweets from {}".format(tw_user.screen_name))
                    tweets = self.bot.tw.user_timeline(
                        screen_name=tw_user.screen_name,
                        since_id=tw_user.last_tweet_id)
                tw_user.last_fetched = datetime.now()
                tw_user.save()
            except tweepy.error.TweepError as e:
                sc = e.response.status_code
                if sc == 429:
                    self.logger.debug("- Hit ratelimit, breaking.")
                    break
                    
                if sc == 401:
                    self.logger.debug("- Protected tweets here.")
                    continue
                    
                if sc == 404:
                    self.logger.debug("- 404? Maybe screen name changed?")
                    continue
                    
                self.logger.debug(
                    "- Unknown exception, Status code {}".format(sc))
                continue

            for tweet in tweets:
                self.logger.debug("- Got tweet: {}".format(tweet.text))

                # Check if tweet contains media, else check if it contains a link to an image
                extensions = ('.jpg', '.jpeg', '.png', '.gif')
                pattern = '[(%s)]$' % ')('.join(extensions)
                photo_url = ''

                if 'media' in tweet.entities:
                    photo_url = tweet.entities['media'][0]['media_url_https']
                else:
                    for url in tweet.entities['urls']:
                        if re.search(pattern, url['expanded_url']):
                            photo_url = url['expanded_url']
                            break

                if photo_url:
                    self.logger.debug("- - Found media URL in tweet: " + photo_url)

                tw, _created = Tweet.get_or_create(
                    tw_id=tweet.id,
                    text=html.unescape(tweet.text),
                    created_at=tweet.created_at,
                    twitter_user=tw_user,
                    photo_url=photo_url,
                )

        # send the new tweets to subscribers
        for s in Subscription.select():
            # are there new tweets? send em all!
            self.logger.debug(
                "Checking subscription {} {}".format(s.tg_chat.chat_id, s.tw_user.screen_name))

            if s.last_tweet_id == 0:  # didn't receive any tweet yet
                try:
                    tw = (s.tw_user.tweets.select()
                           .order_by(Tweet.tw_id.desc())
                           .limit(1))[0]
                    self.bot.send_tweet(s.tg_chat, tw)

                    # save the latest tweet sent on this subscription
                    s.last_tweet_id = tw.tw_id
                    s.save()
                except IndexError:
                    self.logger.debug("- No tweets available yet on {}".format(s.tw_user.screen_name))

                continue

            if s.tw_user.last_tweet_id > s.last_tweet_id:
                self.logger.debug("- Some fresh tweets here!")
                for tw in (s.tw_user.tweets.select()
                            .where(Tweet.tw_id > s.last_tweet_id)
                            .order_by(Tweet.tw_id.desc())
                           ):
                    self.bot.send_tweet(s.tg_chat, tw)
#.........这里部分代码省略.........
开发者ID:franciscod,项目名称:telegram-twitter-forwarder-bot,代码行数:103,代码来源:bot.py

示例2: run

# 需要导入模块: from models import Tweet [as 别名]
# 或者: from models.Tweet import get_or_create [as 别名]
    def run(self):
        self.logger.debug("Fetching tweets...")
        # fetch the tw users' tweets
        for tw_user in TwitterUser.select():
            if tw_user.subscriptions.count() == 0:
                self.logger.debug(
                    "Skipping {} because 0 subscriptions".format(tw_user.screen_name))
                continue

            try:
                if tw_user.last_tweet_id == 0:
                    # get just the latest tweet
                    self.logger.debug(
                        "Fetching the latest tweet from {}".format(tw_user.screen_name))
                    tweets = self.bot.tw.user_timeline(
                        screen_name=tw_user.screen_name,
                        count=1)
                else:
                    # get the fresh tweets
                    self.logger.debug(
                        "Fetching new tweets from {}".format(tw_user.screen_name))
                    tweets = self.bot.tw.user_timeline(
                        screen_name=tw_user.screen_name,
                        since_id=tw_user.last_tweet_id)

            except tweepy.error.TweepError:
                self.logger.debug(
                    "Whoops, I couldn't get tweets from {}!".format(tw_user.screen_name))
                continue

            for tweet in tweets:
                self.logger.debug("Got tweet: {}".format(tweet.text))

                # Check if tweet contains media, else check if it contains a link to an image
                extensions = ('.jpg', '.jpeg', '.png', '.gif')
                pattern = '[(%s)]$' % ')('.join(extensions)
                photo_url = ''

                if 'media' in tweet.entities:
                    photo_url = tweet.entities['media'][0]['media_url_https']
                else:
                    for url in tweet.entities['urls']:
                        if re.search(pattern, url['expanded_url']):
                            photo_url = url['expanded_url']
                            break

                if photo_url:
                    self.logger.debug("Found media URL in tweet: " + photo_url)

                tw, _created = Tweet.get_or_create(
                    tw_id=tweet.id,
                    text=html.unescape(tweet.text),
                    created_at=tweet.created_at,
                    twitter_user=tw_user,
                    photo_url=photo_url,
                )

        # send the new tweets to subscribers
        for s in Subscription.select():
            # are there new tweets? send em all!
            self.logger.debug(
                "Checking subscription {} {}".format(s.tg_chat.chat_id, s.tw_user.screen_name))

            if s.last_tweet_id == 0:  # didn't receive any tweet yet
                try:
                    tw = (s.tw_user.tweets.select()
                           .order_by(Tweet.tw_id.desc())
                           .limit(1))[0]
                    self.bot.send_tweet(s.tg_chat, tw)

                    # save the latest tweet sent on this subscription
                    s.last_tweet_id = tw.tw_id
                    s.save()
                except IndexError:
                    self.logger.debug("No tweets available yet on {}".format(s.tw_user.screen_name))

                continue

            if s.tw_user.last_tweet_id > s.last_tweet_id:
                self.logger.debug("Some fresh tweets here!")
                for tw in (s.tw_user.tweets.select()
                            .where(Tweet.tw_id > s.last_tweet_id)
                            .order_by(Tweet.tw_id.desc())
                           ):
                    self.bot.send_tweet(s.tg_chat, tw)

                # save the latest tweet sent on this subscription
                s.last_tweet_id = s.tw_user.last_tweet_id
                s.save()
                continue

            self.logger.debug("No new tweets here.")
开发者ID:jh0ker,项目名称:telegram-twitter-forwarder-bot,代码行数:94,代码来源:bot.py


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