Create a simple, free, text-driven Twitterbot with AWS Lambda & Node.js
Have you always wanted to make your very own Twitterbot, but didn’t want to run a server to do so? Using AWS Lambda and very little code, you too can run a text-driven Twitterbot that tweets at scheduled intervals!
AWS Lambda is a service from Amazon that runs little stand-alone functions on demand or as scheduled. You upload your function, tell Amazon how many seconds to allow it to run and how much computing power it needs, and you only pay when it runs!
Even better, the Lambda free tier includes 1M free requests per month and 400,000 GB-seconds of compute time per month, and those free limits currently don’t expire after your year of free tier is up. (More details, including what the heck a “GB-second” is, here.) Your bot would have to tweet twenty times a minute to hit those limits! (NOTE: Please do not make a bot that tweets twenty times a minute. That is bad.)
Creating a bot using Lambda is pretty easy if you’re comfortable with Node.js (or enjoy reading instructions). The easiest way to get going is with this repo, which has an empty bot skeleton for you to fill in with your own information. Clone it and then run ‘npm install’.
Setup: Twitter
First, you’ll need to create a Twitter account for your bot, and confirm the email address you used to set it up. Then go to apps.twitter.com and sign in with your new Twitter account to create a Twitter app. Give your app a name, a description, and put a URL in the website field (it doesn’t really matter what URL, but linking to your own site is nice). You don’t need to enter anything in the “Callback URL” field. Scroll down to agree to the developer terms and submit the form.
Note: You may see an error message after you submit the application telling you that you need to add a phone number to your bot account. If you have already connected another Twitter account to your phone number, disconnect it from that account, and connect it to the bot account. (You can swap your phone number back after you create your keys.)
After you’ve created your application, click on the application name and choose the Keys and Access Tokens tab. Then click the Create my Access Token button. Twitter will generate the keys and tokens that you will need. You’ll need these four pieces of information for your bot to work: your Consumer Key, your Consumer Secret, your Access Token, and your Access Token Secret.
In the repo there’s a file in the botfiles directory called ‘temp-config.js’. Enter your keys there and rename the file to ‘config.js’. (<= If you don’t rename this file your bot will not work and you may accidentally commit your keys to your own repo, always a bad idea!)
Setup: AWS
If you don’t already have an AWS account, you can sign up for one here.
Once you have your account, create a new AWS user just for this bot — it’s safer. Create your new user through the IAM console; AWS has detailed directions here. Name it something you’ll immediately identify with your Twitterbot—using the bot’s handle is good. Make sure you save the Access Key ID and the Secret Access Key of your new user, and also note your account ID (your account ID is a 12-digit number, such as 123456789012). If you can’t find it, AWS has an explanation here.
Once your new user is created, you need to attach the AWSLambdaFullAccess policy to your user to allow it to interact with AWS Lambda.
It’s possible to include your AWS Access Key ID and Secret Access Token in your bot’s lambda configuration file, but it’s safer to put it in a named AWS profile locally, and just use the profile name. To create a named profile, install the AWS command-line tool and configure it like so:
aws configure --profile YOURPROFILENAME
Then just follow the prompts to add your Access Key ID and your Secret Access Key, and your default region. Since Lambda is only available in us-east-1 and us-west-2 right now, make sure you use one of those regions when you create your profile. (You don’t need to specify a default output format.)
Once you have your user and user profile set up, enter the user profile in the temp-lambda-config.js file and rename it to lambda-config.js. Here’s the whole profile to set up:
module.exports = {
profile: '',
// load your AWS credentials from a custom profile
region: 'us-west-2',
//the region of your Lambda function
handler: 'index.handler',
//the name of the handler function: index because the main file is index.js
role: 'arn:aws:iam::YOURACCOUNTHERE:role/lambda_basic_execution', // the Lambda role
functionName: '',
//name
timeout: 10,
//how many seconds your function should run before it times out
memorySize: 128,
//how much memory your function needs (shouldn't need more than this)
publish: true,
// this creates a new version of your Lambda function every time you update it
runtime: 'nodejs',
// for node 10, otherwise use 'nodejs4.3'
}
(NOTE: Make sure you have the lamba_basic_execution role set up through AWS IAM before you move on the to next steps! Here’s more info on how to set it up: http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-create-iam-role.html Thanks to Stanislav Slesarev for pointing this out!)
Although you can create and update your Lambda functions through the AWS console, it’s a lot of pointing and clicking and filling out fields. So, instead, this bot uses the very handy node-aws-lambda package to create, update, and deploy right from the command line, using Gulp.
Finally: The Bot Guts
This very very simple bot just pulls a line at random from a file and Tweets it. So you need a file! There’s a sample file in the repo at botfiles/sample-text.js. Add your text to this file, one tweetable item per line.
Next comes the tricky part! The node-aws-lambda package creates a zip file of your code (index.js) and all the dependencies that your code needs to run (node_modules). But our config.js file with our Twitter credentials and the sample text we want the bot to tweet isn’t in index.js and it’s not in node_modules. But using ‘npm install’, we can PUT it in node_modules, and then it will be zipped up and included when the Lambda function is deployed.
To add a local package to your package.json, you need to know the full path of the botfiles folder on your system. (You can find this easily on a Mac from the command line — just enter the directory and type ‘pwd’.) Then use this command:
npm install --save ./YOURPATH/botfiles
You can then check to make sure that it was saved in node_modules. NOTE: if you update the sample text file, you should update the version number in botfiles/package.json and then run
rm -rf node_module/botfiles && npm install /YOURPATH/botfiles
Testing!
The index.js file has three functions, plus the exported Lambda handler function. One picks a line from your file, one checks to make sure it’s short enough to tweet, and one checks that it also doesn’t include offensive words (using Darius Kazemi’s wordfilter package) and isn’t undefined or empty. There are tests for these functions in the test/test.js file, and you can run them with ‘npm test’. (There’s also a gulp task for linting the index.js file — run ‘gulp lint’ to check your code.)
Deploy!
Once your configuration files (config.js and lambda-config.js) include your credentials, and you’ve added text to the text file, you’re ready to deploy! Just type ‘gulp deploy’.
(If you see errors at this point it is almost always because there’s something wrong with your AWS credentials. Double-check that your account number and region are both correct in the lambda-config.js file.)
Test Again!
You can check that your bot is firing correctly and that it’s wired up right to Twitter by going to the AWS Lambda console and submitting a test event. For us-west-2, the console is here. Click on your function name and choose “Configure test event” from the drop-down Actions menu in the upper left.
Because this Lambda function doesn’t rely on any input (other than the sample text file we provided) the test event should be empty:
Hit the “Save and Test” button in the lower corner of this screen. Your function will now run!
You can check the output of your function test on the main function page of the Lambda console. The function doesn’t return a response, so you’ll see ‘null’ in the result window. Check the “Log output” window to see the response from Twitter (and of course, check your Twitter bot’s account).
Schedule!
To make your bot run on a schedule, open up the AWS Lambda console. (You may need to sign in again.) For us-west-2, it’s here. Click on your function name and then choose the “Event Sources” tab. Click on “Add event source.”
Then configure your source to be a “CloudWatch Events — Schedule” source type, give it a name and a description, and choose the rate. (I recommend that your bot should tweet no more than once per hour.) Make sure the “enable event source” box is checked, and submit! (If you don’t want the preformed rate expressions (minute, five minutes, hour, etc.) you can use cron.)
Making Changes!
Redeploying your code is easy. Make your changes locally, then run ‘npm test’ (to make sure nothing broke), ‘gulp lint’ (to catch any syntax issues), and then ‘gulp deploy’. You’ll see the progress in the console, it’ll will look something like this:
[09:35:09] Finished ‘node-mods’ after 5.63 s[09:35:09] Starting ‘zip’…[09:35:10] Finished ‘zip’ after 707 ms[09:35:10] Starting ‘upload’…[09:35:14] Finished ‘upload’ after 4.52 s[09:35:14] Finished ‘deploy’ after 11 s
If you want to change the bot’s schedule, revisit the “Event sources” tab in the Lambda console and delete the Scheduled Event. Then you can create a new one.
Deleting!
If you want to delete the bot entirely, go back to the Lambda dashboard, select your function name, and choose ‘Delete function’ from the Actions drop-down:
If you want to see a bot in the wild running this code, check out As She Is Spoke.