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.
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 >>
No comments:
Post a Comment