DEV Community

Cover image for AWS Lambda: Send Notifications to your Discord Server using SNS Topics
Said Silva
Said Silva

Posted on • Updated on

AWS Lambda: Send Notifications to your Discord Server using SNS Topics

Introduction

First, I'd like to thank @josuebustos for his article, which gave me the idea to come up with an alternative version.
You can integrate Lambda and SNS to send notifications regarding your resources, this brings a lot of possibilities, and we'll see a basic one. Such notifications will contain information from an SNS Topic in AWS. We'll learn how to send messages to a discord channel using webhooks.

Want to know more about Lambda?
Click here

Want to know more about Discord Webhook?
Click here

Getting Started

This tutorial is focused on being as simple as possible, so you can easily set up your lambda function within minutes and change it accordingly if you are having problems or only want the code here is the link of my repo with everything you'll need.

Prerequisites:

  • AWS Account
  • Discord Server

Create a Discord Server and a Webhook

The first step is to create a server. If you already have one skip until the webhook section.

In your Discord Dashboard.

  1. Click the green button in the lower left corner to create a server.
    Add Server

  2. Select one of the following options. I recommend you choose the 'Create my Own' option.
    Add Server

  3. Select Select one of the following options. I recommend you choose the 'For me and my friends' option.
    Add Server

  4. Customize your server with a name and an image if you want it.
    Add Server

  5. I'll recommend you create a separate channel for the webhook to keep things organized. Click on the create channel button above the channel names.
    Channel

  6. Configure the channel as you like, but keep the Text option.
    Channel

Time to set up the webhook

  1. Click on the 'Gear' option on the name of the channel you want to edit.
    Webhook

  2. Select the Integrations option to access the webhooks menu.
    Then press the Create webhook button
    Webhook

  3. You can configure the name and the icon for your webhook. Select the channel you want your webhook to use.
    Webhook

  4. Copy the webhook URL and save it somewhere because we'll use it in a few sections.
    Webhook

Create an SNS Topic

If you already have an SNS Topic that you want to use to send information to your discord channel, skip this section.

We will create a simple one, and then you can connect this topic to any other resource.

Let's get into the SNS service, selecting Simple Notification Service.

SNS

Select the topic option on the sidebar, and then the Create topic option.

SNS

Use the following options for a simple SNS topic and press on the create topic button

SNS

SNS

Now, it's time to subscribe to the SNS topic.
After the creation, this screen will pop up. If not, select your recently created topic in the topics section.
Press on the Create subscription option.

SNS

Select the following options to create a simple Email subscription, change the email field with the email you want to receive the notifications and press the Create subscription button.

SNS

SNS

You'll receive an email asking you to confirm the subscription, do it and then continue.

Now you have an SNS topic you can link to any other AWS resource, here is an example to use SNS topics and Codecommit triggers.

Prepare a Zip for AWS Lambda Layers

To utilize python packages in our lambda function, we need to upload a zip file with the content of our packages to Lambda Layers, follow the steps to create your zip or use mine and skip the creation.
You can follow most of the steps from a terminal or using the GUI.
Create a directory named python. The name is vital if you want to avoid possible issues.
You can use this instruction or create the folder manually.

$ mkdir python
Enter fullscreen mode Exit fullscreen mode

Folder
For the following steps, you'll need a terminal, don't worry it's easy, and remember, if you are not so sure about this, download my zip here. Open a terminal inside your recently created directory or cd into it.

$ cd /d/Documents/python
Enter fullscreen mode Exit fullscreen mode

Use this instruction to install the necessary packages inside the folder. In this case, we'll be installing discord-webhook.

$ pip3 install -t . discord-webhook
Enter fullscreen mode Exit fullscreen mode
  1. The next step is eliminating unnecessary files using this command.
$ rm -r *dist-info __pycache__
Enter fullscreen mode Exit fullscreen mode

Don't worry if you get a warning after this command, proceed
without a problem.

  1. Now, it's time to zip the folder. You can use this command or do it manually.
$ zip -r layer.zip python
Enter fullscreen mode Exit fullscreen mode

Zip

Upload Zip to Lambda Layer

First, let's get into the lambda service

Lambda

Select the Layer option on the sidebar and select Create Layer

Lambda
Upload the zip and fill in the options following the image below.

Lambda

Create the Lambda function

Now it's time to create the function. We will select the Function option on the same service, and then the Create function button.

Function

This is an essential step. To make things easier, instead of selecting the author from scratch option, we will choose the Use a blueprint option. Then we will search for the sns blueprint for python and select it. Then press on the Configure button

Function

Select the following options. Choose a name for your function.

Function
Select your topic from the SNS topic list, and then press Create function

Function

Function

Import the Layer

Inside your function, press the layers button.

Modules

Then press Add a Layer

Modules

In this menu, we'll fill in the options like the image below.
Under the custom layer option, select the Layer we just created and press Add
Layers

Code for the Function

Now you can replace the code from the function with the following:

from discord_webhook import DiscordWebhook, DiscordEmbed
import json

print('Loading function')


def lambda_handler(event, context):
    message = event['Records'][0]['Sns']['Message']
    print("From SNS: " + message)

    webhook = DiscordWebhook(url="replace with your webhook url")
    embed = DiscordEmbed(
        title="AWS",
        description=message,
        color="00ff00")

    #Select an image if you want
    #embed.set_image(url="")

    webhook.add_embed(embed)
    webhook.execute()

    return message
Enter fullscreen mode Exit fullscreen mode

Depending on your SNS topic, you may want to filter the messages with a simple sentence. If that's the case, use the following:

from discord_webhook import DiscordWebhook, DiscordEmbed
import json

print('Loading function')


def lambda_handler(event, context):
    #print("Received event: " + json.dumps(event, indent=2))
    message = event['Records'][0]['Sns']['Message']
    print("From SNS: " + message)
    message_str=str(message)
    ###If sentence to filter the messages you want to receive.
    if "New" in message:
        webhook = DiscordWebhook(url="replace with your webhook url")
        embed = DiscordEmbed(
            title="AWS",
            description=message,
            color="00ff00")

        #embed.set_image(url="")
        webhook.add_embed(embed)
        webhook.execute()
    else:
        pass
    return message
Enter fullscreen mode Exit fullscreen mode

Configure Test Event

Before the testing, we need to configure a Test Event.
Press on the test option and then on the Configure test event option.

Code

Choose a name for your test event. A template for the test event would be already selected. If not, search for the Sns notification template.

Code

Press Save at the end.
Code

Test the code

Before testing, press the deploy button.

Test

Now you're all set. Press on the Test button and check your discord channel.

Test

And here is what it looks like when triggered by an SNS message.

TTest

If you are having problems related to the module while testing, please refer to the official documentation here Or try using the python.zip that is in my repo.

Conclusion

Now you know how to set up a discord notifier that listens to an SNS Topic using Lambdas.
I hope you found this helpful.

Keep Learning.

Top comments (2)

Collapse
 
josuebustos profile image
Josue Bustos

Great tutorial Said! ⭐

And thanks for the mention! πŸ˜‰

Collapse
 
saids11 profile image
Said Silva

Thanks to you Josue! πŸ‘

Greetings.