Some Bits: Nelson's log

12 posts about twitter

Another Twitter archive

Since Twitter was destroyed it’s been frustrating losing access to all the stuff I wrote. X still allows you to download an archive of your own tweets, but then there’s the challenge of making the data useful.

For awhile now I’ve been using Julia’s tweet-archive. It works great but I never loved the styling. (I never tried to improve it, either.) You can see my archive in Julia’s thing here.

Matt Haughey just vibe-coded up an alternative. I like the way it looks. It’s also got a couple of extra tricks. The code works with various old formats of Twitter exports. The Javascript has some nice functions like filtering by year. And it displays reply tweets, albeit not linked to what you’re replying to. You can see my archive in Matt’s thing here.

Matt’s code worked out of the box for me but some of the path management and permissions are a little fiddly. Here’s what I did to get it working, from a Twitter archive I pulled just yesterday.

# Download and prepare the files
mkdir /tmp/t; cd /tmp/t
unzip twitter-dump.zip
git clone https://github.com/mathowie/tweet-search-archive

# Clean up the repo a bit and link in the data
cd tweet-search-archive
rm -r tweets_media
ln -s ../data/tweets.js .
ln -s ../data/tweets_media .
sed -i 's/Your Name/Nelson Minar/; s/yourhandle/nelson/' build.py

# Build the archive
python build.py

# Copy the output to a web server and fix permissions
cp -a tweet_search.html ../data/tweets_media ~/public_html/tmp/tweets/
find ~/public_html/tmp/tweets/ -type d -exec chmod 0755 {} + -o -type f -exec chmod 0444 {} +

My own archive of tweets

I put my own Twitter archive online, hosted here with individual tweet URLs like here. The “server” is all static HTML but the list of tweets is an infinite scroll thing. Oct 2006 to Nov 2022.

I made this with Julia Evans setup, itself based on Darius Kazemi’s tool. Darius’ program generates its own HTML view but it’s got an idiosyncratic presentation. Julia’s code takes the tweet data (from searchDocuments.js) and the media files and constructs a new HTML archive borrowed broadly from Nitter’s UI. The Vue-based infinite scrolling wouldn’t be my first choice for an archive but it works fine and only took a half hour to set up. The main thing I miss is thread nesting.

I mostly just followed Julia’s instructions, getting something basically working is very easy. The scripts aren’t a polished product but if you are comfortable hacking a little code it’s not hard to get working. I’m glad she shared them! Some details:

Here are the specific edits to the code to customize my archive:

  • app.js: Replace two instances of b0rk with nelson
  • index.html: Replace four instances of “julia” or her full name with mine. Replace two instances of “b0rk” with “nelson”.
  • build.py: 5 instances of “b0rk” for “nelson”. 4 instances of “julia” for “Nelson”. (this page includes HTML similar to index.html).
  • profile.jpg: replaced with my own image

Deployed by rsyncing the entire github package, Julia’s scripts write stuff in that directory. Then on the web server I deleted things that weren’t necessary for the static HTML: .git, scripts,

The other thing I did was write a script to filter my tweets by date. I decided to cut off the archive at Nov 3 2022, the stuff I posted afterwards is all not something I care to preserve, just bearing witness to Elon Musk’s destruction of the company and product.

#!/usr/bin/python

import json, pytz
from datetime import datetime

cutoff_dt = datetime(2022, 11, 4, tzinfo=pytz.UTC)

def cutoff(item):
	created_at = item["created_at"]
	dt = datetime.strptime(created_at, "%a %b %d %H:%M:%S %z %Y")
	# print(dt, dt >= cutoff_dt, cutoff_dt)
	if dt >= cutoff_dt:
		return True
	else:
		return False

jsonp_header = 'const searchDocuments = '
data = open("searchDocuments.orig").read()
data = data[len(jsonp_header):]

tweets = json.loads(data)

filtered = tuple(t for t in tweets if not cutoff(t))

print(f'{len(tweets)} tweets in archive, {len(filtered)} passed filter')
with open('searchDocuments.js', 'w') as fp:
	fp.write(jsonp_header)
	json.dump(filtered, fp, separators=(',', ':'))

Twitter streaming API workarounds: lists and following

Twitter is shutting off their streaming API. After months of warning, the actual deadline is in three days, Thursday the 16th. If you were using the streaming API to follow at most a few thousand accounts, there’s a workaround: Twitter lists.

The idea is you create a Twitter list containing all the accounts you want to follow. Then you poll lists/statuses for the timeline of tweets. Polling isn’t awesome but the default rate limit is once a second, so it’s not too bad. Twitter lists are limited to 5000 accounts, so if you need more than that this won’t work (but consider multiple lists).

