Operate the schedule app using python from iphone

motivation

Recently, I'm addicted to watching live streaming of youtube on iphone. The app version is very convenient because it notifies you in advance with an alert.

It is a natural alert function, but if this function is not available, Viewers have to go check the program schedule every time.

For content that "time schedule fluctuates irregularly" It is often overlooked without an alarm function like youtube.

The information site I often see is just like that, I pay 1000 yen every month for paid content, but the schedule has changed so much that I will overlook it too much, so I will try to issue an alert on my own.

Hope

I would like to hold down only the following points.

1.Easy to operate with iphone
2.I get an alert.

Specifically, I will roughly follow the flow below.

1.Get time from site time schedule
2.Add schedule to google calendar
3.Notify with iphone calendar app

I was thinking of doing it with GAS, I will try it with "google colab" which I have been interested in for a long time. https://colab.research.google.com/notebooks/welcome.ipynb?hl=ja

google colab is a service that can run python on the cloud. If you have a browser, you can run it, so you can run it on your iphone/ipad.

You can use pip and apt-get, so it seems very convenient.

code

The code below. At the moment, I have to manually hit the script on a regular basis, but I want to do it with GAS soon.

test.py


import re
import datetime
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#Needed in a local environment
# import chromedriver_binary
from bs4 import BeautifulSoup
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from google.auth.transport.requests import Request
import os.path
import pickle
import time

# 0.Fixed value
CST_CALENDAR_ID = 'Enter the calendar ID of google calendar'
CST_LOCATION = "https://wwww.~~~~~~~~~~~~~~"

# 1.Analyzing sites to add to your calendar
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
#Needed in a local environment
#options.add_argument(r"--user-data-dir=C:\Users\(username)\AppData\Local\Google\Chrome\User Data")
driver = webdriver.Chrome('chromedriver', options=options)
driver.implicitly_wait(10)
driver.get(CST_LOCATION)
html = driver.page_source.encode('utf-8')
soup = BeautifulSoup(html, "html.parser")
arr_OA = soup.find_all('div')
arr_lap = []
all_events = []
today = datetime.date.today()
calYYYY = int(format(today, '%Y'))

flg_ToshiMatagi = False
for info_body in arr_OA:
    bs_date = info_body.find("div", class_='pgmOaTime')
    bs_title = info_body.find("p", class_='pgmTtl')
    if bs_date is not None:
        bs_date_all = bs_date.find_all("span")

        tex_date = ""
        tex_yobi = ""

        for text_tmp in bs_date_all:
            strText = text_tmp.get_text()
            #Date extraction(Assumed data:[12/25(soil)])No era
            if re.findall(r'\d+\/\d+', strText) != []:
                tmp_date = re.findall(r'\d+\/\d+', strText)
                if len(tmp_date) == 1:
                    tex_date = tmp_date[0]
                continue
            #Time extraction(Assumed data:[24:00~24:30]) 
            if re.findall(r'\d+:\d+~\d+:\d+', strText) != []:
                tmp_yobi = re.findall(r'\d+:\d+~\d+:\d+', strText)
                if len(tmp_yobi) == 1:
                    tex_yobi = tmp_yobi[0]
                continue
        #title
        tex_title = bs_title.get_text()

        if tex_date is None or tex_yobi is None: continue
        if tex_date == "" or tex_yobi == "": continue

        #Fort conversion for Google Calendar
        if (tex_title in arr_lap) == False:
            arr_lap.append(tex_title)
            calDate = re.findall(r'\d+', tex_date)
            calTime = re.findall(r'\d+:\d+', tex_yobi)

            #Insanely special correspondence (you do not have to do it)
            calPerTime = re.findall(r'\d+', calTime[0])
            calBgnHour = calPerTime[0]
            # 24,25,26:00... -> 23:50
            if int(calBgnHour) >= 24:
                calTime[0] = "23:50"
                calTime[1] = "23:50"
            #Over the years
            cur_month = int(calDate[0])
            if cur_month == 1 and bfr_month == 12:
                calYYYY = calYYYY + 1
            bfr_month = int(cur_month)

            startDate = '{0}-{1}-{2}T{3}:00'.format(calYYYY, calDate[0], calDate[1], calTime[0])
            endDate = '{0}-{1}-{2}T{3}:30'.format(calYYYY, calDate[0], calDate[1], calTime[0])

            print(startDate,endDate,tex_title)
            if startDate is None or endDate is None: continue
            if startDate == "" or endDate == "": continue

            event = {
                'summary': tex_title,
                'location': CST_LOCATION,
                'description': tex_title,
                'start': {
                    'dateTime': startDate,
                    'timeZone': 'Japan',
                },
                'end': {
                    'dateTime': endDate,
                    'timeZone': 'Japan',
                },
            }

            all_events.append(event)

