#!/usr/bin/env python import re import sys import os from rich import print from rich.panel import Panel from rich.console import Console from tweepy import API from tweepy import Cursor from tweepy import OAuthHandler from tweepy import Stream from tweepy.streaming import StreamListener """ Stream Twitter threads using Tweepy in Console. Installation: It requires two python packages, install them using `pip install tweepy rich --user` Usage: python tw_thread.py By default it tries to read tokens from Environment, you can supply them in script by assigning values to CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET. Or set them in environment variable with the following names CONSUMER_KEY => TW_KEY CONSUMER_SECRET => TW_SKEY ACCESS_TOKEN => TW_TOK ACCESS_TOKEN_SECRET => TW_STOK Access Tokens can be generated from here, https://developer.twitter.com/en/docs/basics/authentication/guides/access-tokens.html """ CONSUMER_KEY = os.environ.get("TW_KEY") CONSUMER_SECRET = os.environ.get("TW_SKEY") ACCESS_TOKEN = os.environ.get("TW_TOK") ACCESS_TOKEN_SECRET = os.environ.get("TW_STOK") auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) console = Console() history = [] heading_template = """[bold bright_white]{}[/] ([grey50]@{}[/]) ยท [yellow]{}[/]""" tweet_template = ( """{}\n\n[light_sky_blue3]https://twitter.com/{}/status/{}[/light_sky_blue3]""" ) def print_heading(tweet): timestamp = tweet.created_at.strftime("%A, %d. %B %Y %I:%M%p") username = tweet.author.screen_name name = tweet.author.name console.rule(heading_template.format(name, username, timestamp), align="left") def pretty_tweet(tweet): if not tweet.id in history: history.append(tweet) username = tweet.author.screen_name tweet_id = tweet.id_str content = tweet.full_text hashtags = re.findall(r"(#\w*[0-9a-zA-Z]+\w*[0-9a-zA-Z])", content) for tag in hashtags: highlight = "[yellow]{}[/yellow]".format(tag) content = content.replace(tag, highlight) console.print(Panel(tweet_template.format(content, username, tweet_id))) class Listener(StreamListener): def __init__(self, conversation_id): self.conversation_id = conversation_id super(Listener, self).__init__() def on_status(self, status): if status.in_reply_to_status_id_str == self.conversation_id: pretty_tweet(status) def on_error(self, status_code): print(status_code) return False conversation_id = sys.argv[1].split("/").pop().split("?")[0] source = api.get_status(id=conversation_id, tweet_mode="extended") if source.in_reply_to_status_id_str: print("Getting first tweet") conversation_id = source.in_reply_to_status_id_str source = api.get_status(id=conversation_id, tweet_mode="extended") source_name = source.author.screen_name source_id = source.author.id_str print_heading(source) replies = Cursor( api.search, q="from:{} conversation_id:{}".format(source_name, conversation_id), tweet_mode="extended", timeout=999999, ).items(1000) conversations = [] for reply in replies: conversations.append(reply) conversations.append(source) for tweet in reversed(conversations): pretty_tweet(tweet) listener = Listener(conversation_id=conversation_id) stream = Stream(auth=api.auth, listener=listener, tweet_mode="extended") try: stream.filter(follow=[source_id]) except KeyboardInterrupt: print("Bye.") finally: stream.disconnect()