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 >>


Tuesday, 5 May 2020

Build Your Own Blog - Page Layout and Flexbox

<< Creating the BlogArchive Component                                  Table of Contents

In this part of the 'Build Your Own Blog' series, we want our web page to be suitable for various screen sizes, such as mobile and laptop.

(If you're new here, I recommend visiting the Table of Contents or here for the previous post)

Flexbox is a Responsive Web Design CSS technology that allows us to dynamically alter our web page to suit the dimnesions of the screen it is being displayed in.

By the end of this post, our blog site will be capable of supporting the following screen types:

Laptop



Mobile



Notice that the Blog Archive component is being pushed to beneath the Blog Post.


1. Open app.component.sass and add the following:
























The container class is our main container class that belongs to the parent div. It adds a margin to the whole page which is proportionate to the width of the screen. This will centre our web page by bringing its components together rather than being spread out. It's easier on the eyes.

You'll notice that the blog-body class uses display: flex. This will enable Flexbox on this div and all its child items.

justify-content: space-between will spread the components across the full width of it's container whilst adding an even amount of space between them.

flex-direction: row will force our components to appear in a row instead of being in a column.

flex-wrap: wrap is the magick for pushing the BlogArchive component beneath the BlogPost component if it can no longer fit within the width dimensions of the container.


flex will dynamically size the component proportionate to other components. blog-post has flex:3 and blog-archive has flex:1 - this means BlogArchive will be 3x bigger than the BlogPost component.

flex-grow will determine how quickly the component will grow/shrink into the remaining space of the screen as the screen size changes.

2.  Open app.component.html and add the following:



The final piece in the puzzle! We use all three components that we've created in this series and we place them within their own divs and corresponding classes to apply the final layout of the page.

3. Run ng serve
Congratulation! If you've made it this far, you should now have a basic blog web site that is responsive.

In the following posts, we will dive into creating our API layer using .Net Core Web API and AWS DynamoDB for accessing our blog data.


<< Creating the BlogArchive Component                                  Table of Contents

Build Your Own Blog - Create the BlogArchive Component and Angular Material Tree

<< Create the BlogPost Component                           Table of Contents                                Page Layout and Flexbox  >>

In this part of the 'Build Your Own Blog' series, we will create a component for the blog archive. This is responsible for navigating historical blogs. It will look like below:


(If you're new here, I recommend visiting the Table of Contents)

The Archive will have the following features:
  • Expandable tree view of historical blogs.
  • Tree will contain three level of nodes - year, month and blog post.
  • If a node contains a sub-nodes it will include the sub-node count next to the nodes name.
To achieve this, we will be using Angular Materials' Tree component to create the expandable tree layout.

I found my first time using the Tree component difficult. I heavily relied upon the following links to get it working. I recommend you also looking at them, if you have trouble with my description.

A useful video and description by Jameson Saunders on the Angular Material Tree:
https://www.youtube.com/watch?v=BALaj39rbZE&t=301s

A similar description and use of the Angular Material Tree by Vag from media.com:
https://medium.com/@vag/angular-material-tree-26adccadc63b


Let's go!

1. Add a new component called 'blogarchive' by running:

 ng generate component blogarchive

2. Install Angular Material by opening Visual Studio Code's Terminal and running:

ng add @angular/material

This will install Angular Material, the Component Dev Kit and Angular Animations.

3. Open blogarchive.component.ts and add the following:



Notice that we are hardcoding the tree data. We will come back to this in later posts and hook this up to a backend API for querying real blog post data.

FileNode represents a single node in our tree. The name is the label that will appear in the archive tree and children are it's sub-nodes.

NestedTreeControl represents the tree control itself. We pass it a parameter which contains an observable of node.children, this is so that as we navigate the tree, we can dynamically fetch a nodes children.

MatTreeNestedDataSource represents the JSON representation of our tree data. It contains the parent/child hierarchy.

Using rxjs, we create an instance of BehaviorSubject and setup a subscription that updates our data source (nestedDataSource.data) as our data changes (dataChange.next).

hasNestedChild will be used in our html for knowing if a child has any nested children.

getChildrenCount will be used for identifying the number of children a node has.


4. Open blogarchive.component.sass and add the following:

Angular Materials' Tree component has simple styling which isn't suitable for our blog.

The default font-colour is white so we override mat-tree-node and set the colour to red.
The default height of a node is also too large, so we reduce it by setting the height to 20px.
The default background colour of the component is black, so we set it to white by setting archive-tree.background-color 

We also override mat-icon-button.width to reduce the size of the arrow icon.

We also setup classes for the border of our component. We use box-shadow to give our component a soft shadow and border-radius to curve the corners.

5. Open blogarchive.component.hml and apply the following:


Notice the mat-tree element that contains two sub-elements (mat-tree-node and mat-nested-tree-node). The mat-tree dataSource is set to the nestedDataSource instance we setup in the constructor earlier; this contains our tree data. We also set the treeControl to the nestedTreeControl instance.

mat-tree-node represents a node that has no children. The mat-nested-tree-node represents a node that does have children. 

mat-tree-node and mat-nested-tree-node elements are used interchangeably depending on the state of hasNestedChild. 
mat-nested-tree-node
will conditionally set the arrow icon to right or down depending on whether nestedTreeControl.isExpanded or not.


Congratulations! We now have an Archive component for navigating historical blog posts.

<< Create the BlogPost Component                           Table of Contents                                Page Layout and Flexbox  >>

Build Your Own Blog - Create the BlogPost Component

<< Create Your First Component                        Table of Contents                   Create the BlogArchive Component >>  

We will now create a component containing the content of a blog. It will look like below:



(If you're new here, I recommend visiting the Table of Contents)

Each blog post will contain:
  • Date
  • Title
  • Content as HTML capable of supporting images, code snippets and text
  • Posted by and at what time.
  • A border - green-ish with a drop shadow.
Let's get started!

1. Add a new component called 'blogpost' by running:

 ng generate component blogpost

2. Open blogpost.component.sass and add the following classes:








































The blog-post class defines the border of the component. We set the height:auto so that the components height will be defined based on it's content. However, we don't allow it to be smaller than 150px.

word-wrap: break-word
forces the text in the component to move to a new line once it reaches the edge of the components width.

3. Create a new folder called 'types' in src > app > types






















4. Create a TypeScript file called BlogPost and add the following:













This class is responsible for transferring all the data from to the template (DOM). Think of this class as a Data Transfer Object (DTO) or a binding between the TypeScript Controller (blogpost.component.ts) and the View/Template.

5. Open blogpost.component.ts and add the following:



Notice that we create an instance of the BlogPost class, injecting in test data we wish to be displayed in the component. Later, we will modify this class to connect it to our backend API for fetching real blog data.

6. Open blogpost.component.html and add the following html, using the classes we've just defined:



The BlogPost component is now complete.

In my next post, we will create the BlogArchive component.


<< Create Your First Component                        Table of Contents                   Create the BlogArchive Component >>   













Build Your Own Blog - Create Your First Component and Component Driven Design

<< Your First Angular Project                                  Table of Contents                            Create the BlogPost Component >>

In this post we are going to build our first component using Angular. If you haven't already, please read the previous post to set up the prerequisites required.

(If you're new here, I recommend visiting the Table of Contents)

I will show you how to use the Angular CLI (ng command) to add a new component, download and apply a font and apply simple styling to our component and home page.

We will call our header component 'blogheader'. For now, it will contain only the title of the page "kite .net", more will be added later.



When choosing colours for your web page, it is advisable to pick colours form the same scheme. The reason is that we want the colours to compliment each other so that they appear aesthetically pleasing to our user. Read more about this here: colour schemes

Component Driven Design

The idea is that we arrange our website into components. Think of a component as a group of html, css and javascript designed for a specific purpose. In our case, we have Header, Post and Archive components.

These components will be modular that are re-usable and can be initialised multiple times on a website. This will reduce code duplication and complexity. Everything we need for a component is contained only within that component alone.

A component consists of the following parts:
  • Selector - The name of the element to instantiate the component)
  • Template (Html) - The layout of a component. i.e. How the data will be displayed.
  • Style (CSS/SASS) - The styling required for this component
  • TypeScript - The logic behind the initialisation of the component. i.e. Fetching the data required for the template.
Click here to read more about: Component Driven Development

If you're familiar with the Model-View-Controller (MVC) design pattern, it is very similar.

BlogHeader Component

1. Add a new component by running ng generate component blogheader


You will now see the following added to the project.



2. Download this font (zip) from Google Fonts: https://fonts.google.com/specimen/Allerta+Stencil



3. Create a new folder assets > fonts

4. Unzip the font to the fonts folder:

 

3. Open app > styles.sass and add the following:



This will allow us to refer to our font in our css as 'stencil'

4. Open blogheader.component.sass and add the following:









This will define our header class using our 'stencil' font plus other font attributes.

5. Open blogheader.component.html and add the following:




Applying the header class will apply the font, size and colour.


6. Open app.component.sass and add the following class:







The container class will be used for creating a central page layout across all components.

10. Finally, run your application locally using ng serve and see the results.


Well done! We've created our first component using Angular!

<< Your First Angular Project                                  Table of Contents                            Create the BlogPost Component >>