[Linux] Discord의 웹후크(webhook)를 사용해서 메세지 보내기

Discord의 웹후크(webhook)를 사용해서 리눅스에서 메세지를 보내는 방법을 알아보겠습니다. 아래와 같은 절차로 진행하면 됩니다.

  1. Discord 가입 및 웹후크 생성
  2. 리눅스 쉘 스크립트로 메세지 보내기
  3. 응용: 리소스 임계치 도달 메세지 보내기
  4. 응용: 날짜 이벤트 메세지 보내기

1. Discord 가입 및 웹후크 생성
  1. Discord 사용자 등록 및 로그인(https://discord.com/): 스마트폰으로 등록할 수도 있습니다.
  2. 화면 오른쪽 상단의 “Open Discord” 버튼 클릭
  3. 서버 추가하기(이름: trading)
    1. 화면 왼쪽 “서버 추가하기” 버튼 클릭
      discord 서버만들기
    2. “직접 만들기” 버튼 클릭
      discord 서버만들
    3. “나와 친구들을위한 서버” 클릭
      discord 서버만들
    4. 서버 이름으로 “trading” 입력한 후 “만들기” 버튼 클릭
      discord 서버만들
  4. 추가한 서버로 메세지를 받기 위한 웹후크 만들기
    1. 추가된 서버(t, trading)의 “채널 편집”을 위한 Gear 아이콘을 클릭
      discord 웹후크 만들기
    2. 왼쪽 “연동” 메뉴을 선택하고 “웹후크 만들기” 버튼 클릭
      discord 웹후크 만들기
    3. “Captain Hook” 영역을 클릭
      discord 웹후크 만들기
    4. “웹후크 URL 복사”를 버튼을 클릭하여 복사한 후 메모장 등에 붙여놓기하여 보관
      discord 웹후크 만들기
2. 리눅스 쉘 스크립로 메세지 보내기

쉘 스크립트를 사용해서 간단하게 메세지를 보내는 예제를 알아보겠습니다.

  1. bash 쉘 스크립트를 작성 및 실행
    discord_url 변수에 위에서 생성한 웹후크 URL를 설정합니다.
    $ vi discord-send-msg.sh
    #!/bin/bash
    
    discord_url="discord 웹후크 URL"
    
    # Define a function to send a message
    send_discord_notification() {
      local message=$1
      
      # Construct payload
      local payload=$(cat <<EOF
    {
      "content": "$message"
    }
    EOF
    )
    
      # Send POST request to Discord Webhook
      curl -H "Content-Type: application/json" -X POST -d "$payload" $discord_url
    }
    
    # Use the function
    send_discord_notification "Hello, World!"
    
    출처: https://gist.github.com/apfzvd/300346dae55190e022ee49a1001d26af
    
  2. 메세지 도착 확인(Hello, World!)
    discord message 확인
3. 응용: 리소스 임계치 도달 메세지 보내기

디스크 사용량를 주기적으로 점검해서 80%를 넘으면 경고 메시지를 보내는 예제를 만들어보겠습니다.

  1. bash 쉘 스크립트를 작성
    $ vi discord-send-disk-check-result.sh
    #!/bin/bash
    
    discord_url="discord 웹후크 URL"
    
    # Define a function to send a message
    send_discord_notification() {
      local message=$1
      
      # Construct payload
      local payload=$(cat <<EOF
    {
      "content": "$message"
    }
    EOF
    )
    
      # Send POST request to Discord Webhook
      curl -H "Content-Type: application/json" -X POST -d "$payload" $discord_url
    }
    
    # 임계값 설정 (80%)
    THRESHOLD=80
    
    # df 명령어로 디스크 사용량을 확인하고, 각 파일 시스템에 대해 루프 실행
    df -h --output=pcent,target | tail -n +2 | while read output; do
        # 디스크 사용량과 마운트 지점을 추출
        usage=$(echo $output | awk '{print $1}' | tr -d '%')  # 사용량에서 % 제거
        mount_point=$(echo $output | awk '{print $2}')        # 마운트 지점 추출
    
        # 사용량이 임계값을 넘으면 경고 메시지 출력
        if [ "$usage" -gt "$THRESHOLD" ]; then
            msg="경고: $mount_point의 디스크 사용량이 ${usage}%로 임계값($THRESHOLD%)을 초과했습니다!"
            send_discord_notification "$msg"
        fi
    done
    
  2. crontab에 등록하여 매 시간마다 점검
    $ crontab -e
    0 * * * * /path/to/discord-send-disk-check-result.sh
    
4. 응용: 날짜 이벤트 메세지 보내기

날짜별 등록된 이벤트를 확인해서 해당 일자에 등록된 이벤트가 있으면 메시지를 보내는 예제를 만들어보겠습니다.

  1. 쉘 스크립트 작성
    $ vi discord-send-event-check-result.sh
    #!/bin/bash
    
    discord_url="discord 웹후크 URL"
    
    # Define a function to send a message
    send_discord_notification() {
      local message=$1
      
      # Construct payload
      local payload=$(cat <<EOF
    {
      "content": "$message"
    }
    EOF
    )
    
      # Send POST request to Discord Webhook
      curl -H "Content-Type: application/json" -X POST -d "$payload" $discord_url
    }
    
    # 날짜별 여러 이벤트를 저장할 수 있는 배열을 정의
    declare -A events
    
    # 특정 날짜에 여러 이벤트를 배열로 저장
    events["2024-09-10"]="회의, 발표 준비"
    events["2024-09-11"]="크리스마스, 선물 교환"
    events["2024-01-01"]="새해, 불꽃놀이"
    events["2024-09-10"]="회의, 친구와 저녁"
    
    # 현재 시스템의 날짜를 가져옴 (YYYY-MM-DD 형식)
    current_date=$(date +%Y-%m-%d)
    
    # 해당 날짜에 이벤트가 있는지 확인하고 출력
    if [[ -n "${events[$current_date]}" ]]; then
        send_discord_notification "$current_date에 등록된 이벤트:"
        echo ${events[$current_date]} | tr ',' '\n' | while read output; do
            send_discord_notification "[$output]"
        done
    else
        send_discord_notification "$current_date에는 등록된 이벤트가 없습니다."
    fi
    
  2. crontab에 등록하여 매일 확인
    $ crontab -e
    1 0 * * * /path/to/discord-send-event-check-result.sh
    

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다