LoginSignup
7
9

More than 5 years have passed since last update.

毎朝大相撲力士の画像を送ってくれるLINE BOTを作った

Posted at

はじめに

朝起きるのがとても苦手です。
スマホのアラームを複数セットしていますが、聞き飽きているので、ん、と思うだけでまたすぐ寝てしまいます。

そこで、
アラーム設定時刻に定期実行する、自分の好きなものの画像をネットから拾って送信してくれるLINE BOT
を作ってみました。

ネットの画像を拾う(Google Custom Search API)

Google Custom Search APIを使って画像収集を参考に、
APIを有効にして、自分の好きなものの画像をネットから取得しました。


def get_image_urls(search_word):
    CUSTOM_SEARCH_API_KEY = "**********"
    CUSTOM_SEARCH_ENGINE_ID = "**********"
    custom_search_url = f"https://www.googleapis.com/customsearch/v1?key={CUSTOM_SEARCH_API_KEY}&cx={CUSTOM_SEARCH_ENGINE_ID}&searchType=image&q={search_word}&num=10"
    img_urls = []
    res = urllib.request.urlopen(custom_search_url)
    data = json.loads(res.read().decode('utf-8'))
    for i in range(len(data["items"])):
        img_urls.append(data["items"][i]["link"])
    return img_urls

def get_image(search_word):
    img_urls = get_image_urls(search_word)
    img_url = random.choice(img_urls)
    img = requests.get(img_url).content
    return img

自動でLINEを送信する(LINE Notify)

PythonからLINE NotifyでLINEにメッセージを送るを参考に、
LINE Notifyに登録し、画像を送信するBOTを作りました。

def line(img):
    LINE_NOTIFY_TOKEN = "**********"
    line_notify_url = 'https://notify-api.line.me/api/notify'

    message = '起きる時間です'
    payload = {'message': message}
    headers = {'Authorization': 'Bearer ' + LINE_NOTIFY_TOKEN}
    files = {"imageFile": img}
    r = requests.post(line_notify_url, headers=headers, params=payload, files=files)

プログラムを定期実行する(AWS Lambda + CloudWatch)

12時になったらお昼を告げるためSlackに「ごはんですよ」の画像を投稿させたいを参考に、Lambda Functionを作成し、CloudWatchで定期実行させました。
サードパーティのライブラリであるrequestsを使う際、【AWS】Lambdaでpipしたいと思ったときにすべきことを参考にしました。

import json
import random
import urllib.request
import urllib.parse
import requests

def lambda_handler(event, context):
    search_words = ['千代丸', '遠藤関', '高見盛', '朝青龍', '寺尾力士', 'わんぱく相撲']
    search_word = random.choice(search_words)
    search_word = urllib.parse.quote(search_word)
    img = get_image(search_word)
    return line(img)

まとめ

これで毎朝スッキリと目覚めることが出来そうです。

コードは全てgithubにあります。間違い等ご教授いただけたらうれしいです。

7
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
9