from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import chromedriver_binary
import re #正規表現モジュール
import time
import sys
import lineNotify as line
import random
import json
import kindle_sqlite
from datetime import datetime as dt
import slackweb
import os
import traceback
import requests
import linecache
import traceback
from pprint import pprint
from webdriver_manager.chrome import ChromeDriverManager



message = ""
person_name = ""
error_count = 0
error_book_titles = []
total_buy_price = 0
total_buy_count = 0
item_count = 0
max_page_num = 0
current_page = 1


#ランダムリスト
l = [3, 4, 5, 6, 7]

keys_json = open('config.json', 'r')
keys = json.load(keys_json)

#任意に変更してください
MAIL_ADDRESS = keys["mail_address"]
PASSWORD = keys["password"]
TARGET_SITE_URL = keys["target_site_url"]
DRIVER_PATH = keys["driver_path"]
PERSON_NAME = keys["person_name"]
BALANCE = keys["balance"]
DATABASE_PATH = keys["database_path"]
SLACK_NOTIFY_FLG = 1
POST_DATABASE_FLG = 1


if('upload_base_url' in keys):
  upload_base_url = keys["upload_base_url"]
else:
  upload_base_url = 'https://koalabo.work'

if('slack_web_url' in keys):
  slack_web_url = keys["slack_web_url"]
else:
  slack_web_url = 'https://hooks.slack.com/services/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'



#キャッシュディレクトリの作成
path = os.getcwd()
tmp_dir_name = 'tmp_data'
os.makedirs(tmp_dir_name, exist_ok=True)

slack = slackweb.Slack(url=slack_web_url)


#WindowsPC用　exeを用意しないとうまくいかない可能性が高い
#driver_path = 'C:\driver\chromedriver.exe'

