DEV Community

loading...
Cover image for So you want to make a Twitter bot (1/3)

So you want to make a Twitter bot (1/3)

walaura profile image Laura buns ・Updated on ・6 min read

One of my hobbies is creating twitter bots, you might be familiar with @fakefantas for example? if you aren't that's okay that's not the point. The point is that sometimes people ask me how to do these, and I love talking about this because on paper there's a lot of complexity involved but when you break it down into parts it's pretty manageable!

(Most of my bots just tweet random stuff on a timer, this means they don't listen to replies or know what they posted before. This helps a lot with complexity but hopefully by the end of this series you'll be able to work out how to add this)

Bots are a cool 'problem' to solve because they sound daunting at first, it's a lot to take in! However when you break the problem into smaller problems now you got a lot to take in but also you gotta take it in 3 times. PROGRESS.

When it comes to bots, you have a part that's creating the content. This part takes thin air and produces content. This is hard because you gotta be funny but also sometimes you'll want images or even video, and we gotta automate THAT somehow I normally use I normally use puppeteer.

  • You then have a second part that takes your content and turns it into a tweet that shows up on twitter.com. This is hard because backend development and API keys are b🔥ll👎sh🙅‍♀️t but thankfully what we are doing is a pretty textbook example.
  • There's a third part where we deploy this to somebody else's computer and have it run automatically, instead of us doing the work I use Heroku. for this but something like Glitch can work out fine too!

On this first tutorial I wanna focus on the second part. (bc i can't count) We are gonna create our app on Glitchand by the end of this we are gonna be able to type npm run tweet and see the thing pop on our screenies.

A thing! We are using Glitch to avoid setting up Node locally, but it effectively hosts and deploys our code so it can do a lot of the third step for us. I personally use GitHub+Heroku because they give me more robust tools around collaboration and scheduling.

Tweeting something

Let's start with the basics, let's make a JS function that gives us the day of the week, we are gonna ignore timezones because thats not the point today and not make it any more complicated than it has to be.

/*tweet.js*/
const weekdays = [
  "Sunday", /*america wtf*/
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday"
];

const tweet = function () {
  return `Wooo todays a ${weekdays[new Date().getDay()]}`;
};

console.log(tweet());

if you run node ./tweet.js (and it's a Saturday) you'll now get Wooo todays a 6. Once you're happy, one final thing is that console logging rules for debugging while we make a file but when we are done this will have to be part of a larger system, so let's export tweet instead! We'll import it later. Feel free to make any changes, all we really care about here is that calling tweet() gives us a text under 280 characters.

- console.log(tweet());
+ module.exports = tweet;

leave that to sit in your kitchen counter (or wherever you code) and let's focus our attention on becoming a Twitter developer:

Making a Twitter app

We will wanna create an 'app' in dev.twitter.com If you click around you will see that Twitter has really lost its cool over time about this. Now luckily our use case is still covered.

The developer console is always changing over time as Twitter becomes less of a quirky website and more and more of a soul crushing direct competitor to NBCUniversal but the core concept is.

Screenshot of the twitter developer site showing a roadblock

  • You need an 'access token' (and secret). These tell twitter what user is posting to it (instead of a username/password combo)
  • To get the access token you need to make an app that will have a 'consumer key' (and secret). This tells twitter what 'app' is posting to it (instead of a users browser). Four keys total. All good things come in pairs.
  • To obtain your consumer key/secret you wanna create a 'twitter app'. As of the time of writing, after creating an app twitter will conveniently give you the access token/keys for your current account which is hella nice

Find that 'create app button', click through and fill out the form. Do whatever song and dance Twitter requires you to do and by the end you should be able to find a page with your tokens:

Screenshot of the page with the tokens. In this case they are on the app settings under the 'keys and tokens' section.

Important These tokens are like your password and grant anybody with all four of them access to your Twitter account. Treat them carefully!!

Let's go back to coding

If you had a bit of a wander around the twitter developers site you'll see there's hella detailed documentation for how to post to twitter and make authenticated requests and a bunch of other stuff. Now, something I love about using node (and that my ex that was more into reinventing wheels than into driving hated) is that somebody else has already done our job for us.

Have a read through the page for the twitter package and you'll see that we already got authentication (our 4 tokens!) covered all the way at the top and tweeting a bit below, will it work? let's npm i twitter and find out!

/*index.js*/
const Twitter = require('twitter');

const client = new Twitter({
  consumer_key: "314gvas...12kjbh31n2",
  consumer_secret: "bd129u...21hjbv3",
  access_token_key: "89xzcyh...ads",
  access_token_secret: "98217...gyve98"
});

client.post("statuses/update", { status: "bananas lol" }, function(
  error,
  tweet,
  response
) {
  if (error) throw error;
  console.log("yay!");
  console.log(response);
});

We aren't using our tweet() function yet because it's always good to test parts in isolation first. Imagine this didn't work. is the problem here or in tweet.js? Nobody knows, it's chaos. Making things as small as possible helps you find bugs faster.

Having that said, in this case we will hopefully get lucky and this is gonna work out of the box! Try running node index.js

'Bananas lol' posted on Twitter

This got 2 likes before i deleted it i shit you not. Okay, time for a trial by fire! let's plug in our tweet() function

/*don't forget to import this at the top!!*/
const tweet = require("./tweet.js");

/*and keep the authentication stuff in the middle the same*/
client.post("statuses/update", { status: tweet() }, function(
  error,
  tweet,
  response
) {
  if (error) throw error;
  console.log("yay!");
  console.log(response);
});

'Woooo its a Saturday posted on Twitter

(Goes without saying, you will wanna use your bot account, not your own account) but the larger point is we did it!!!!!
In part 2 we will be moving this from our computer to Heroku and setting it up so it tweets every hour or whatever. In the meantime, why not come up with a funnier tweet() function?

Lost? here's what we've got so far on glitch. You'll notice that instead of using the tokens straight up I'm using this thing called process.env. As I said before you don't wanna reveal your tokens! Not even in code!!

We'll go into detail about this in part 2 too but for now either don't let your code leave your computer or use something like dotenv.

Discussion

pic
Editor guide
Collapse
healeycodes profile image
Andrew Healey

This is wonderfully written and it's very cool to learn more about someone else's process from idea -> bot -> deployment.

I actually checked out the fakefantas GitHub issues during Hacktoberfest :)

Collapse
walaura profile image