DEV Community

Cover image for GMAIL to Discord Channel Webhook Tutorial
soom
soom

Posted on • Updated on

GMAIL to Discord Channel Webhook Tutorial

Abstract

프로젝트를 진행하면서 Slack, Microsoft Teams, Discord 등 커뮤니케이션 툴은 원활한 프로젝트 진행을 위해 필수적인 요소 중에 하나다.

특히, 게임 보조 도구로 알려진 Discord의 경우 퍼포먼스에 민감한 게이머들을 만족시키는 강력한 커뮤니케이션 기능을 가지고 있다보니 이를 프로젝트 메인 커뮤니케이션 툴로 사용하는 경우도 점점 증가하고 있다.

이번 포스팅에서는 팀 메일이나 공식 메일이 올때마다 메일을 확인하는 것이 아닌 Discord의 하나의 채널에서 알림이 올수 있도록 웹훅 설정을 하는 과정을 소개하고자 한다.

Discord DOCs 링크: https://discord.com/developers/applications


Getting Started

Prerequisite

  • 여기서는 Discord 계정이 있고 서버를 생성한 상태를 가정한다
  • 서버에 해당하는 웹훅 권한이 필요하다

웹훅 권한 설정

gmail_discord_1


Setting Discord Webhook

Integrations 메뉴에서 Webhooks 생성을 클릭

Integrations 메뉴

gmail_discord_2


New Webhook을 선택해서 새로운 Webhook을 생성한 뒤 필요한 정보(Bot Name, Channel)를 입력해서 Noti-Bot을 생성

Discord 세팅은 여기까지 완료

Webhook 생성

gmail_discord_3


Setting up Google App Script

구글 앱 스크립트 페이지 접속:
https://www.google.com/script/start/

새 프로젝트 생성

구글 앱 스크립트 메인 화면

gmail_discord_4

메인 대쉬보드

gmail_discord_5


새로운 프로젝트에 다음과 같이 코드를 작성

Note

  • webhooks 변수에는 DiscordWebhook URL을 입력
Webhook 생성 화면

gmail_discord_6

  • channel 변수에는 채널 이름을 등록
Discord 채널명

gmail_discord_7

  • searchQuery 에는 구글 메일에서 쓰는 검색 쿼리를 사용한다. (하기 이미지 참조)
Gmail 쿼리 검색

gmail_discord_8

  • Gmail에서는 Discord2000 자 이상되는 내용을 게시할수 없기 때문에 2000 자 넘는경우 제한하는 로직이 필요하다.
code.gs
function postDiscord(postMessage) {
    const webhooks = 'https://discord.com/api/webhooks/webhooks/{webhook.id}/{webhook.token}';
    const channel = '{channel name}';
    const parse = 'full';
    const method = 'post';

    const payload = {
        channel: channel,
        content: postMessage,
        parse: parse,
    };

    const params = {
        method: method,
        payload: payload,
        muteHttpExceptions: true,
    };

    response = UrlFetchApp.fetch(webhooks, params);
}

function sendMailsToDiscord() {
    const searchQuery = '{gmail query}';
    const date = new Date();
    const checkSpan = 30;
    date.setMinutes(date.getMinutes() - checkSpan);

    const threads = GmailApp.search(searchQuery);
    const msgs = GmailApp.getMessagesForThreads(threads);

    for (let i = 0; i < msgs.length; i++) {
        const lastMsgDate = threads[i].getLastMessageDate();

        if (lastMsgDate.getTime() < date.getTime()) break;

        for (let j = 0; j < msgs[i].length; j++) {
            const msgDate = msgs[i][j].getDate();
            const msgBody = msgs[i][j].getPlainBody();
            const subject = msgs[i][j].getSubject();

            const postMessage =
                'From mailing list' +
                '\n' +
                Utilities.formatDate(msgDate, 'America/New_York', 'MM/DD/yyyy hh:mm:ss') +
                '\n' +
                'Title:' +
                subject +
                '\n' +
                '[hr]' +
                msgBody;

            // 2000 Characters limits
            if (postMessage.length > 2000) {
                const stopPos = 1900; //
                const msg = '"Exceeded 2000 character limit."';
                postMessage = postMessage.substring(0, stopPos) + '\n' + msg;
            }

            postDiscord(postMessage);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

trigger 를 설정

이후 새로운 메일이 올 경우 지정한 채널에 새로운 메세지가 푸시될 것이다.

Note

  • 실행할 함수를 선택: sendMailsToDiscord

  • 실행할 배포: Head

  • 이벤트 소스 선택: 시간 기반

  • 트리거 기반 시간 유형 선택: 분 단위 타이머

  • 분 간격 선택: 30분마다

  • 트리거 실패 알림 설정: 즉시 알림

trigger 화면

gmail_discord_9


Conclusion

본 포스팅에서는 GMAIL에서 Discord 채널에 새로운 메일이 올때마다 푸시하는 webhookGoogle App Script를 통해 Set up해 보았다.

Discord는 퍼포먼스에 민감한 게이머를 만족시킬수 있을정도의 수준의 서비스를 제공하고 있고 앞으로 여러 프로젝트에서도 많이 쓰일 것이다. 여기에 전 세계 메일의 표준이라고도 할수 있는 GMAIL을 연동하는 것은 가장 많이 사용하는 Webhook 중 하나가 될것이며 본 포스팅이 그런 부분에 많은 도움이 되었으면 하는 바램이다.

본 포스팅에 쓰인 Method가 궁금하다면 하기의 Google App Script 링크에서 자세한 내용을 참고

Link: https://developers.google.com/apps-script/reference/document

Latest comments (0)