이 글은 디스코드용 수능 알림이를 만든 토이 프로젝트 정리글입니다.
2023년 수능이 끝나고, 이제 내가 현역인 2024 수능이 시작되었다.
이걸 기념(?)해서 수능 당일날, 디스코드로 수능까지 남은 날자수를 보내주는
수능 알림이를 만들었다.
이 토이 프로젝트를 위해서 디스코드 봇 만드는 법과,
Github Action 사용법을 공부했다.
두 기술 모두 한 번쯤은 공부해보려고 생각해봤던 것들인데 이 기회에 공부해봤다.
# main.py
import discord
import datetime
from pytz import timezone
TOKEN = "..."
TEST_CHANNEL_ID = ...
channelIdList = [TEST_CHANNEL_ID, ...]
client = discord.Client(intents=discord.Intents.default())
def getNowDate():
today = datetime.datetime.now(timezone('Asia/Seoul'))
return today
def getRealLastExamDiff():
nowDate = getNowDate()
realLastExam = datetime.datetime(2023, 11, 16, tzinfo=timezone('Asia/Seoul'))
realLastExamDiff = realLastExam - nowDate
return realLastExamDiff
def getChannelList():
result = set([])
channelList = client.get_all_channels()
for i in channelList:
result.add(i.name)
return result
@client.event
async def on_ready():
print(f"On Ready {client.user}")
await client.change_presence(status=discord.Status.online)
realLastExamDiff = getRealLastExamDiff()
for n, id in enumerate(channelIdList):
ch = client.get_channel(id)
await ch.send(f"수능 D-{realLastExamDiff.days + 1}\n화이팅하십시오 휴먼들")
exit(0) #디스코드 메시지를 보낸뒤에 파이썬 코드 종료
client.run(TOKEN)```
```yml
name: D-day Alarm
on:
schedule: #주기적으로 매일 23시에 실행 (UTC 표준 시간 기준)
- cron: "0 23 * * *"
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest # 코드를 실행할 가상환경 설정
timeout-minutes: 1 # 타임 아웃 적용, 실행후 1분뒤에 자동 종료
steps:
- uses: actions/checkout@v3
- name: Set up Python 3.10 # 가상환경에 파이썬 설정
uses: actions/setup-python@v3
with:
python-version: "3.10"
- name: Install dependencies # 파이썬에서 사용하는 모듈들 설정
run: |
python -m pip install --upgrade pip
python -m pip install discord
python -m pip install pytz
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: Run python # 메인 코드 실행
run: |
python main.py
처음 Github Action으로 자동화 했을때는 매일 17시(오후 5시)에 디스코드 메시지가 오는 문제가 발생했다.
이유는 스케쥴 이벤트는 시간을 cron 표기법을 사용하는데
cron표기법은 표준 시간을 기준으로 하기 때문이다.
# workflow 기존 코드
on:
schedule:
- cron: "0 8 * * *"
이벤트를 다음과 같이 설정했는데, 매일 8시에 실행하게 설정해서
표준시 8시, 한국시간 15시에 디스코드 알림이 온것이다.
# workflow 개선 코드
on:
schedule:
- cron: "0 23 * * *"
Github Action에 시간대를 설정하는 방법이 없는거 같아서
다음과 같이 한국시간 8시에 맞는 표준시를 찾아서 workflow 파일을 수정해줬다.
디스코드 메시지의 날짜가 하루 많이 많이 오는 문제가 발생했다.
수능까지 남은 시간이 하루 더 늘어나는건 좋은 현상이지만,
현실은 아니기 때문에 심각한 버그다.
코드가 실행되는 가상환경의 시간대가 한국과 다른 표준시로 설정되있어서 발생한 문제이다.
# main.py 기존 코드
def getNowDate():
"""오늘 날짜를 가져오는 함수"""
today = datetime.datetime.now()
return today
기존 코드에는 오늘 날짜를 가져오는 코드에 시간대를 설정해 주지 않았다.
def getNowDate():
"""오늘 날짜를 가져오는 함수"""
today = datetime.datetime.now(timezone('Asia/Seoul'))
return today
이걸 다음과 같이 Asia/Seoul로 시간대를 추가해주었다.
이 프로젝트를 통해서 디스코드봇을 만드는 방식과
Github Action을 사용한 자동화를 공부했다.
나중에 블로그에 자세하게 정리해보는게 좋을 것 같다.
Python과 Github Action을 사용해서 다양한 업무 자동화를 해봐야겠다.
지금의 봇은 정해진 서버에 정해진 날의 디데이만 구할 수 있다.
이걸 더 확장해서 사용자가 지정한 서버의 채널에서 사용 할 수 있게 하고
사용자가 직접 디데이를 구할 기념일을 추가해서 사용 할 수 있게 하는 등
사용자들이 사용할 수 있도록 배포를 해보고 싶다.