Daily English App With AWS Serverless Services EventBridge, Lambda, SNS, S3

Daily English App With AWS Serverless Services EventBridge, Lambda, SNS, S3

Introduction

Create an AWS Serverless Application with S3, SNS, Lambda, EventBridge and IAM.

Application Architecture

This diagram shows the services used in this app.

Steps

Step 1: Create a S3 bucket and upload the word-list file

Step 2: Create a SNS topic and add an email subscription

Step 3: Create a Lambda function to get a random word from the word list file in S3 bucket and send the daily word email

import json
import boto3
import random

def send_sns(message, subject):
    try:
        sns = boto3.client('sns') 
        topic_arn = "yourTopARN"
        result = sns.publish(TopicArn=topic_arn, Message=message, Subject=subject)
        if result['ResponseMetadata']['HTTPStatusCode'] == 200:
            print(result)
            print("Notification send successfully!")
            return True
    except Exception as err:
        print("Error occured while publish notifications and error is: ", err)
        return False

def get_random_item(my_list):
    # Check if the list is empty
    if not my_list:
        return None

    # Select a random item from the list
    random_item = random.choice(my_list)
    return random_item

def lambda_handler(event, context):
    try:
        bucket_name = "daily-vocab-bucket-jan"
        s3_vocab_file_name = "WordsList1.csv"

        # read from s3 and get the daily word
        s3 = boto3.client('s3')
        read_from_file = s3.get_object(Bucket=bucket_name, Key=s3_vocab_file_name)
        data = read_from_file["Body"].read().decode('UTF-8')
        word_list = data.split("\n")
        random_word = get_random_item(word_list)
        print("Random word:", random_word)

        # send text message to phone
        message = random_word
        subject = "Daily English Word"
        sns_result = send_sns(message, subject)
        return sns_result
    except Exception as err:
        print (err)

Note: make sure the lambda role has permissions to access S3 and SNS

Step 4: Create an EventBridge schedule to send email daily

Step 5: Check the email (set the schedule to send an email every min to test)