GitHub Actions으로 날씨알리미 만들기

·2020년 4월 7일
3
post-thumbnail

TL;DR

매일 아침 07:55에 오늘의 날씨를 이미지로 Slack에 알려줍니다.

준비물

구축하기

GitHub Private 저장소 생성

Private 로 생성해주세요.
예) 저장소 이름 : github-action

소스코드 작성

2개의 파일이 필요합니다.
weatherbot.yml
send_to_weather.py

.github/workflows/ 하위 경로에 weatherbot.yml 있어야만 GitHub Actions 이 동작합니다!

$ root@master:github-action# tree -al -I '.git'
.
├── .github
│   └── workflows
│       └── weatherbot.yml
├── README.md
└── send_to_weather.py

weatherbot.yml

name: Weather Bot (웨더봇)

on:
   schedule:
     - cron: '55 22 * * *' # UST 가 default. UST 22:55는 한국시간 07:55

jobs:
  build:
    runs-on: ubuntu-18.04 # 우분투 18.04 에서
    strategy:
      matrix:
        python-version: [3.7] # 파이썬 3.7 버전으로

    steps:
    - uses: actions/checkout@v2
    - name: Set up python ${{ matrix.python-version }}
      uses: actions/setup-python@v1
      with:
        python-version: ${{ matrix.python-version }}
    
    - name: Install python package # 파이썬 관련 패키지를 설치하고
      run: |        
        pip install selenium
        pip install requests        
        pip install twython
        pip install pillow
    
    - name: Install ubuntu package # 우분투 관련 패키지도 설치한 후
      run: |        
        sudo apt-get install fonts-unfonts-core
        sudo apt-get install fonts-unfonts-extra
        wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add        
        sudo apt-get install google-chrome-stable    
        wget https://chromedriver.storage.googleapis.com/2.40/chromedriver_linux64.zip
        unzip ./chromedriver_linux64.zip   
      
    - name: Run! # send_to_weather.py 파일을 실행하시오! 
      run: | 
        python ./send_to_weather.py 

수정1~5를 본인 설정에 맞게 변경해주세요.

send_to_weather.py

from time import sleep
from selenium import webdriver
from PIL import Image
from io import BytesIO
from twython import Twython
import requests
import json

try:

    options = webdriver.ChromeOptions()
    options.add_argument("start-maximized")
    options.add_argument("lang=ko_KR")
    options.add_argument('headless')
    options.add_argument('window-size=1920x1080')
    options.add_argument("disable-gpu")
    options.add_argument("--no-sandbox")

    # chrome driver
    driver = webdriver.Chrome('chromedriver', chrome_options=options)
    driver.implicitly_wait(3)    
    
    # 케이웨더 접속
    driver.get('https://www.kweather.co.kr/weather.html')
    driver.maximize_window()    

    kweather_map = driver.find_element_by_class_name('kweather_map')

    location = kweather_map.location
    size = kweather_map.size

    left = location['x']
    top = location['y']
    right = location['x'] + size['width']
    bottom = location['y'] + size['height']
    sleep(3)
    
    png = driver.get_screenshot_as_png()
    img = Image.open(BytesIO(png))
    # 오늘의 날씨 영역만 잘라냅니다.
    area = (left, top, right, bottom)    
    kweather = img.crop(area)
    kweather.save('kweather.png')
    photo = open("./kweather.png", 'rb')
    
    #############################################
    # configure twitter API 
    ######################################
    APP_KEY = 'Sj2nUNEWxHFNdkR1234567890' # 수정1
    APP_SECRET = 'UQ4FUe7tlC3OZKPYrZLWhZFewDeaxzcxvaKysVor1234567890' # 수정2
    OAUTH_TOKEN = '976599794335416320-ould5HpxCQjgNcIai6rkA1234567890' # 수정3
    OAUTH_TOKEN_SECRET = 'DbIWTEWZwCQW2u1K3US0TJNVD8D3B1fm96S1234567890' # 수정4
    
    ###################
    # upload twitter
    ##################
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    # 트위터에 잘라낸 오늘의 날씨 영역 이미지를 업로드 합니다.
    response = twitter.upload_media(media=photo)
    tweet_message = 'kweather'
    result = twitter.update_status(status=tweet_message, media_ids=[response['media_id']])
    photo_url = result['extended_entities']['media'][0]['media_url_https']    
    
    #######################
    # send to slack
    ############################
    # Slack 인커밍 웹훅
    slack_incoming_url = "https://hooks.slack.com/services/TFN5D0ALR/BKUL3LYGL/6mDjUaSdUgaIal1234567890" # 수정5
    slack_payload = {
        "attachments": [
            {

                "text": "오늘의 날씨",
                "image_url": photo_url,
                "color": "#764FA5"
            }
        ]
    }
    # 슬랙에 쏩니다!
    req = requests.post(url=slack_incoming_url, data=json.dumps(slack_payload))
    print(req)

except Exception as e:
    print(e)    
    driver.quit()

finally:
    print("finally...")
    driver.quit()

동작 확인하기

github-action 저장소에 위에 작성한 weatherbot.ymlsend_to_weather.py 2개의 파일을 업로드 합니다.
노란볼을 확인하고 Actions 클릭합니다.
자! 이제 weatherbot.yml 에 작성한대로 일련의 작업이 일어납니다. 이것이 Github Actions!
따라해보실래요?



하고 싶은 말

자연스레 Github Actions, Selenium, API, Slack Incoming WebHook 도 사용하였습니다!

0개의 댓글