---
# System prepended metadata

title: 運彩小幫手-LINEBOT
tags: [LINEBOT, python, project]

---

# 運彩小幫手-LINEBOT
###### tags: `LINEBOT` `python` `project`

[TOC]

## Functions
```graphviz
digraph hierarchy {

		nodesep=1.0 // increases the separation between nodes
		node [color=Red,fontname=Courier,shape=box] //All nodes will this shape and colour
		edge [color=Blue, style=dashed] //All the lines look like this

		運彩小幫手->{賠率計算器 場中賽況}
}
```
1. 賠率計算器
2. 場中賽況


## Tools


## Code
1. ### 計算對沖賠率與下注金額

```python=
import math
import decimal

def calc():
    high_principle = int(input("下注本金 : "))
    high_odds = float(input("下注賠率 : "))

    #計算出可下注的最高金額
    low_principle = high_principle * (high_odds -1)

    #無條件捨去，因為一注為10元
    b = low_principle % 10
    if int(b) != 9 :
        low_principle = low_principle - b
    else:
        low_principle = low_principle - b + 10

    #計算出最少低賠率
    low_odds = high_principle / low_principle + 1
    buy_low_odds =  decimal.Decimal(low_odds).quantize(decimal.Decimal('0.01'),rounding=decimal.ROUND_UP)

    print("------------------------------------")
    print("下注本金：{}".format(high_principle))
    print("下注賠率:{}".format(high_odds))
    print("可下注最高金額：{}".format(low_principle))
    print("可下注最低賠率：{}".format(buy_low_odds))
    print("------------------------------------")
    print("總金額：{}".format(high_principle + low_principle))
    
    return

def main():
    calc()

if __name__ == "__main__":
    main()

```

2. ### 場中賽況
* **Flow chart**
```flow
st=>start: 場中賽況
e=>end: 結束
op=>operation: 資料爬取
io=>inputoutput: 顯示比賽資訊
op2=>operation: 爬取場中投注schedule
io2=>inputoutput: 顯示目前無比賽，顯示今日剩餘的單場場中投注比賽
cond=>condition: 目前場中是否有比賽？

st->op->cond
cond(yes)->io->e
cond(no)->op2->io2->e
```

:::spoiler **Code**

```python=
import json
import requests
import random
from fake_useragent import UserAgent

ua = UserAgent()
user_agent = ua.random
headers = {'user-agent': user_agent}
res = requests.get("https://www.sportslottery.com.tw/api/services/app/LiveGames/GetLiveOnAndRegister?isContainRegister=false", headers = headers)
#print(res.status_code) #顯示網頁回傳狀態
data = res.json()

#Test json file in local
#path = '2.json'
#with open(path,"rb") as f :
    #data = json.load(f)
    #print(data)   #讀取出來的資料型別為dict型

Game_data = data['result']['liveOn']

if len(Game_data) == 0:
    print("目前沒有任何賽事")
else:
    for i in range(len(Game_data)):
        Game_name = Game_data[i]['ln'][0]
        player_one_chinese = Game_data[i]['atn'][0]
        player_one_english = Game_data[i]['atn'][1]
        player_two_chinese = Game_data[i]['htn'][0]
        player_two_english = Game_data[i]['htn'][1]
        player_one_score = Game_data[i]['as'].get('10') #當局分數 ex:tennis 
        player_two_score = Game_data[i]['hs'].get('10') #當局分數 ex:tennis
        
        print("\n" + Game_name)
        print("{} : {}".format(player_one_chinese,player_two_chinese))
        for b in range(len(Game_data[i]['as'])):
            b = b + 1
            player_one_as = Game_data[i]['as'].get(str(b))
            if player_one_as == -1 :
                break
            else:
                player_two_hs = Game_data[i]['hs'].get(str(b))
                print("第{}局 {} : {}".format(b, player_one_as, player_two_hs))
        
        #網球
        if Game_data[i]['si'] == 445:
            print("{} : {}".format(player_one_score, player_two_score))
        
        #動畫連結
        #res1 = requests.get("https://h2h.sportslottery.com.tw/sportradar/zht/h2h.html?matchID={}".format(Game_data[i]['mi']), headers = headers)
        #if res1.status_code == 200:
        #   print(res1)
        
        ball_type = Game_data[i]['si']
        if ball_type == 441:
            time = Game_data[i]['ed']
            print("比賽進行時間：{}".format(time[21:23]))
```
:::

:::spoiler **LINEBOT code**
```python=
def game_processing(event):
    try:
        ua = UserAgent()
        user_agent = ua.random
        headers = {'user-agent': user_agent}
        res = requests.get("https://www.sportslottery.com.tw/api/services/app/LiveGames/GetLiveOnAndRegister?isContainRegister=false", headers = headers)
        #print(res.status_code) #顯示網頁回傳狀態
        data = res.json()
        Game_data = data['result']['liveOn']

        if len(Game_data) == 0:
            text4 = "目前沒有任何賽事"
            message = TextSendMessage(
                text = text4
            )
            line_bot_api.reply_message(event.reply_token,message)
        else:
            message =[]
            for i in range(len(Game_data)):
                Game_name = Game_data[i]['ln'][0] #比賽名稱
                player_one_chinese = Game_data[i]['atn'][0] #中文名字
                #player_one_english = Game_data[i]['atn'][1] #英文名字
                player_two_chinese = Game_data[i]['htn'][0] #中文名字
                #player_two_english = Game_data[i]['htn'][1] #英文名字
                player_one_score = Game_data[i]['as'].get('10') #當局分數 ex:tennis 
                player_two_score = Game_data[i]['hs'].get('10') #當局分數 ex:tennis

                text3 = Game_name  + "\n"
                text3 += player_one_chinese + " : " + player_two_chinese + "\n"
                for b in range(len(Game_data[i]['as'])):
                    b = b + 1
                    player_one_as = Game_data[i]['as'].get(str(b)) #分數
                    if player_one_as == -1 :
                        break
                    else:
                        player_two_hs = Game_data[i]['hs'].get(str(b)) #分數
                        text3 += "第"+ str(b) +"局" + str(player_one_as) + " : " + str(player_two_hs) + "\n"
                
                #if player_one_score != -1:
                if Game_data[i]['si'] == 445: #網球
                    text3 += "當盤分數" + str(player_one_score) + " : " + str(player_two_score) + "\n" #當局分數
                
                if Game_data[i]['si'] == 441: #足球
                    text3 += "目前進行時間 : " + Game_data[i]['ed'][21:23] + " 分鐘\n" #目前進行時間

                res1 = requests.get("https://h2h.sportslottery.com.tw/sportradar/zht/h2h.html?matchID={}".format(Game_data[i]['mi']), headers = headers)
                if res1.status_code == 200 :
                    text3 += "場中動畫連結\n"
                    text3 += "https://h2h.sportslottery.com.tw/sportradar/zht/h2h.html?matchID=" + str(Game_data[i]['mi']) + "\n"
                message0 = TextSendMessage(
                    text=text3
                )
                message.append(message0)
            line_bot_api.reply_message(event.reply_token,message)
    except:
        message1 = [
            StickerSendMessage(
                package_id='2',
                sticker_id='161'
            ),

            TextSendMessage(
                text = "工程師正在修復中"
            )
        ]
        line_bot_api.reply_message(event.reply_token, message1)
```
:::