Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Use Twitter's API and a Few Command Line Tools to Pick a Random Reply

use-twitters-api-and-a-few-command-line-tools-to-pick-a-random-reply.jpg

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:

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

Timestamps

  • 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

Code

Here’s the steps on how to get this set up locally:

  1. pip3 install --user twarc

  2. sudo apt-get install jq (jq is available with brew and other package managers too)

  3. Create your Twitter API keys at https://apps.twitter.com

  4. Create an .env file 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.

Reference Links

Are you going to use this to pick winners for a contest? Let us know below.

Never Miss a Tip, Trick or Tutorial

Like you, I'm super protective of my inbox, so don't worry about getting spammed. You can expect a few emails per year (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments