• Home
  • About
    • Pieces for Studying photo

      Pieces for Studying

      Moon is a minimal, one column jekyll theme.

    • Learn More
    • Email
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • Baekjoon
    • CS231N
    • Study
  • Projects

[AWS] Lambda를 이용한 Slack Bot (1) - Configuration

28 Nov 2020

Reading time ~1 minute

AWS Lambda를 이용하여 정해진 시간마다 페이지를 크롤링해 슬랙 메시지를 보내는 Slack bot을 제작하여 보았습니다.

  • axios와 cheerio를 이용해 원하는 데이터 추출
  • Incoming webhook을 이용해 메시지 전송

0. 준비물

  • node + typescript
  • serverless : open source CLI로, 서버리스 어플리케이션을 편리하게 관리 할 수 있음
  • serverless-plugin-typescript : 타입스크립트 컴파일 제공 플러그인
  • @slack/webhook
  • axios + cheerio : page crawling
  • AWS, Slack 계정

1. Serverless 설정

  1. 프로젝트 초기화
    npm init
    
  2. serverless 설치 & 설정 serverless 설치
    npm install -g serverless
    serverless create --template aws-nodejs
    

    AWS 계정과 연동 : IAM 사용자 생성 후 권한 부여(AdministratorAccess) 이후 Access Key 와 Secret을 이용해 등록

    serverless config credentials --provider aws --key [KEY] --secret [SECRET]
    

    serverless 설정

plugins:
  - serverless-plugin-typescript
provider:
  name: aws
  runtime: nodejs12.x
functions:
  hello:
    handler: index.hello // index.ts의 hello function
    environment:
      WEBHOOK_URL: VALUE
    events:
      schedule: cron(0 8 * * ? *) // 매일 8시

따로 Lambda를 트리거 하지 않고 주기에 맞춰 실행하기만 하면 되기 때문에 API Gateway는 연동하지 않았다.

필요한 모듈 설치

npm install axios cheerio @slack/webhook
npm install -D typescript @types/axios @types/cheerio

2. Incoming webhook

HTTP를 이용해 간단하게 슬랙 메시지를 보내는 방법이다. 먼저 새로운 App을 만들고 Incoming Webhook을 생성하면 끝이다. 생성하면 unique한 URL이 생성되는데, 이 URL로 원하는 내용을 JSON형태로 담아 POST 요청을 보냄으로써 메시지를 전송할 수 있다.

curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/URL`


study Share Tweet +1