cloudflareはTwitterアカウントの@CloudflareSysで障害情報を報告しているので
ここを監視して指定したキーワードに引っかかったら
メール通知するようにしました。
処理内容
- @CloudFlareSysのTwitterタイムラインの最新メッセージを取得
- 前回のメッセージの違っていると更新されたと判断
- キーワード(ここではTokyo,DNS)が含まれていたらメール送信
- スクリプトはcronで定期実行
スクリプト本体
cdn_tw_check.py
# ! /usr/local/python/bin/python
from twitter import *
import configparser
import shelve
import pyzmail
import os
confpath = os.path.join(os.path.dirname(__file__), 'settings.ini')
dbpath = os.path.join(os.path.dirname(__file__), 'twmsg')
conf = configparser.ConfigParser()
conf.read(confpath)
db=shelve.open(dbpath,"c")
twmsg={}
OAUTH_TOKEN = conf.get('twitter','OAUTH_TOKEN')
OAUTH_SECRET = conf.get('twitter','OAUTH_SECRET')
CONSUMER_KEY = conf.get('twitter','CONSUMER_KEY')
CONSUMER_SECRET = conf.get('twitter','CONSUMER_SECRET')
TARGET_NAME = conf.get('twitter','TARGET_NAME')
SENDER = conf.get('mail','SENDER')
RECIPIENTS = conf.get('mail','RECIPIENTS')
SUBJECT = conf.get('mail','SUBJECT')
PREFERED_ENCODING = conf.get('mail','PREFERED_ENCODING')
TEXT_ENCODING = conf.get('mail','TEXT_ENCODING')
SMTP_HOST = conf.get('mail','SMTP_HOST')
mail_flag=False
def msgsend(text_content):
payload, mail_from, rcpt_to, msg_id=pyzmail.compose_mail(\
SENDER, \
[RECIPIENTS], \
SUBJECT, \
PREFERED_ENCODING, \
(text_content, TEXT_ENCODING), \
html=None, \
attachments=None)
ret=pyzmail.send_mail(payload, mail_from, rcpt_to, SMTP_HOST)
tw=Twitter(auth=OAuth(OAUTH_TOKEN,OAUTH_SECRET,CONSUMER_KEY,CONSUMER_SECRET))
nowmsg=tw.statuses.user_timeline(screen_name=TARGET_NAME)[0]["text"]
twmsg = {TARGET_NAME:db.get(TARGET_NAME,"")}
lastmsg = twmsg[TARGET_NAME]
db[TARGET_NAME] = nowmsg
db.close()
if lastmsg != nowmsg :
for i in conf.get('keyword','ERROR').split(","):
if nowmsg.find(i) > -1:
mail_flag=True
if mail_flag:
msgsend(nowmsg)
設定ファイル
settings.ini
[twitter]
OAUTH_TOKEN=***
OAUTH_SECRET=***
CONSUMER_KEY=***
CONSUMER_SECRET=***
TARGET_NAME=@CloudFlareSys
[mail]
SENDER=<Sender Email Address>
RECIPIENTS=<Recipient Email Address>
SUBJECT="CloudFlare Tweet Message"
PREFERED_ENCODING=iso-8859-1
TEXT_ENCODING=iso-8859-1
SMTP_HOST=<SMTP HOST>
[keyword]
ERROR=Tokyo,DNS
githubにも置きました