event = {
                'summary': "All schedules are complete. Please update the schedule.",
                'location': CST_LOCATION,
                'description': tex_title,
                'start': {
                    'dateTime': startDate,
                    'timeZone': 'Japan',
                },
                'end': {
                    'dateTime': endDate,
                    'timeZone': 'Japan',
                },
            }
all_events.append(event)

# 2.Add google calendar
# https://developers.google.com/calendar/quickstart/python?authuser=1
#Hard-code the contents of the json file created in Step 1 into the code and output the file.
#Colab has special support for Colab because saved files disappear.
JSONstring = 'JSON content'
with open('credentials.json', mode='w') as f:
    f.write(JSONstring)

SCOPES = ['https://www.googleapis.com/auth/calendar']

flow = InstalledAppFlow.from_client_secrets_file(
    'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)

for event in all_events:
    print(event)
    time.sleep(10)
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
        # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)
    # creds = GoogleCredentials.get_application_default()
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)
    event1 = service.events().insert(calendarId=CST_CALENDAR_ID,
                                    body=event).execute()

Recommended Posts

Operate the schedule app using python from iphone
Operate the programming follow from Pythonista (iPhone)
Operate Redmine using Python Redmine
Operate Filemaker from Python
[Python] Let's execute the module regularly using schedule
Operate neutron from Python!
Operate LXC from Python
Study from the beginning of Python Hour8: Using packages
Using the LibreOffice app in Python (1) Where are the macros?
A little bit from Python using the Jenkins API
Flatten using Python yield from
I tried using the Python library from Ruby with PyCall
Operate your browser using the Selenium Web Driver Python bindings
Using Rstan from Python with PypeR
Notes on using MeCab from Python
Operate an I2C-connected display from Python
Operate DynamoDB from Python like SQL.
Existence from the viewpoint of Python
Using Cloud Storage from Python3 (Introduction)
Use the Flickr API from Python
Extract the targz file using python
Try using the Python Cmd module
Run Ansible from Python using API
Precautions when using phantomjs from python
Access spreadsheets using OAuth 2.0 from Python
Try using Amazon DynamoDB from Python
How to get followers and followers from python using the Mastodon API
Operate Firefox with Selenium from python and save the screen capture
Try using the Wunderlist API in Python
From Python to using MeCab (and CaboCha)
Try using the Kraken API in Python
Behind the flyer: Using Docker with Python
Download the file from S3 using boto.
Learning notes from the beginning of Python 1
Try using the Python web framework Django (1)-From installation to server startup
[Python] [Excel] Operate an Excel sheet from Python using openpyxl (using a test sheet as an example)
Working with OpenStack using the Python SDK
I tried using UnityCloudBuild API from Python
Try to operate Excel using Python (Xlwings)
Reboot the router using Python, Selenium, PhantomJS
How to operate Linux from the console
Launch the Python interpreter from Git bash
Access Google Calendar from the iOS app
[Pyto] Operate iPhone Taptic Engine with Python
From Python 3.4, pip becomes the standard installer! ??
[Python] Automatically operate the browser with Selenium
Search for synonyms from the word list (csv) using Python Japanese WordNet
Operate Sakura's cloud object storage from Python
Learning notes from the beginning of Python 2
[Python] Get the main color from the screenshot
python setup.py test the code using multiprocess
Use the LibreOffice app in Python (2) Manipulate calc (from macros and externals)
Region extraction method using cellular automaton Try region extraction from the image with growcut (Python)
Using the 1-Wire Digital Temperature Sensor DS18B20 from Python on a Raspberry Pi
Get the contents of git diff from python
Aggregate test results using the QualityForward Python library
Operate the Speech Signal Processing Toolkit via python
The first web app created by Python beginners
Exclusive release of the django app using ngrok
Try using the BitFlyer Ligntning API in Python
Python: Try using the UI on Pythonista 3 on iPad