Skip to content

Instantly share code, notes, and snippets.

@JUNNETWORKS
Created June 9, 2019 17:18
Show Gist options
  • Save JUNNETWORKS/a6adf7f774246324222ba9e399f9b69f to your computer and use it in GitHub Desktop.
Save JUNNETWORKS/a6adf7f774246324222ba9e399f9b69f to your computer and use it in GitHub Desktop.
暁寮寮食BOT自動化用定期実行スクリプト
"""
cron で1日1回実行するスクリプト
- 今月のデータがあるか
- 暁寮のHPのメニュー表が更新されているか
- 更新されてればメニュー表をDLし、それを画像に変換し、登録フォームに自動でリクエストを送りメニューを登録する
"""
import requests
import io
import os
import json
import datetime
from bs4 import BeautifulSoup
from pdf2image import convert_from_bytes
def get_html(url):
# 暁寮のサイトからデータを取得
res = requests.get(url)
res.encoding = res.apparent_encoding # 日本語の文字化けを修正 # https://qiita.com/nittyan/items/d3f49a7699296a58605b
html = res.text
return html
def get_menu_pdf_name(url):
html = get_html(url)
soup = BeautifulSoup(html, "html.parser")
menu_pdf_name = soup.find("a", text="寮食堂メニュー").get("href")
return menu_pdf_name
def update_this_month(url):
# get url of pdf file of this month menu
menu_pdf_name = get_menu_pdf_name(url)
# download pdf from website
pdf_res = requests.get(url + menu_pdf_name)
# conver pdf to image
menu_img = convert_from_bytes(pdf_res.content)[0]
# PIL image to bytes
img_byte_arr = io.BytesIO()
menu_img.save(img_byte_arr, format='PNG')
img_byte_arr = img_byte_arr.getvalue()
# send post request
requests.post("http://35.192.169.248/AkatsukiFood/form/", files={"file": img_byte_arr})
def read_previous_pdf_name(text_path):
text = ""
if os.path.exists(text_path):
with open(text_path, "r") as f:
text = f.read()
else:
with open(text_path, "w") as f:
f.write(text)
return text
# 今月のメニューデータが存在しているか
def exist_this_month_menu():
now = datetime.datetime.now()
url = "http://35.192.169.248/AkatsukiFood/api/{}/{}".format(now.year, now.month)
menu = requests.get(url)
menu = json.loads(menu.text)
return bool(menu)
if __name__ == "__main__":
school_dormitory_url = "http://ryo.s.toba-cmt.ac.jp/"
text_path = "pdf_name.txt"
# 今月のデータが存在してない
if not exist_this_month_menu():
# 前のpdfファイル名と現在寮HPにあるPDFの名前を取得
previous_pdf_name = read_previous_pdf_name(text_path)
current_pdf_name = get_menu_pdf_name(school_dormitory_url)
# 寮HP上のPDFが更新されているならメニューを登録
if current_pdf_name != previous_pdf_name:
update_this_month(school_dormitory_url)
# write current pdf name on website to txt file
with open(text_path, "w") as f:
f.write(current_pdf_name)
else:
print("寮のWebサイトのPDFはまだ更新されていません")
else:
print("今月のデータは登録済み")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment