Use Twitter's API and a Few Command Line Tools to Pick a Random Reply
In this video we'll pipe together twarc, jq, sed, sort and head to pick a random reply from a tweet. This could be useful for contests.
Quick Jump: Going Over Everything
I recently found myself wanting to run a contest on Twitter where I would pick a random person who replied to a tweet so they could get a free NGINX T-shirt.
I was on a time crunch for this because I was involved with an NGINX virtual conference, so I spent about 20 minutes one morning slapping together a few command line tools to help automate and fairly pick a winner.
Going Over Everything
- 0:11 – You could use this strategy for picking winners in a contest
- 1:25 – Using twarc (a Python library) to interface with Twitter’s API
- 2:12 – Creating a Twitter app and getting your API keys
- 12:21 – Installing twarc, fixing the access keys and installing jq
- 15:21 – Using jq to parse out Twitter handles from the JSON API response
- 16:36 – Using sed to delete myself from the list of handles
- 17:33 – Using sort to get a unique random list of handles
- 19:10 – Using head to grab the first result
- 19:33 – Making it even more random by running it a random amount of times
- 20:56 – Setting the LANG (locale) to English to control how things are sorted
- 22:25 – The command line is so nice for solving specific problems you might have
Here’s the steps on how to get this set up locally:
pip3 install --user twarc
sudo apt-get install jq(
jqis available with
brewand other package managers too)
- Create your Twitter API keys at https://apps.twitter.com
.envfile using the snippet below and paste in your keys:
export ACCESS_TOKEN= export ACCESS_TOKEN_SECRET= export CONSUMER_KEY= export CONSUMER_SECRET=
Pick out a random Twitter handle from a list of replies to a specific tweet:
# Get accesss to your Twitter API credentials. source .env twarc replies 1306247342140645376 \ | jq -r ".user.screen_name" \ | sed "/^nickjanetakis$/d" \ | LANG=en_US.UTF-8 sort -uR \ | head -n 1
It would be expected that you replace
1306247342140645376 with your tweet’s ID and to replace
nickjanetakis with your Twitter handle or any handle you want to ignore.
- NGINX Sprint 2020 Playlist
- Tech Field Day Coverage Playlist
Are you going to use this to pick winners for a contest? Let us know below.