if __name__ == '__main__':
  # ブラウザーを起動





  message += "★" + PERSON_NAME + "さんスクリプト実行開始：" + dt.now().strftime("%Y-%m-%d %H:%M:%S")
  if SLACK_NOTIFY_FLG == 0:
      try:
        slack.notify(text=message)
      except Exception as e:
        print("slack通知エラー")


  options = Options()
  options.add_argument('--user-data-dir='+ path + '\\' + tmp_dir_name)
  #https://www.cloudgate.jp/ua.php
  #ここにUAを書きます。
  #--user-agent= ***
  if('user_agent' in keys == False):
    options.add_argument('--user-agent=' + keys["user_agent"])

  #ブラウザーでみられるようになる
  # options.add_argument('--headless')
  # Chromeのドライバを得る

  # print(DRIVER_PATH)
  # sys.exit()
  print("★処理をスタートするよ！！")
  print("開始日時：" + dt.now().strftime("%Y-%m-%d %H:%M:%S"))

  #テーブルの作成
  kindle_sqlite.createTablebuyKindleItems()

  # browser = webdriver.Chrome(chrome_options=options)
  # browser = webdriver.Chrome(options=options)
  browser = webdriver.Chrome(ChromeDriverManager().install(),options=options)
  # if DRIVER_PATH == '':
  #   browser = webdriver.Chrome(chrome_options=options)
  # else:
  #   browser = webdriver.Chrome(chrome_options=options,executable_path=DRIVER_PATH)

  try:

    #amazonにアクセス
    print("Amazonアクセス")
    browser.get("https://www.amazon.co.jp/")

    sleep_time = 3
    print(str(sleep_time) + "秒待機")
    time.sleep(sleep_time)
    

    logined_flg = 0
    #ログインできているか確認
    if len(browser.find_elements_by_id('nav-link-accountList-nav-line-1')) == 1:
      if browser.find_element_by_id('nav-link-accountList-nav-line-1').text.find("さん") >= 0:
        print("ログインOK")
        logined_flg = 1


    #ログインできていない場合はログイン処理    
    if logined_flg == 0:
      print("ポイントの確認ができなかったので、多分ログインできていない。、ログインページにいく")
      browser.get("https://www.amazon.co.jp/ap/signin?openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.co.jp%2F%3Fref_%3Dnav_ya_signin&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.assoc_handle=jpflex&openid.mode=checkid_setup&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&")

      sleep_time = 5
      print(str(sleep_time) + "秒待機")
      time.sleep(sleep_time)
      
      if len(browser.find_elements_by_id("ap_email")) == 1:
        email_elem = browser.find_element_by_id("ap_email")
        email_elem.send_keys(MAIL_ADDRESS)

      if len(browser.find_elements_by_id("ap_password")) == 1:
        password_elem = browser.find_element_by_id("ap_password")
        password_elem.send_keys(PASSWORD)

      if len(browser.find_elements_by_xpath("//input[@name='rememberMe']")) == 1:
        browser.find_element_by_xpath("//input[@name='rememberMe']").click()


      if len(browser.find_elements_by_xpath("//input[@id='continue']")) == 1:
        browser.find_element_by_xpath("//input[@id='continue']").click()

        

      sleep_time = 180
      print(str(sleep_time) + "秒待機")
      time.sleep(sleep_time)


      if len(browser.find_elements_by_xpath("//input[@name='password']")) == 1:
        password_elem = browser.find_element_by_xpath("//input[@name='password']")
        password_elem.send_keys(PASSWORD)
        

      else:      
        message += "●error:ログインできませんでした。"      
        # slack.notify(text=message)
        try:
          slack.notify(text=message)
        except Exception as e:
          print("slack通知エラー")

        browser.close()
        sys.exit()

      if len(browser.find_elements_by_xpath("//input[@name='rememberMe']")) == 1:
        browser.find_element_by_xpath("//input[@name='rememberMe']").click()

      if len(browser.find_elements_by_xpath("//input[@id='continue']")) == 1:
        browser.find_element_by_xpath("//input[@id='continue']").click()

      elif len(browser.find_elements_by_xpath("//input[@type='submit']")) == 1:
        browser.find_element_by_xpath("//input[@type='submit']").click()



      sleep_time = 300
      print(str(sleep_time) + "秒待機")
      time.sleep(sleep_time)


      #2段階認証処理で引っかかってしまった場合。
      if len(browser.find_elements_by_xpath("//input[@name='option']")) > 0 :
        print('認証処理')
        browser.find_element_by_xpath("//input[@id='continue']").click()
        sleep_time = 2
        print(str(sleep_time) + "秒待機")
        time.sleep(sleep_time)

      sleep_time = 180
      print(str(sleep_time) + "秒待機。認証処理がある可能性があるので待機")
      time.sleep(sleep_time)
      
    



    print("ポイントの確認処理")
    disp_top_point_flg = 0
    if len(browser.find_elements_by_id('nav-discobar-jppoints-link')) == 1:
      node = browser.find_element_by_id('nav-discobar-jppoints-link')
      print("〇nav-discobar-jppoints-link")

      if len(node.find_elements_by_class_name('nav-b')) > 0:
        current_point_str = node.find_element_by_class_name('nav-b').text
        current_point = int(current_point_str.replace(',', ''))
        print("現在のポイント："+ str(current_point))
        disp_top_point_flg = 1


    elif len(browser.find_elements_by_id('nav-supra')) == 1:
      node = browser.find_element_by_id('nav-supra')
      print("〇nav-supra")

      if len(node.find_elements_by_class_name('nav-b')) > 0:
        current_point_str = node.find_element_by_class_name('nav-b').text
        current_point = int(current_point_str.replace(',', ''))
        print("現在のポイント："+ str(current_point))
        disp_top_point_flg = 1


    if disp_top_point_flg == 0:
      print("ポイントバー表示されていないかも")
      browser.get("https://www.amazon.co.jp/Amazon%E3%83%9D%E3%82%A4%E3%83%B3%E3%83%88/b/?ie=UTF8&node=2632478051")

      sleep_time = 2
      print(str(sleep_time) + "秒待機")
      time.sleep(sleep_time)
      if len(browser.find_elements_by_class_name('point-total-color')) == 1:
        
        current_point_str = browser.find_element_by_class_name('point-total-color').text
        current_point_str = current_point_str.replace(',', '')
        current_point_str = current_point_str.replace('pt', '')
        # print(current_point_str)
        current_point = int(current_point_str)
        # print("現在のポイント："+ str(current_point))


    # time.sleep(50)
    #maxポイント
    #保有ポイントの確認
    balance = int(BALANCE)
    print("現在の最大所持ポイント："+ str(balance))
    sleep_time = 2
    print(str(sleep_time) + "秒待機")
    time.sleep(sleep_time)






    # 1.URLを読み込む&サイトに行く(各Kindle紹介ブログサイト)
    url = TARGET_SITE_URL
    browser.get(url)
    max_page_num = len(browser.find_elements_by_class_name('page_no'))
    if max_page_num == 0:
      max_page_num = 1
    print("最大ページ数：" + str(max_page_num))


    #実際の購入処理を行う
    for page_num in range(max_page_num):

      page_num = page_num + 1
      if page_num > 1:
        #url = "https://vape-start.com/kindle_100cashback/"
        url = TARGET_SITE_URL + "?page=" + str(page_num)


        print(url)
        browser.get(url)
        


      # 2.本リストの配列を作成する
      books = browser.find_elements_by_class_name('row_item_1')
      product_links = []
      #sys.exit()

      i = 1
      # 3.商品リンクを取得
      for node in books:
        product_links.append(node.find_element_by_class_name('btn_amazon').get_attribute("href"))

        #product_links.append('https://www.amazon.co.jp/dp/B007SQUJ7S?tag=maftracking282233-22&linkCode=ure&creative=6339')
        #product_links.append("https://www.amazon.co.jp/dp/B079XXWSL9")

      item_count = len(product_links)
      print(str(item_count) + '件')


      for link in product_links:
        through_flg = 0
        print(str(i) + '/' + str(item_count))


        while True:

          if through_flg == 1:
            break
          else:
            book_point = 0
            current_point = 0
            book_price = 0
            title = ""
            asin = link.split('dp/')[1]

            if '?tag=bookpad-toma-22' or '?tag=bookpad-22' in asin:
              asin = link.split('dp/')[1].split('?')[0]

            #購入済テーブルにすでにあるかどうかチェック
            #if kindle_sqlite.chehckData(asin) == True:
            item = kindle_sqlite.checkItem(asin)

            if item != None:
              print(item[2] + " - テーブルにすでに登録されています。購入済です。")
              through_flg = 1
            else:

              browser.get(link)
              print(link)
              # time.sleep(500)


              #アダルト商品の場合、認証処理をとおす
              if len(browser.find_elements_by_id('a-page')) > 0:
                center_node = browser.find_element_by_id('a-page')

                if center_node.text.find("年齢確認") >= 0:
                  print("年齢確認処理")
                  # time.sleep(500)
                  time.sleep(5)

                  if len(browser.find_elements_by_id('black-curtain-yes-button')) > 0:
                    print("はいボタンを押下します")
                    # time.sleep(100)
                    node = browser.find_element_by_id('black-curtain-yes-button')



                    
                    # browser.execute_script("arguments[0].click();", node.find_element_by_xpath("//input[@type='submit']"))
                    browser.execute_script("arguments[0].click();", node)
                    print("押下しました")
                    time.sleep(5)

                    if len(browser.find_elements_by_id('a-page')) > 0:
                      print("押下しても変わらない場合")
                      adult_link = node.find_element_by_tag_name('a').get_attribute("href")

                      print("直接リンク")
                      print(adult_link)
                      browser.get(adult_link)


                      # node.execute_script("window.scrollTo(0, document.body.scrollHeight);")
                      time.sleep(5)
                      
                      # node.click()

                  # if len(center_node.find_elements_by_tag_name('a')) == 2:
                  #   link_nodes = center_node.find_elements_by_tag_name('a')
                  #   for node in link_nodes:
                  #     message_str = node.text
                  #     print(message_str)
                  #     if message_str.find('はい') >= 0:
                  #       # node.click()
                  #       url = node.get_attribute("href")
                  #       browser.get(url)
                  #       time.sleep(5)
                  #       break

              time.sleep(3)

              if len(browser.find_elements_by_id('ebooksProductTitle')) == 1:
                title = browser.find_element_by_id('ebooksProductTitle').text

              print('■' + str(i)+ '/' + str(item_count) +  ' - ' + str(dt.now().strftime("%Y-%m-%d %H:%M:%S")) + ' - '+ title)



              # 4.今すぐ読むボタンが表示されている場合スルー
              if len(browser.find_elements_by_class_name('read-now-button')) == 1:

                print("既に購入済みのためスルーします。")
                print("保有ポイント:" + str(current_point))
                #すでに購入済
                through_flg = 1

                #データの追加
                book_data = {
                  "asin":asin,
                  "title":title,
                  "price": -1,
                  "point": -1,
                }
                kindle_sqlite.insertData(book_data)

              elif len(browser.find_elements_by_id('one-click-button')) == 1:#1-Clickで今すぐ買うボタンがあれば・・・！

                #現在ポイントの取得
                current_point_get_flg = 0
                while True:
                  if current_point_get_flg == 1:
                    break
                  else:

                    if len(browser.find_elements_by_class_name('balanceSection')) == 1:
                      print("〇balanceSection")
                      node = browser.find_element_by_class_name('balanceSection')
                      
                      current_point_str = node.get_attribute("data-balance-amount").replace('.00', '')
                      current_point_str = current_point_str.replace('.0', '')

                      current_point = int(current_point_str)

                      print(type(current_point))
                      # time.sleep(60)

                      print("現在のポイント："+ str(current_point))
                      current_point_get_flg = 1

                    elif len(browser.find_elements_by_id('nav-discobar-jppoints-link')) == 1:
                      print("nav-discobar-jppoints-link")
                      node = browser.find_element_by_id('nav-discobar-jppoints-link')

                      if len(node.find_elements_by_class_name('nav-b')) == 1:
                        #保有ポイントの確認
                        current_point_str = node.find_element_by_class_name('nav-b').text
                        current_point = int(current_point_str.replace(',', ''))
                        current_point_get_flg = 1
                        print("現在のポイント："+ str(current_point))
                      
                    elif len(browser.find_elements_by_id('nav-supra')) == 1:
                      print("nav-supra")
                      node = browser.find_element_by_id('nav-supra')

                      if len(node.find_elements_by_class_name('nav-b')) == 1:
                        #保有ポイントの確認
                        current_point_str = node.find_element_by_class_name('nav-b').text
                        current_point = int(current_point_str.replace(',', ''))
                        current_point_get_flg = 1
                        print("現在のポイント："+ str(current_point))



                    time.sleep(1)



                #本の価格・ポイントの確認処理
                if len(browser.find_elements_by_id('buybox')) == 1:
                  node = browser.find_element_by_id('buybox')
                  #￥627の購入を希望しますか？ボタンがあった場合,clickさせる
                  if len(node.find_elements_by_class_name('a-expander-inline-header')) == 1:
                    browser.find_element_by_class_name('a-expander-inline-header').click()

                # 4.本の価格の確認
                if len(browser.find_elements_by_class_name('kindle-price')) == 1:
                  node = browser.find_element_by_class_name('kindle-price')
                  print(node.text)
                  if len(node.find_elements_by_class_name('a-color-price')) > 0:
                    book_price_str = node.find_element_by_class_name('a-color-price').text
                    try:
                      book_price = int(book_price_str.replace('￥', '').replace('(税込)', '').replace(',',''))
                      print("本の価格：" + str(book_price))
                    except Exception as e:
                      book_price = 0
                      print("本の価格取得できず：" + str(book_price))

                #キャッシュバックポイントの取得
                if len(browser.find_elements_by_class_name('loyalty-points')) == 1:
                  print("loyalty-points")
                  node = browser.find_element_by_class_name('loyalty-points')

                  if len(node.find_elements_by_class_name('a-color-price')) > 0:
                    book_point_str = node.find_element_by_class_name('a-color-price').text
                    book_point = int(book_point_str.replace('ポイント', '').replace(',',''))
                    print("本のキャッシュバックポイントA：" + str(book_point))

                elif len(browser.find_elements_by_id('tmmSwatches')) == 1:
                  print("tmmSwatches")
                  node = browser.find_element_by_id('tmmSwatches')

                  if len(node.find_elements_by_class_name('a-color-price')) > 0 :
                    for child_node in node.find_elements_by_class_name('a-color-price'):
                      if(child_node.text.find('獲得ポイント:') == 0):
                        boot_point_str = child_node.text.replace('獲得ポイント: ', '')
                        boot_point_str = boot_point_str.replace('pt', '')
                        book_point = int(boot_point_str)
                        print("本のキャッシュバックポイントB：" + str(book_point))
                        break                  
                  # print(book_point)

                  if book_point == 0 and len(node.find_elements_by_class_name('extra-message')) > 0 :
                    for child_node in node.find_elements_by_class_name('extra-message'):
                      if(child_node.text.find('獲得ポイント:') == 0):
                        boot_point_str = child_node.text.replace('獲得ポイント: ', '')
                        boot_point_str = boot_point_str.replace('pt', '')
                        book_point = int(boot_point_str)
                        print("本のキャッシュバックポイントC：" + str(book_point))
                        break
                  # print(book_point)

                  

                  if book_point == 0 and len(node.find_elements_by_id('tmm-grid-swatch-KINDLE')) > 0:
                    child_node = node.find_element_by_id('tmm-grid-swatch-KINDLE')
                    if len(child_node.find_elements_by_class_name('slot-extraMessage')) > 0:    
                      slot_node = child_node.find_element_by_class_name('slot-extraMessage')
                      if len(slot_node.find_elements_by_class_name('a-color-price')) > 0:
                        price_node = slot_node.find_element_by_class_name('a-color-price')
                      
                        arr = price_node.text.split('(')
                        if len(arr) > 0:
                          boot_point_str = arr[1]
                          print(boot_point_str)
                          boot_point_str = boot_point_str.replace(')', '')
                          boot_point_str = boot_point_str.replace('pt', '')
                          book_point = int(boot_point_str)

                          print("本のキャッシュバックポイントD1：" + str(book_point))



                  if book_point == 0 and len(node.find_elements_by_class_name('slot-buyingPoints')) > 0:
                    print("slot-buyingPoints")
                    child_node = node.find_element_by_class_name('slot-buyingPoints')
                    boot_point_str = child_node.text.replace('獲得ポイント: ', '')
                    boot_point_str = boot_point_str.replace('(', '')
                    boot_point_str = boot_point_str.replace(')', '')
                    boot_point_str = boot_point_str.replace('pt', '')
                    book_point = int(boot_point_str)
                    print("本のキャッシュバックポイントD2：" + str(book_point))
                  # print(book_point)

                  if book_point == 0 and len(node.find_elements_by_class_name('slot-extraMessage')) > 0:                    
                    print("slot-extraMessage")
                    child_node = node.find_element_by_class_name('slot-extraMessage')

                    boot_point_str = ""
                    arr = child_node.text.split('(')
                    if len(arr) > 0:
                      boot_point_str = arr[1]
                    # boot_point_str = child_node.text.split('(')[1]
                    # print(boot_point_str)
                    # sys.exit()
                    
                    # boot_point_str = boot_point_str.replace('(', '')
                    boot_point_str = boot_point_str.replace(')', '')
                    boot_point_str = boot_point_str.replace('pt', '')
                    boot_point_str = boot_point_str.replace('で購入', '')
                    book_point = int(boot_point_str)
                    print("本のキャッシュバックポイントE：" + str(book_point))
                  # print(book_point)
                  

                  # time.sleep(150)
                else:
                  print("ポイント取得できず")


                # time.sleep(300)

                #ポイントを使うチェックがついているか。ついていなかったらチェックを入れる
                print("ポイントを使うチェックがついているか。ついていなかったらチェックを入れる")
                if len(browser.find_elements_by_id('balance-checkbox-0')) > 0:
                  check_node = browser.find_element_by_id('balance-checkbox-0')
                  if check_node.get_attribute("checked") == 'false':

                      print("ポイントを使うにチェックが入っていなかったため、チェックつけます。")
                      browser.execute_script("arguments[0].click();",check_node)
                      #check_node.click()だとうまくいかない。
                  else:
                    print("ポイント使用チェックOK")
                else:
                  print("チェックボックスが見当たらず。予期せぬエラーです")


                    





                if len(browser.find_elements_by_id('youPayValue')) == 1:
                  #ご請求金額の確認
                  you_pay_value_str = browser.find_element_by_id('youPayValue').text                  
                  print("youPayValue")
                  print(you_pay_value_str)

                  if len(you_pay_value_str) == 0:
                    print("youPayValue取得できなかったので、5秒待機してもう一度取得")
                    print(you_pay_value_str)
                    time.sleep(5)

                  try:
                    you_pay_value_str = you_pay_value_str.replace('￥', '')
                    you_pay_value_str = you_pay_value_str.replace(',', '')
                    you_pay_value = int(you_pay_value_str)
                  except ValueError:
                    print("youPayValueを取得できなかったので、処理をスキップします")
                    you_pay_value = -1

                else:
                  print("find_elements_by_id('youPayValue')が取得できませんが処理を続行します")
                  # time.sleep(180)
                  you_pay_value = -1

                
                # print(you_pay_value)
                # time.sleep(5)


                #購入処理に走る
                if book_price != 0 and book_point != 0 and book_price == book_point and current_point >= book_price and (you_pay_value == 0 or you_pay_value == -1):


                  
                  if len(browser.find_elements_by_id('one-click-button')) > 0:
                    # browser.execute_script("arguments[0].click();", node)
                    # browser.find_element_by_id('one-click-button').click()
                    browser.execute_script("arguments[0].click();", browser.find_element_by_id("one-click-button"))
                  else:
                    print("購入ボタンなし")
                    time.sleep(3)
                    break
                  
                  

                  if len(browser.find_elements_by_id('thankYouMessage')) == 1:
                    total_buy_price = total_buy_price + book_price
                    total_buy_count = total_buy_count + 1
                    through_flg = 1
                    print("購入しました。")

                    #データの追加
                    book_data = {
                      "asin":asin,
                      "title":title,
                      "price":book_price,
                      "point":book_point
                    }
                    kindle_sqlite.insertData(book_data)

                    # ログの処理


                    time.sleep(random.choice(l))

                  elif len(browser.find_elements_by_class_name('flexBoxContent')) > 0 and browser.find_element_by_class_name('flexBoxContent').text.find('注文されています') > 0:

                    print("既に購入済みのためスルーします。(ご注文状況のお知らせ)")
                    print("保有ポイント:" + str(current_point))
                    #すでに購入済
                    through_flg = 1

                    #データの追加
                    book_data = {
                      "asin":asin,
                      "title":title,
                      "price":book_price,
                      "point":book_point
                    }
                    kindle_sqlite.insertData(book_data)
                    time.sleep(2)

                  else:
                    print("想定外のエラーが発生しました。")
                    print("パスワード入力を求められたら、入力して、OKを押してください")
                    time.sleep(100)
                    break
                    
                elif you_pay_value == 0:
                  
                  print("ご請求金額が0円ではないため、購入しません")
                  through_flg = 1

                  # time.sleep(100)

                #保有最大ポイントより本の価格が高い = ポイントをチャージしないと買えない時
                elif balance < book_price:
                  book_title = browser.find_elements_by_id('ebooksProductTitle').text()
                  error_count += 1
                  error_book_titles.append(book_title)

                  #エラー報告(LineNotify)
                  #driver = webdriver.Chrome("~/chromedriver")
                  message += "\n\n"
                  message += "ポイントが足りず購入できませんでした。" + "\n"
                  message += "本のタイトル:" + str(book_title) + "\n"
                  message += "金額:"+ str(book_price) + "\n"
                  line.SendMessage(message)

                  through_flg = 1

                  break

                #ポイント還元率が100%でないとき = 買いたくない時
                elif book_price != book_point:

                  print("ポイント還元率が100%でないため購入しません。")
                  print("保有ポイント:" + str(current_point))
                  through_flg = 1

                elif book_price != 0 and book_point != 0 and book_price == book_point and current_point < book_price:
                  print("ポイント復活の時間が必要です。")
                  print("1分間お待ちください。")

                  time.sleep(60)

                else:
                  print("想定外のエラーが発生しました。（Kindleの商品じゃないのかも？？）")
                  through_flg = 1

              else:
                print("ポイント還元率が100%ではないため購入しません。")
                print("保有ポイント:" + str(current_point))
                through_flg = 1
        i = i + 1

    #購入報告
    message += "\n\n"

    if total_buy_count >= 1:

      message += PERSON_NAME + "の今回の購入分！"+ "\n"
      message += "今回購入金額:" + str(total_buy_price) + "\n"
      message += "今回購入冊数:" + str(total_buy_count) + "\n"
      # message += "ご購入いただきありがとうございました!"
      # line.SendMessage(message)


    else:
      message += PERSON_NAME + "の今回の購入分はありませんでした"+ "\n"


    month_total_buy_price = 0
    month_total_buy_count = 0
    cursor = kindle_sqlite.getMonthBuyItems()
    # res = month_total_buy_items.fetchall()
    # print(cursor.fetchall())
    for row in cursor:
      # print(row['price'])
      month_total_buy_price += row['price']
      month_total_buy_count += 1
    


    message += "今月の合計購入金額:" + str(month_total_buy_price) + "\n"
    message += "今月の合計購入冊数:" + str(month_total_buy_count) + "\n"
    
    message += "★" + PERSON_NAME + "さんスクリプト実行終了：" + dt.now().strftime("%Y-%m-%d %H:%M:%S")

    if SLACK_NOTIFY_FLG == 1:

      try:
        slack.notify(text=message)
      except Exception as e:
        print("slack通知エラー")




    #ファイルアップロード
    if POST_DATABASE_FLG == 1:
      file = {'upload_file': open(DATABASE_PATH, 'rb')}
      upload_url = upload_base_url + '/' + 'shop/kindle_items/upload_file'      
      r = requests.post(upload_url, files=file)


  except Exception as e:
    # t, v, tb = sys.exc_info()
    # traceback.print_tb(tb)
    # print(tb)
    exc_type, exc_obj, tb=sys.exc_info()
    lineno = tb.tb_lineno
    print(str(lineno) + ":" + str(type(e)))
    print(str(e))

    error_message = "●ERROR:" + PERSON_NAME + "さんエラー" +"\n"
    error_message += str(lineno) + ":" + str(type(e)) + "\n"
    error_message += str(e)

    if SLACK_NOTIFY_FLG == 1:
      try:
        slack.notify(text=message)
      except Exception as e:
        print("slack通知エラー")



  finally:
    print("処理の終了")

    #ブラウザを終了
    browser.quit()
    

  