class TwitterApi(object): """Singleton class that connects to twitter account.""" api = None instance = None def __new__(cls): if cls.instance is None: cls.instance = super(TwitterApi, cls).__new__(cls) return cls.instance def __init__(self): if self.api is None: self.api = Api(*TWITTER_SETTINGS) def _get_tweet_user_name(self, tweet): """Return the screen name of tweet author.""" return tweet.user.screen_name def get_home_tweets(self): """Return a dictionary of all the tweets with their users.""" home_tweets = self.api.GetHomeTimeline() tweets = [( tweet.id, self._get_tweet_user_name(tweet), unicode(tweet.text)) for tweet in home_tweets] return tweets
def pull_and_publish( consumer_key: str, consumer_secret: str, access_token: str, access_token_secret: str, slack_token: str, slack_channel: str, wait_time: int, ): """Continuously pull recent Twitter statuses and publish them to Slack.""" twitter_api = Api(consumer_key, consumer_secret, access_token, access_token_secret) slack_client = WebClient(slack_token) channel_id = _get_channel_id(slack_client, slack_channel) since_id = None while True: statuses = twitter_api.GetHomeTimeline(since_id=since_id) if statuses: logger.info(f"Got {len(statuses)} statuses from Twitter.") since_id = publish_new_statuses(channel_id, since_id, slack_channel, slack_client, statuses) else: logger.info("No new twitter statuses.") time.sleep(wait_time)
def get_home_timeline(session: Api) -> List[Tweet]: try: timeline = session.GetHomeTimeline(count=200, exclude_replies=True, include_entities=False) return [status.AsDict() for status in timeline] except TwitterError: return []