Exemplo n.º 1
0
def prediction(line_token: str, save_dir: str) -> None:
    '''
    日別感染者数の【予測】グラフを作成します。

    Args:
        line_token (str): POSTするLINEのトークン
        save_dir (str): 一時データを保存するディレクトリパス
    '''
    try:
        body = get_requests(
            'https://covid19-japan-web-api.now.sh/api/v1/total?predict=true')
    except Exception as error:
        print(f'error:{error.args}')
        return

    history_path = os.path.join(save_dir, 'history_prodiction.json')
    graph_image_path = os.path.join(save_dir, 'graph_prodiction.png')

    if os.path.isfile(history_path):
        old_body = json_read(history_path)
    else:
        old_body = []

    if body != old_body:
        make_graph(
            body, graph_image_path,
            'COVID - 19 days to measure the number of infected persons')
        text = '日別感染者数の予測グラフ'
        post_line(line_token, text, graph_image_path)
        json_write(body, history_path)
Exemplo n.º 2
0
def duplication_report(event_id: str, save_file_path: str) -> int:
    '''
    Check out the follow-up to "Seismic Intensity Bulletin".

    Args:
        event_id (str): Id of the event
        save_file_path: The path of the cache file to save.
    Returns:
        int: What is the report?
    '''
    now = datetime.datetime.now()

    if os.path.isfile(save_file_path):
        previous_data = json_read(save_file_path)
    else:
        previous_data = []

    # delete old element
    if previous_data != []:
        delete_data = []
        for index, element in enumerate(previous_data):
            date = datetime.datetime.strptime(str(element['date']),
                                              r'%Y%m%d%H%M%S')
            diff_date = now - date
            if diff_date.seconds > 3600:
                delete_data.append(index)

        delete_data.sort(reverse=True)
        for element in delete_data:
            del previous_data[element]

    # check report
    is_existence = False
    report = 1
    for element in previous_data:
        if str(event_id) == element['id']:
            is_existence = True
            element['report'] += 1
            report = element['report']
            element['date'] = now.strftime(r'%Y%m%d%H%M%S')
            break
    if not is_existence:
        report = 1
        data = {
            'date': now.strftime(r'%Y%m%d%H%M%S'),
            'id': str(event_id),
            'report': report
        }
        previous_data.append(data)

    json_write(save_file_path, previous_data)

    return report
    def __load_cache(self, empty_element: Any) -> Any:
        '''
        Load cache file.
        If it does not exist, the argument is returned directly.

        Args:
            empty_element (Any): Element that is returned directly if it does not exist.

        Returns:
            Any: The contents of the cache file. If not present, argument element.
        '''
        if os.path.isfile(self.save_file_path):
            buffer = json_read(self.save_file_path)
        else:
            buffer = empty_element

        return buffer
Exemplo n.º 4
0
    def __init__(self, user_file_path: str, cache_dir_path: str):
        '''
        Compare the user config with the buffer and send the changes and newly added elements to the configured SNS.

        Args:
            uer_file_path(str): User config json file path.
            cache_dir_path(str): The directory path to save the buffer.
        '''
        self.user_file_path = user_file_path
        self.cache_dir_path = cache_dir_path
        self.cache_file_path = os.path.join(self.cache_dir_path,
                                            'buffre_user_setting.json')

        if os.path.isfile(self.cache_file_path):
            self.users = json_read(self.cache_file_path)
        else:
            self.users = {}

        self.setup()
Exemplo n.º 5
0
def now_total(line_token: str, save_dir: str) -> None:
    '''
    感染者数の速報を通知する

    Args:
        line_token (str): LINEのアクセストークン
        save_dir (str): 一時データを保存するディレクトリパス
    '''
    try:
        body = get_requests(
            'https://covid19-japan-web-api.now.sh/api/v1/prefectures')
    except Exception as error:
        print(f'error:{error.args}')
        return

    save_file_path = os.path.join(save_dir, 'day_before.json')

    if os.path.isfile(save_file_path):
        old_patient = json_read(save_file_path)
    else:
        old_patient = {'patient': 0, 'before': 0, 'date': None}

    total_patient = 0
    for body_metadata in body:
        total_patient += int(body_metadata['cases'])

    if total_patient != old_patient['before']:
        date = datetime.datetime.now().strftime(r'%d')

        if old_patient['date'] != date:
            old_patient['patient'] = old_patient['before']

        difference = total_patient - old_patient['patient']

        text = f'\n現在の感染者数: {total_patient}人\n(前日比: {difference:+})'
        post_line(line_token, text, None)

        old_patient['before'] = total_patient
        old_patient['date'] = date

        json_write(old_patient, save_file_path)