The main thing you’ll lose this way is replies; Twitter lists don’t include replies not to list members. (Or maybe not to people you follow, I’m confused on that point.) But otherwise it seems to work. If you’re working with old Twitter code be sure you understand about extended_tweets; you almost certainly want to be getting them.

One wrinkle: creating a list of thousands of people isn’t easy. It looked to me like there was a hard limit of adding 1000 users to a list every day. Also maybe a soft limit of hundreds in a short period of time.

The other option I tried was instead of a list, create an account and follow the users of interest. Then look at their home timeline. This doesn’t work as well for various reasons. First, Twitter mucks with a home timeline more than a list timeline, more risk of reordering and stuff. Also the rate limit is lower (once a minute). Finally it seems harder to quickly follow thousands of new accounts, I ran into more draconian rate limits.

One more wrinkle: listing or following a user notifies them you are interested in them. Following people via the streaming API was completely passive, now users have a hint they’re being watched. It’s not a big deal but some users may choose to block you when they get listed / followed.

Twitter robot purge

Twitter purged a bunch of robot accounts this week as some sort of effort to clean up their platform. You can see the personal result for you by logging in to https://analytics.twitter.com/, you’ll see the falloff.

My personal account @nelson lost about 5% of followers. My account is pretty ordinary other than it’s old.

I have an account with a much simpler set of followers though: my robot account @somebitslinks. That’s an automated account posting interesting links I place on Pinboard. It’s not social in any way. But it got 10,000 followers all in one day in January 2012 when it was listed for a few hours as a recommended account on Twitter’s home page.

Over the years that account has lost followers, I imagine as people got fed up with all the robot spam in their timelines. It slowly dropped from 10,000 to 9000. This week in the purge it dropped from 8947 to 8087, or just about 10%.

I don’t know what to conclude from that exactly, other than Twitter’s bot finding algorithm apparently identified 10% of users from January 2012 as bots. Makes me wonder what the real number is.

Update: some context in this tweet, showing big accounts losing anywhere from 2% to 78% of followers. Also this NYT summary.

Twitter API, tweepy, and error handling

I’m writing some Twitter API code. A few lessons learned in using the tweepy library.

The error handling is not awesome. All API errors throw tweepy.error.TweepError, which is fine, but that object has no structure. The docs have some stuff about getting codes that seems outdated. In the code there’s an api_code field , but it’s set to None. I’m doing stuff like e.reason.endswith(“401”) to detect the 401 error code Twitter throws for protected users. (This is also the code Twitter throws for an invalid token, so that’s not great.)

The rate limiting handling is pretty good. In particular there’s a wait_on_rate_limit option that is pretty handy for simply waiting for a rate limit to expire.

When paging through user_timeline the default fetch size is only 20 tweets. You can instantly get 10x the effective calls by bumping up to count=200.

Twitter’s rate limits are confusing. Nominally it’s “calls per 15 minutes” but there must be some sort of grace period or something built in because sometimes you get more calls than that. There’s a nice rate_limit_status API call that is very helpful but is sometimes out of date; in particular I’ve seen reset times that are now in the past, so apparently my limit reset (and calls are working) but the status call doesn’t tell me that. Anyway, here’s some Q&D Python code to print out which API calls you’re currently at less than maximum on.

r = twapi.rate_limit_status()
now = time.time()
for resource in r["resources"]:
    for name, status in r["resources"][resource].items():
        if status['remaining'] != status['limit']:
            print ("%4d of %4d left, reset in %ds %s" % (status['remaining'], status['limit'], status['reset'] - now, name))

Wanted: simple persistent apps

What’s an easy way to build a Python app that grabs data from somewhere every few minutes, persists it, and then does some analysis of it?

I’m building a new thing that gets some data from Tweets and stores it. The main loop is downloading new tweets for a group of users and storing details of those tweets. It’s not very complicated. Structurally it’s similar to my lolslackbot project.

And I’m building it the same bad way. Persistence via sqlite with hand-rolled SQL statements. This is tedious, error prone, and makes upgrading / changing things difficult. Testing is also a huge PITA.

Is there some modern alternative that’s better?

My first thought is to at least use some sort of ORM. Django or SQLAlchemy, presumably. I’ve done a little Django and it’s hard to love it. Also ORMs cause problems, although maybe not at the small scale I’m working at.

I’m wondering if there’s some other fancier / funkier persistence system I should consider. I kind of want the simplicity and flexibility that an object database or maybe a NoSQL system promises. But those don’t seem to work out well in practice.

Twitter API: extended tweets

tl;dr: if you’re writing new Twitter API code, be sure you’re requesting extended tweets.

Boy am I out of touch. Twitter did a major API change over a year ago to better support modern tweets that don’t really fit in 140 characters. I stumbled into this while trying to use the API to get the URLs for this tweet. My old code mostly worked but this tweet is long enough to trigger the need for extended tweets. My old code was seeing a URL for the tweet it was in reply to and not the bendbulletin.com URL.

