Skip to content

Instantly share code, notes, and snippets.

@curipha
Created October 31, 2021 12:32
Show Gist options
  • Save curipha/85eda837413e15e80a9da2be412690f7 to your computer and use it in GitHub Desktop.
Save curipha/85eda837413e15e80a9da2be412690f7 to your computer and use it in GitHub Desktop.
Send a Teams Webhook when JR 京都線 is delayed
#!/usr/bin/env python3
# coding: utf-8
import json
from urllib import request,parse
from lxml import html
WEBHOOK = 'https://127.1.1.1/' # Put your webhook endpoint here
URI = 'https://trafficinfo.westjr.co.jp/kinki.html'
XPATH_BASE = '//div[@id="syosai_1"][1]'
XPATH_IMG = '//div[@id="contents"]//img[@usemap]'
fp = request.urlopen(URI)
parser = html.fromstring(fp.read())
dom = parser.xpath(XPATH_BASE + '/strong[1]/text()')
if len(dom) > 0 and u'列車の遅れなどの情報はありません' in dom[0]:
print('Train operates normally!')
exit()
image = None
dom = parser.xpath(XPATH_IMG)
if len(dom) > 0:
image = parse.urljoin(fp.geturl(), dom[0].attrib.get('src'))
dom = parser.xpath(XPATH_BASE + '/div[@class="jisyo"]')
if len(dom) < 1:
print('Possibly DOM structure has been changed!')
exit(1)
topics = []
for elem in dom:
areas = []
area_dom = elem.iterfind('div[@class="jisyo_contents"]/p')
for area in area_dom:
if area.find('span[@class="line"]') is not None:
areas.append(
{
'line': area.findtext('span[@class="line"]'),
'station': area.findtext('span[@class="station"]').replace(u' ', ' '),
}
)
topics.append(
{
'title': elem.findtext('div[@class="jisyo_hdr"]/h2[@class="jisyo_title"]/a[@id]'),
'image': image,
'summary': elem.xpath('string(div[@class="jisyo_contents"]/p[@class="gaiyo"])'),
'areas': areas,
'history': parse.urljoin(
fp.geturl(),
elem.xpath('div[@class="jisyo_hdr"]/div[@class="jisyo_date"]//a[@href]')[0].attrib.get('href'),
),
}
)
for topic in topics:
if not any(map(lambda area: '京都' in area['line'], topic['areas'])):
print('Delayed, but it is not on 京都線')
print(topic['areas'])
continue
payload = {}
payload['title'] = topic['title']
payload['text'] = """
<p><a href="{}">詳細・履歴</a></p>
<p>{}</p>
<ul>{}</ul>
<img src="{}" />
""".format(
topic['history'],
topic['summary'],
'<li>' + '</li><li>'.join(map(lambda area: area['line'] + ': ' + area['station'], topic['areas'])) + '</li>',
topic['image'],
)
post = request.Request(WEBHOOK, json.dumps(payload).encode(), { 'Content-Type': 'application/json' })
request.urlopen(post)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment