AWS SNS to Telegram and slack

  • Category: 電腦相關
  • Last Updated: Tuesday, 30 July 2019 11:58
  • Published: Monday, 22 July 2019 15:05
  • Written by sam

原本只做了sns裡面的信件服務

加一下Telegram這樣也比較方便在聊天時順便看…

2019 07 22 142023

先到Amazon SNS建立Topics

2019 07 22 142601

建立AWS Lambda

Create function

2019 07 22 142946

 2019 07 22 143139

貼上代碼


import json
import os
import logging
from botocore.vendored import requests

# Initializing a logger and settign it to INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)

# Reading environment variables and generating a Telegram Bot API URL
TOKEN = os.environ['TOKEN']
USER_ID = os.environ['USER_ID']
TELEGRAM_URL = "https://api.telegram.org/bot{}/sendMessage".format(TOKEN)

# Helper function to prettify the message if it's in JSON
def process_message(input):
    try:
        # Loading JSON into a string
        raw_json = json.loads(input)
        # Outputing as JSON with indents
        output = json.dumps(raw_json, indent=4)
    except:
        output = input
    return output

# Main Lambda handler
def lambda_handler(event, context):
    # logging the event for debugging
    logger.info("event=")
    logger.info(json.dumps(event))

    # Basic exception handling. If anything goes wrong, logging the exception    
    try:
        # Reading the message "Message" field from the SNS message
        message = process_message(event['Records'][0]['Sns']['Message'])

        # Payload to be set via POST method to Telegram Bot API
        payload = {
            "text": message.encode("utf8"),
            "chat_id": USER_ID
        }

        # Posting the payload to Telegram Bot API
        requests.post(TELEGRAM_URL, payload)

    except Exception as e:
        raise e

回到Amazon SNS

2019 07 22 143630

2019 07 22 143655

回到Lambda Add trigger

2019 07 22 144038

回到Amazon SNS Topics

2019 07 22 144150

點Publish message

2019 07 22 144237

測試一下,正確的話,就能正確收到訊息

如第一張圖

Telegram Bot 就自行Google啦

#2019/07/25

https://aws.amazon.com/tw/chatbot/