The clue was that the tweet object also had “truncated: true” set on it. What is that? Happily I found this discussion which explained about extended tweets. Twitter also documented this thoroughly last year, it’s explained well in this document.

By default the Twitter API still returns “compatibility tweets” which strictly fit in 140 characters. And in other ways are pretty broken, or at least incomplete. You have to add a tweet_mode=extended to your request URL to get the new extended format. Just to complicate things this new format has some changes, most notably there is no more “text” field. Now it’s called “full_text”. There’s also some funky third format for streaming and Gnip APIs that has both formats in a single message.

I fixed my Tweepy code by adding tweet_mode=’extended’ to the Cursor constructor.

I can’t see any reason any new code shouldn’t immediately switch to using extended tweets forever and always. It’s a shame Twitter didn’t go with a version numbering scheme to change things like this in a neater way, although versions have problems too.

While I’m here, two grumbles about the Twitter API:

Twitter’s own web client no longer is using the JSON API for everything, some stuff is pre-rendered. This means you can’t just use their web app to crib examples of API calls from.

Twitter’s API console for interactive testing of requests is kind of nice. But they don’t format the JSON responses in a useful way! You just get one long-ass line of text you have to paste into a prettifier to make sense of.

Twitter Python clients by release date

I want to write a program using the long-suffering Twitter API. There’s a zillion Python options, here’s what I found. I used the most recent PyPI release date as my primary criteria, because I want something actively maintained.

Of course release age isn’t everything. All four libraries linked above have similar APIs for doing simple things. I believe all four now support the streaming API too. On a quick glance tweepy and python-twitter have the most reassuring test suites.

I picked tweepy to start with because it has the most recent recommendations on /r/python. Also there’s still activity on GitHub, even if no recent releases. So far so good.

Hexbin map of my tweets

Twitter published user archives, hooray! I cargo culted some code together off of Mike’s Walmart map to show a little histogram of where I tweet. Two maps with different projections and different visualization of magnitude (size vs color)

Screen Shot 2012-12-19 at 4.45.34 PM Screen Shot 2012-12-19 at 5.07.15 PM

Some things I learned:

  • Hexbins can be brittle. If I change the scale of the map or the hexes just a bit the qualitative shape of the connected objects changes radically.
  • Scaling and centering a projection to a dataset is a little tricky. d3.geo.projection() has you doing the scaling and translation in screen coordinates by default, need to do it in geo coordinates to make more sense. (Mike says to use the center() method.)
  • D3 projections are fun! The second projection is a kavrayskiy7, whatever the hell that means, borrowed from this example.

tweetchive in IE9

Cross-platform Javascript has gotten a whole lot better in the HTML5 era. I developed all of Tweetchive without testing it at all in anything other than Chrome. It just worked in Firefox and Safari and Mobile Safari. IE9 still takes a bit of work, had to make two changes:

  • Added <!DOCTYPE html>. Other browsers don’t care, but IE9 runs in quirks mode without this and leaves out useful things like the JSON functions.
  • Dropped in Moment.js to parse dates. new Date(“some random localized string”) does a good job of parsing dates in most browsers, but not in IE.
    moment(fullTweet.created_at, “ddd MMM DD HH:mm:ss Z YYYY”).valueOf()

Twitter API headers

I’m dorking around with the Twitter API, public calls like http://api.twitter.com/1/statuses/user_timeline.json?screen_name=nelson&count=100&page=3&include_rts=1&trim_user=true&include_entities=false. Here’s the HTTP headers that returns:

  HTTP/1.1 200 OK
  X-RateLimit-Limit: 150
  X-RateLimit-Remaining: 112
  X-RateLimit-Reset: 1337888547
  X-RateLimit-Class: api
  Content-Type: application/json;charset=utf-8
  Last-Modified: Thu, 24 May 2012 19:26:16 GMT
  Expires: Tue, 31 Mar 1981 05:00:00 GMT
  Pragma: no-cache
  Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
  Set-Cookie: guest_id="v1:133788757695829242";Expires=Sat, 24-May-14 19:26:16 GMT;Path=/;Domain=.twitter.com
  Status: 200 OK
  X-Transaction: a990ed040a2ffcdd
  X-Frame-Options: SAMEORIGIN
  Date: Thu, 24 May 2012 19:26:16 GMT
  Server: tfe
  Content-Length: 86940

Sadly, there’s no Access-Control-Allow-Origin header there to allow CORS. The Twitter API does support an optional callback= paramter to get them to emit JSONP instead. I was trying to use D3’s AJAX library to make the calls, but it only supports CORS and not JSONP.