Build a Twitter bot with arc.codes ⚡️
Published: 2021-03-09 13:13:54

## Introduction

In this tutorial, we're going to create a Twitter bot using arc.codes `@scheduled` functions feature that will tweet the daily price of [Blockstacks($STX)](https://twitter.com/Stacks). 

Stacks is a new cryptocurrency integrated with Bitcoin's security, capital, and network, enabling you to build apps, smart contracts, and digital assets.

### Prerequisites

- You must have an approved Twitter developer account.
- AWS account.

> You can clone the code for this project here: https://github.com/ShawnHosea/stacksbot

## Step 1: Create a Twitter app

First, let's set up our Twitter developer account to create an app and gain access to our API keys. 

![Screen Shot 2021-03-04 at 4.56.39 AM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ix6h8gupqv59nzn4634.png)

Follow these instructions to create an app:

- Navigate to https://developer.twitter.com/en and click `Developer Portal`
- Create and name your app.
- Scroll to `App permissions` and change to `Read and Write`.
- Navigate to the `Keys and tokens` tab and regenerate all of your API keys. Make sure to save them somewhere safe.
 
## Step 2: Create an Architect app & add environment variables

Now it's time to create our Architect project. We're going to follow the [Quickstart found on arc.codes](https://arc.codes/docs/en/guides/get-started/quickstart).

```bash
mkdir twitterApp
cd twitterApp
arc init
```

Next, create a `preferences.arc` file holding the following keys:

 - TWITTER_API_KEY
 - TWITTER_API_SECRET
 - TWITTER_ACCESS_TOKEN
 - TWITTER_ACCESS_TOKEN_SECRET

You can sync these API keys by using the [arc env CLI command](https://arc.codes/docs/en/reference/prefs.arc/env)

Here is an example of how your `preferences.arc` file should look:

```bash
# The @env pragma is synced (and overwritten) by running arc env
@env
testing
  TWITTER_ACCESS_TOKEN something-for-testing
  TWITTER_ACCESS_TOKEN_SECRET something-for-testing
  TWITTER_API_KEY something-for-testing
  TWITTER_API_SECRET something-for-testing

staging
  TWITTER_ACCESS_TOKEN something-for-staging
  TWITTER_ACCESS_TOKEN_SECRET something-for-staging
  TWITTER_API_KEY something-for-staging
  TWITTER_API_SECRET something-for-staging

production
  TWITTER_ACCESS_TOKEN something-for-production
  TWITTER_ACCESS_TOKEN_SECRET something-for-production
  TWITTER_API_KEY something-for-production
  TWITTER_API_SECRET something-for-production
```

## Step 3: Create a Scheduled function

Start by adding a Scheduled function to your `app.arc` files `@scheduled` pragma. 

```arc
@app
init

@static
folder public

@events

@http
get /

# Scheduled function for once a day.
@scheduled
daily rate(1 day)

# @aws
# profile default
# region us-west-1
```

- We're going to be using the [twitter-api-client](https://github.com/FeedHive/twitter-api-client) to interact with the Twitter API more seamlessly. 
- We'll use [tiny-json-http](https://www.npmjs.com/package/tiny-json-http) to fetch the data from [Coincap.com](https://coincap.io/) to use for our daily scheduled tweet.
- `cd` into `src/scheduled/daily` to install these two dependencies above so that we may use them inside of the function.
- Place this code into `src/scheduled/daily`

```js
const tiny = require('tiny-json-http')
const { TwitterClient } = require('twitter-api-client')


exports.handler = async function scheduled (event) {

  const twitterClient = new TwitterClient({
    apiKey: process.env.TWITTER_API_KEY,
    apiSecret: process.env.TWITTER_API_SECRET,
    accessToken: process.env.TWITTER_ACCESS_TOKEN,
    accessTokenSecret: process.env.TWITTER_ACCESS_TOKEN_SECRET
  })

  let url = `https://api.coincap.io/v2/assets/blockstack`
 

  const status = await tiny.get({url})
  .then(response => {
    let stx = response.body.data
    let tweet
    if (stx) {
      //tweet the $STX price
      tweet = 'Daily $STX price: ' + "\n" + "\n" + '$' + stx.priceUsd
    } 
    return tweet
  }).catch(err => {
    console.error(err)
  })

  console.log('Log2:', status)

  await twitterClient.tweets.statusesUpdate({
    status: status
  }).then(response => {
    console.log("Tweeted!", response)
  }).catch(err => {
    console.error(err)
  })
	
  console.log(JSON.stringify(event, null, 2))
  
  return 
}
```

- First, we authenticate our Twitter account using our API keys loaded through the `twitter-api-client`. 
- Then, we use `tiny-json-http` to pull in the $STX data from Coincap.io
- After our account is authenticated and data loaded, we create a tweet using the [`twitter-api-client`](https://github.com/FeedHive/twitter-api-client/blob/master/REFERENCES.md#twitterclienttweetsstatusesupdateparameters) to tweet out a status update.

You can test this code to ensure that your function is working by placing this exact code in the `get /` of your app. When you navigate to this endpoint, it will trigger a status update to your Twitter feed.

![Screen Shot 2021-03-09 at 8.01.44 AM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uucyu07z8fjlw7o61sxy.png)

## Conclusion

[Architect](arc.codes) and [Begin](Begin.com) are great tools for interfacing with the Twitter API. I encourage you to explore both arc.codes and the Twitter API to see what kinds of bots you can come up with!