6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

調べたいキーワードを含むニュースを配信するSlackbotを作った話

Posted at

こんばんは〜
今日はAtcoderじゃなくて、slackbotを作った話です:point_up:
指定したキーワードを含む最新のgoogleニュース5件を返してくれるようにしました。
入力は「news (キーワード)」※newsの後にスペースが必要
初期設定はこちらを参考にさせて頂きました。

# coding: utf-8
from slackbot.bot import respond_to
import feedparser
import json
import pprint
import urllib
import re

@respond_to('news\s(.*)') #入力はnews xxxx
def news_reply(message, keyword): #inputの2つ目を調べる際のkeywordとする
    # RSSのスクレイピング
    s = keyword
    # URLエンコーディング
    s_quote = urllib.parse.quote(s)
    url = "https://news.google.com/news/rss/search/section/q/" + s_quote + "/" + s_quote + "?ned=jp&hl=ja&gl=JP"

    d = feedparser.parse(url)
    news = list()

    for i, entry in enumerate(d.entries, 1):

        p = entry.published_parsed
        sortkey = "%04d%02d%02d%02d%02d%02d" % (p.tm_year, p.tm_mon, p.tm_mday, p.tm_hour, p.tm_min, p.tm_sec)

        tmp = {
            "no": i,
            "title": entry.title,
            "link": entry.link,
            "published": entry.published,
            "sortkey": sortkey  #日付でソート
        }

        news.append(tmp)

    news = sorted(news, key=lambda x: x['sortkey'])
    #最新のニュース5件のタイトルとリンクを表示
    for i in range(1,6): 
        text = news[-i]["title"] + '\n' + news[-i]["link"]
        message.reply(text)

見た目はこんな感じ。
スクリーンショット 2019-06-21 23.26.40.png

結論:
slackbotは簡単に作れる。
普通にググれば良い :ramen:

6
2
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
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?