Wednesday, 15 July 2020

Build Your Own Twitter Bot - Deployment with AWS CloudFormation

<< Reading Images from S3                               Table of Contents                                    Scheduling with CloudWatch >>

In this post, I will show you how to use AWS CloudFormation templates for deploying our functions to AWS Lambda.

Open the serverless.template and add the following:




The serverless.template is used by AWS CloudFormation for orchestrating multiple AWS services. In our case, we want to deploy two AWS Lambda functions called OccultTwitterBotTweetFunction and OccultTwitterBotRetweetFunction.

FunctionName: The name of our AWS Function to be displayed in AWS
Handler: The function in our code that will be executed
Runtime: The function will be executed by the dotnetcore3.1 runtime
Role: The execution role that the function will use.
Policies: The permissions we want to give to our function. 

To deploy our functions, right click the project that contains the serverless.template, OccultTwitterBot, and click "Publish To AWS Lambda..."


Give a name to the Stack. The stack is what governs all your services defined in the template.
It gives you the ability to create, update and delete the stack.

Create an S3 Bucket for deployment. This is where your lambda binaries will be placed during the deployment.


<< Reading Images from S3                               Table of Contents                                    Scheduling with CloudWatch >>





Building Your Own Twitter Bot - Scheduling with AWS CloudWatch Events


<< Deployment                                                Table of Contents

In this post, we will be using AWS CloudWatch to set up an event that will trigger our AWS Lambda function at regular intervals.

There are a couple of ways to achieve this outcome. We can either create the event first in CloudWatch and link to the Lambda function or we can create it directly via AWS Lambda.

Let's go with the second option.

Open the AWS Lamba function, under Designer we want to see the following setup. Notice the CloudWatch Event trigger.

To add this trigger, click on "Add trigger"


Select EventBridge(CloudWatch Events)



You will now see a Rule dropdown box. Select "Create a new rule"


We want an event to trigger an AWS Lambda function once a day.

Set the Rule name to "RunOnceADay".

Select "Schedule expression" as Rule type.
Set the Schedule expression to "rate(1 day)".
The Schedule expression can support cron or rate expressions.

Click on "Add"

That's it! As long as the Event is enabled on the Lambda function, it will be triggered each and every day.

<< Deployment                                                Table of Contents





Build Your Own Twitter Bot - Reading Images from S3


<< Selecting a Tweet                                            Table of Contents                                                     Deployment >>

In this post, I will show you how to read an image from an S3 bucket so that we can attach it to our Tweet.

In S3, create a new bucket called dynamodb-occulttwitterbot-imagestore

In our TwitterBotService project, create a class called S3ImageService and add the following method:



We use the TransferUtility class to open a Stream to the image located in our bucket. We then read this Stream into a MemoryStream instance.

We use the MemoryStream so that we can handle the file in memory, there is no need to save it as a physical file. We simply want to read the file from S3 and upload it straight to Twitter.


We will use the Tweetinvi library for uploading an image to Twitter. We will use Upload.UploadBinary which accepts a byte array. This allows us to use MemoryStream.ToArray() to return us the full byte array of the whole image.

In our OccultTwitterBot project, we use the S3ImageService to get our image stream:



The ImageKey is an attribute in our DynamoDb table which holds the name of the image.

<< Selecting a Tweet                                            Table of Contents                                                     Deployment >>

Build Your Own Twitter Bot - Semi-Randomly Selecting a Tweet

<< DynamoDb                                            Table of Contents                                        Reading Images from S3 >>

In this post, we will semi-randomly select a tweet based on probability, giving a weight to tweets that have been tweeted less frequently.

The tweets have been fetched from a DynamoDb table which have an attribute called TweetCount. We will be using this for our algorithm.

In our TwitterBotService project, create an interface called ITweetSelector and add the following method:



Create a concrete class called TweetSelector and implement ITweetSelector




If all TweetCounts are equal then we calculate a single tweet's probability with:

TweetProbability = (TweetCount / TweetCountTotal) * 100

However, if we have multiple TweetCounts we then we want to give the highest probability to the lowest TweetCount:

To do this, for each Tweet we:

NewTweetCountTotal += TweetCountTotal - TweetCount

This represents our new total where the Tweet with the lowest TweetCount has the highest ratio of the total.

We then calculate a single tweet's probability with:

TweetProbability = ((TweetCountTotal - TweetCount) / NewTweetCountTotal) * 100

This formula gives the Tweets with the lowest TweetCount, the highest probability of being selected.

We then select a random number between 1 and 100.

We share the Tweets with their corresponding probability ratios that's shared within that 1 to 100% range.

The number that falls within the range of a tweets share of the 1 to 100% range will be the tweet selected.

For example:

