RSS更新を通知するBotを書いた。
今回はPleromaで通知するBot。
下をコピペすれば良い
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
from mastodon import Mastodon
import feedparser
import sys
import os
api = Mastodon(
api_base_url = 'https://social.glass-lab.net',
client_id = '',
client_secret = '',
access_token = ''
)
RSS_URL = "https://glass-lab.net/index.xml"
PUBDATE_LOG = "last_pubdate.log"
news_dic = feedparser.parse(RSS_URL)
latest_entry = news_dic['entries'][0]
message = 'ブログが更新されました '+ latest_entry.title + ' '+ latest_entry.link
pubDate = latest_entry.published
# 修正内容2 : 前回ツイートした記事の pubDate を取得
lastPubDate = None
if os.path.exists(PUBDATE_LOG):
with open(PUBDATE_LOG, "r") as rf:
lastPubDate = [line.strip() for line in rf.readlines()]
# 修正内3: 同じ記事をツイートしようとした場合、処理終了
if (pubDate == lastPubDate):
print("前回ツイートした記事です")
sys.exit()
else:
print("新しい記事が見つかりました。")
api.toot(status=message)
with open("last_pubdate.log", "a") as f:
f.write(pubDate + "\n")
|
実際にはClient_id、client_secret、Access_tokenを取得し上記に含めておく必要がある。
APIの取得のしかたはこちらの記事で解説している。
ちなみになのだが、Apiの類は平文のままコードに記述するのはあまり良くない。が、大したBotではないので許して欲しい。
これを利用したBotは私のPleromaにホストされている。
ちなみに筆者は上記のコードをcronで5分おきに動作させている。
としてcrontabを編集する
1
|
*/5 * * * * python3 bot.py
|
とすることで5分おきに動作させることができる
#PR
筆者が使っているもの、今回利用したもの
リンク
リンク
パソコンランキング