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

![weather-logo.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/144058/5e24b705-a4a0-e47b-ce00-66cdc17bbb87.png)
## TL;DR
> 매일 아침 07:55에 오늘의 날씨를 **이미지**로 Slack에 알려줍니다. :sunny:

![w01.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/144058/581c5d8e-d60a-8f8d-d880-e07b94618a24.png)


## 준비물
- GitHub 계정
- [Slack Incoming WebHook](https://slack.com/apps/A0F7XDUAZ-incoming-webhooks) URL
- 트위터 API https://developer.twitter.com/en/apps
    - APP_KEY
    - APP_SECRET
    - OAUTH_TOKEN
    - OAUTH_TOKEN_SECRET

![w02.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/144058/520b7372-233c-43b4-f953-4e2f0a28ab1f.png)


## 구축하기
### GitHub Private 저장소 생성
:lock: Private 로 생성해주세요. 
예) 저장소 이름 : github-action
![w03.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/144058/f5f0b5da-0a91-0285-b7dc-11604080a268.png)


### 소스코드 작성
2개의 파일이 필요합니다. 
`weatherbot.yml`
`send_to_weather.py`

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


```bash
$ root@master:github-action# tree -al -I '.git'
.
├── .github
│   └── workflows
│       └── weatherbot.yml
├── README.md
└── send_to_weather.py
```
```yml: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를 본인 설정에 맞게 변경해주세요.

```python: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.yml`와 `send_to_weather.py` 2개의 파일을 업로드 합니다.
노란볼을 확인하고 Actions 클릭합니다.
자! 이제 `weatherbot.yml` 에 작성한대로 일련의 작업이 일어납니다. 이것이 :thumbsup_tone2: **Github Actions!**
따라해보실래요?
![w04.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/144058/4f11fa6f-bff7-fdd7-2877-52a45bc02a73.png)
![w05.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/144058/a9904df7-8a74-5080-414e-83fe0fa5b6eb.png)
![w06.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/144058/64ba0985-b3c9-72c7-f42b-bd9d2fff86e9.png)
![w10.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/144058/a117fdaf-7da2-8d44-c691-a2f6f829302a.png)


## 하고 싶은 말
자연스레 `Github Actions` + `Selenium` `API` `Slack Incoming WebHook` 도 사용하였습니다!