We have three Tweets and the number of times they have been tweeted:

Tweet   TweetCount
A           5
B           16
C           24

TweetCountTotal = 45

First, let's calculate the new total:

NewTweetCountTotal += TweetCountTotal - TweetCount

A = 45 - 5 = 40
B = 45 - 16 = 29
C = 45 - 24 = 21

NewTweetCountTotal = 90

Using the formula:

TweetProbability = ((TweetCountTotal - TweetCount) / NewTweetCountTotal) * 100
A probability = ((45 - 5) / 90) * 100 = 44.44%
B probability = ((45 - 16) / 90) * 100 = 32.22%
C probability = ((45 - 24) / 90) * 100 = 23.33%

We can see that Tweet A, which only had 5 previous tweets, now has the highest probability of being selected with a 44.44% chance.

<< DynamoDb                                            Table of Contents                                        Reading Images from S3 >>


Build Your Own Twitter Bot - DynamoDb Table and Repository Class

<< Sending Tweets                                       Table of Contents                                                           Selecting a Tweet >>

In this post, I will create a DynamoDb table and a repository class that allows to read and update items.

DynamoDb Table


Create a new table in AWS DynamoDb called OccultTwitterBotTable
Create a Partition key called TweetId. This will be a unique number that increment for each Tweet item.

The other attributes are:

Message - The text contained within the tweet inclusind hashtags
TweetCount - The number of times the tweet has been tweeted (frequency)
ImageKey - The filename of the image to be attached to the tweet.





TwitterBotService.DAL


Open TwitterBotService.DAL project and add a class called TweetRepository. This will enscapsulate the ability for reading data from our table.



In this class we have the following methods:

GetItem - for fetching a single item giving an identifier.
GetAllItems - Get all items from the table using a scan
UpdateItem - Update attributes for an item
WaitUntilReady - Wait until the table is active

UpdateItem is capable of updating any attribute on an item that is set in the parameter updatedAttributes. After invoking the UpdateItem command, it will call WaitUntilReady() which will stop the code from progressing until the table becomes active again.

<< Sending Tweets                                       Table of Contents                                                           Selecting a Tweet >>


Build Your Own Twitter Bot - Sending Tweets

<< Retweeting                                                        Table of Contents                                                           DynamoDb >>

In this post, we will be creating an AWSLambda function for sending tweets by semi-randomly selecting tweets from a DyamoDb table.

This function will be scheuled to execute once a day.

Interface

In our TwitterBotService solution and project, open the ITwitterBot interface and add the following method:



SendTweet

Add the implementation for TwitterBot.SendTweet for sending tweets with a possible image.



If an image MemoryStream exists then we will attach the it to the tweet using PublishTweetOptionalParameters. Otherwise, we just send the message of the tweet.


TweetFunction

Now that we have our TwitterBot API ready for retweeting, let's set up our AWSLambda Tweet function.

1.Open OccultTwitterBot solution and project and add a new class called TweetFunction (or just rename the default Function class).

This class and FunctionHandler is what will be invoked when we trigger our Tweet AWSLambda event.


2. Add the following code:



We create an instance of our TwitterBot class and authenticate passing in our twitter account credentials.