Exemplo n.º 6
0
def today_total(line_token: str, save_dir: str) -> None:
    '''
    - 前回取得したデータと最新のデータを比較し日付が変わっている場合に
        - 前回取得したデータと最新の陽患者数の増加数の計算
        - その他様々なデータを取得
        - 増加数をグラフ描画し保存。メタデータをjsonで保存。
        - 増加数のグラフ描画とデータをLINEにpost

    Args:
        line_token (str): LINE notifyのアクセストークン
        save_dir (str): 一時データを保存するディレクトリパス
    '''
    try:
        body = get_requests(
            'https://covid19-japan-web-api.now.sh/api/v1/total')
    except Exception as error:
        print(f'error:{error.args}')
        return
    day = body['date']

    save_file_path = os.path.join(save_dir, 'save.json')
    daily_infections = os.path.join(save_dir, 'daily.json')
    graph_image_path = os.path.join(save_dir, 'graph_dayly.png')

    if os.path.isfile(save_file_path):
        old_body = json_read(save_file_path)
        old_day = old_body['date']
        difference = body['positive'] - old_body['positive']
    else:
        old_day = None
        difference = 0

    if day != old_day:
        if os.path.isfile(daily_infections):
            daily = json_read(daily_infections)
        else:
            daily = []

        day_obj = datetime.datetime.strptime(str(day), r'%Y%m%d')
        daily.append({'date': day, 'positive': difference})

        text = f'''
{day_obj.month}月{day_obj.day}日

☣感染者: {body['positive']}人
(前日比: {difference:+})
  - 退院: {body['discharge']}人
  - 入院中: {body['hospitalize']}人
    * 軽中度・無症状: {body['mild']}人
    * 人工呼吸・ICU: {body['severe']}人
    * 確認中: {body['confirming']}人
    * 待機中: {body['waiting']}人
  - 死亡: {body['death']}人

source by: https://covid-2019.live/ '''

        make_graph(daily, graph_image_path,
                   'Number of infected persons per day')
        post_line(line_token, text, graph_image_path)

        print(text)
        print('-' * 30)
        print('\n\n')

        json_write(daily, daily_infections)
        json_write(body, save_file_path)
Exemplo n.º 7
0
    def setup(self) -> None:
        '''
        Set up the user config.
        Any new additions or changes will be sent to your platform.
        '''
        # Too many branches and statements is specifications
        # pylint: disable=R0912,R0915
        new_users = json_read(self.user_file_path)

        delete_element = set()
        for user_name in self.users:
            if user_name not in new_users:
                delete_element.add(user_name)

        for key in delete_element:
            del self.users[key]

        for user_name in new_users:

            if user_name not in self.users:
                # new accounts
                self.users[user_name] = new_users[user_name]

                token = new_users[user_name]['token']

                if new_users[user_name]['areas'] == []:
                    areas = 'All'
                else:
                    areas = '、'.join(new_users[user_name]['areas'])

                seismic_intensity = new_users[user_name]['seismic_intensity']
                if seismic_intensity == '0':
                    seismic_intensity = 'All'

                is_quick_report = new_users[user_name]['is_quick_report']

                text = f'[設定を追加しました]\n(´-ω-`)\
\n- 送信する最低震度: {seismic_intensity}\n- 送信する地域: {areas}\n- 緊急速報の送信: {is_quick_report}'

            elif new_users[user_name]['seismic_intensity'] != self.users[
                    user_name]['seismic_intensity']:
                # changed seismic intensity
                self.users[user_name] = new_users[user_name]

                token = new_users[user_name]['token']
                seismic_intensity = new_users[user_name]['seismic_intensity']
                if seismic_intensity == '0':
                    seismic_intensity = 'All'
                text = f'[設定を変更しました]\n(´-ω-`)\n- 送信する最低震度: {seismic_intensity}'

            elif new_users[user_name]['areas'] != self.users[user_name][
                    'areas']:
                # changed areas
                self.users[user_name] = new_users[user_name]

                token = new_users[user_name]['token']
                if new_users[user_name]['areas'] == []:
                    areas = 'All'
                else:
                    areas = '、'.join(new_users[user_name]['areas'])
                text = f'[設定を変更しました]\n(´-ω-`)\n- 送信する地域: {areas}'

            elif new_users[user_name]['is_quick_report'] != self.users[
                    user_name]['is_quick_report']:
                # changed quick report
                self.users[user_name] = new_users[user_name]

                token = new_users[user_name]['token']
                is_quick_report = new_users[user_name]['is_quick_report']
                text = f'[設定を変更しました]\n(´-ω-`)\n- 緊急速報の送信: {is_quick_report}'

            else:
                continue

            platform = int(new_users[user_name]['platform'])
            if platform == 1:
                line(token, text, None)
            elif platform == 2:
                channel = new_users[user_name]['channel']
                slack(token, channel, text, None)
            elif platform == 3:
                discode(token, text, None)
            elif platform == 4:
                consumer_key = new_users[user_name]['consumer_key']
                consumer_secret = new_users[user_name]['consumer_secret']
                token_secret = new_users[user_name]['token_secret']
                tweet(consumer_key, consumer_secret, token, token_secret, text,
                      None)

        json_write(self.cache_file_path, self.users)