We create an instance of our TwiiterRepository class passing in our table name, access key and secret key. The keys can be obtained by setting up an IAM (it's good practice to set up service specific IAMs e.g. DynamoDb IAM) with programmatic access which has full access rights to DynamoDb (AmazonDynamoDbFullAccess)

We call repository.GetAllItems to get all the tweets from our DynamoDb. A scan is used to do this, which is fine for a table with a small number of items.

We use TweetSelector.GetNextTweetId to semi-randomly select our next tweet. It works by calculating the probability of a tweet being selected by giving a weight to tweets that have been tweeted less frequently.

An interesting feature of DynamoDb is that it is schema-less, this means that not all items need to have the same attributes. In our case, some tweets in the table don't use the ImageKey attribute. If it's used then an image will be attached to a tweet by reading it from an S3 bucket. If it doesn't exist then we send a simple tweet which contains text only.

Finally, we send the tweet and update our DynamoDb by incrementing the tweet count.

<< Retweeting                                                        Table of Contents                                                           DynamoDb >>


Build Your Own Twitter Bot - Retweeting

<< Project Setup                                                Table of Contents                                                        Sending Tweets >>

In this post, we will be creating an AWS Lambda function for retweeting a number of tweets based on specific hashtags. This function will be scheuled to execute once an hour.

Before we get started, you need to setup a Twitter Developer account.

You will need to:
1. Create a Twitter Account
2. Apply for a Developer account: https://developer.twitter.com/en/apply-for-access
3.  Generate an API Key & Secret and an Access Token & Secret for your account.
4. App permissions are set to read and write.


To be able to retweet, our TwitterBot library will have to be able to:

  • Authenticate
  • Search for tweets based on hashtags
  • Retweet those tweets


Interface

In our TwitterBotService solution and project, create an Interface called ITwitterBot:




Authenticate

The Authenticate method will accept the API Key & Secret and Access Token & Secret, which you setup for your Twitter Developer account, as parameters and will return the authenticated user instance.

Create a TwitterBot concrete class that implements ITwitterBot



This method uses Tweetinvi (Twitter API wrapper) to authenticate and to return the our Twitter accounts user.


SearchTweets

Add the implementation for TwitterBot.SearchTweets for searching tweets with a certain hashtag:



The classes we use for searching for tweets belong to Tweetinvi:

  • SearchTweetsParameters
  • Search
  • ExceptionHandler


We use SearchTweetParameters to specify that we want the 10 most recent english tweets based on the hashtags set in the searchQuery parameter string.

Search.SearchTweets will search for the tweets based on these parameters and will return the tweets as IEnumerable<ITweet>

If we receive a null, then there will be an exception and that can be retrieved by calling ExceptionHandler.GetLastException()

Finally, we only want to return tweets that do not belong my twitter account, that aren't retweets, and
were tweeted in the last hour.


RetweetFavouriteAndFollow

Add the implementation for TwitterBot.RetweetFavouriteAndFollow for retweeting, favouriting and following the users of tweets.



In this method we simply loop through IEnumerable<ITweet> tweets retweeting and favouriting the tweets. We then select the distinct users of the tweets, so we only follow tweeters once.



RetweetFunction

Now that we have our TwitterBot API ready for retweeting, let's set up our AWSLambda Retweet function.

1.Open OccultTwitterBot solution and project and add a new class called RetweetFunction (or just rename the default Function class).

This class and FunctionHandler is what will be invoked when we trigger our Retweet AWSLambda event.

2. Add the following code:


We create an instance of our TwitterBot class and authenticate passing in our twitter account credentials.

We call twitterBot.SearchTweets and pass in the hashtags that we want to retweet.

If we have tweets to tweet, we then retweet the, and log useful information to AWS CloudWatch log using LambdaLogger.

In a later post, I will show you how to deploy our function using AWS CloudFormation and setting up a CloudWatch event.

In the next post, we will set up an AWS Lambda function for sending tweets.

<< Project Setup                                                Table of Contents                                                        Sending Tweets >>

Build Your Own Twitter Bot - Introduction






This blog series will show you how to create your own Twitter Bot.





Table Of Contents

Project Goal


Our Twitter Bot project will consist of the following features:
  • Automatic tweeting based on smart selection of pre-made tweets
  • Automatic retweeting, favouriting and following users
  • Automatic unfollowing users


We will use the following technologies:
  • Twitter API (TweetinviAPI)
  • C# .Net Core
  • AWS Services:
  • AWS Lambda
  • DynamoDb
  • AWS CloudFormation
  • CloudWatch Events


Build Your Own Twitter Bot - Project Setup

<< Introduction                                           Table of Contents                                                                    Retweeting >>

Prerequisites


Before we begin building our Twitter Bot, you need to have the following:

We will be creating the following solutions and project structures:
  • OccultTwitterBot
    • OccultTwitterBot
    • OccultTwitterBot.Console






  • TwitterBotService
    • TwitterBotService
    • TwitterBotService.DAL



OccultTwitterBot Project

1. In Visual Studio, create a new AWS Serverless Application project:



We will call our project 'OccultTwitterBot'

This project will contain the logic for our AWS Lambda functions (Tweet, Retweet and Unfollow)

2. Select Empty Serverless Application:



3. Click Finish.

You will now see an empty project containing the following items:

Function.cs - The FunctionHandler in this class is what will be triggered by our Cloudwatch event.

serverless.template - This is our AWS CloudFormation template which is responsible for defining the resources we will require, so that AWS will know what to provision. We will be using this for defining our three Lambda functions.

4. Ensure you have the following Nuget packages installed:





TwitterBotService Class Library

(I recommend creating this in a separate solution) Create a new .Net Core class library project called 'TwitterBotService'. This will act as our TweetInviAPI wrapper which will cater for our specific TwitterBot needs.

Install the following Nuget packages:




TwitterBotService.DAL Class Library

Create a new .Net Core class library project called 'TwitterBotService.DAL'. This will be our Data Access Layer for querying and updating Tweets to our DynamoDb table.

Install the following Nuget packages:




Finally, add the TwitterBotService and TwitterBotService.DAL references to the OccultTwitterBot project.




We should now have the skeleton project structure ready. Now let's move onto the fun stuff!

<< Introduction                                           Table of Contents                                                                    Retweeting >>