---
# System prepended metadata

title: 10/21 Discord Bot 開發(五)

---

# 10/21 Discord Bot 開發(五)

:::info
時間：2023/10/21 21:00 ~ 2023/10/22 02:15
地點：線上會議(Discord)
參與：xiaojie4082、wei._.614、StarLeisure、SmingXO

![](https://hackmd.io/_uploads/ry8j08-GT.png)
:::

## 本次討論事項
- 添加按鈕 
- 公車資訊

## 添加按鈕
```python!
    button = discord.ui.Button(label="中央氣象局", url="https://www.cwa.gov.tw/V8/C/W/Town/Town.html?TID=6601300")
    view = discord.ui.View()
    view.add_item(button)
    await ctx.interaction.response.send_message(embed=embed, view=view)
```

## 公車資訊
- 運輸資料流通服務平臺
    - [https://tdx.transportdata.tw](https://tdx.transportdata.tw)
- 範例程式
    - https://github.com/tdxmotc/SampleCode/blob/master/Python3/auth_TDX.py
- 資料網址
    ![image.png](https://hackmd.io/_uploads/BkpDSjv76.png)
    - https://tdx.transportdata.tw/api/basic/v2/Bus/EstimatedTimeOfArrival/City/Taichung/162?%24filter=StopUID%20eq%20%27TXG20091%27&%24orderby=StopSequence&%24format=JSON

### 程式碼
```python!
import requests
import json

app_id = ''
app_key = ''

# 162 靜宜大學(校門), 主顧樓, 聖母堂(終), 聖母堂(起)
# 301 靜宜大學(校門), 主顧樓, 靜園餐廳(終), 靜園餐廳(起)
# 368 靜宜大學(校門), 主顧樓, 聖母堂(終), 聖母堂(起)

stop_dict = {'162': ['TXG20091', 'TXG20092', 'TXG20093', 'TXG20094'], '301': ['TXG20091', 'TXG20094','TXG15247','TXG15230'], '368':['TXG24503','TXG24504','TXG24505','TXG24506']} 

auth_url="https://tdx.transportdata.tw/auth/realms/TDXConnect/protocol/openid-connect/token"

def EstimateTime():
    class Auth():

        def __init__(self, app_id, app_key):
            self.app_id = app_id
            self.app_key = app_key

        def get_auth_header(self):
            content_type = 'application/x-www-form-urlencoded'
            grant_type = 'client_credentials'

            return{
                'content-type' : content_type,
                'grant_type' : grant_type,
                'client_id' : self.app_id,
                'client_secret' : self.app_key
            }

    class data():

        def __init__(self, app_id, app_key, auth_response):
            self.app_id = app_id
            self.app_key = app_key
            self.auth_response = auth_response

        def get_data_header(self):
            auth_JSON = json.loads(self.auth_response.text)
            access_token = auth_JSON.get('access_token')

            return{
                'authorization': 'Bearer '+access_token
            }

    try:
        d = data(app_id, app_key, auth_response)     
    except:
        a = Auth(app_id, app_key)
        auth_response = requests.post(auth_url, a.get_auth_header())
        d = data(app_id, app_key, auth_response)
    EstimateTime = {}
    for route, uids in stop_dict.items(): 
        EstimateTime[route] = []
        for uid in uids: 
            url = "https://tdx.transportdata.tw/api/basic/v2/Bus/EstimatedTimeOfArrival/City/Taichung/" + route + "?%24filter=StopUID%20eq%20%27" + uid + "%27&%24orderby=StopSequence&%24format=JSON"
            try:
                data_response = requests.get(url, headers=d.get_data_header())
            except:
                data_response = requests.get(url, headers=d.get_data_header())   

            data = json.loads(data_response.text)
            try:
                EstimateTime[route].append(data[0]["EstimateTime"]/60 + "分鐘")
            except:
                EstimateTime[route].append("-")
    return EstimateTime
```
```python!
@tasks.loop(minutes=1)
async def bus_background_task():
    try:
        Estimate = EstimateTime()
        current_time = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime())
        embed=discord.Embed(title="校園公車站牌資訊", description=
            "校門\n" + 
            ":bus: `162` `" + Estimate["162"][0] + "`\n" +
            ":bus: `301` `" + Estimate["301"][0] + "`\n" +
            ":bus: `368` `" + Estimate["368"][0] + "`\n\n" +

            "主顧樓\n"
            ":bus: `162` `" + Estimate["162"][1] + "`\n" +
            ":bus: `301` `" + Estimate["301"][1] + "`\n" +
            ":bus: `368` `" + Estimate["368"][1] + "`\n\n" +

            "聖母堂/靜園餐廳\n"
            ":bus: `162` `" + Estimate["162"][3] + "`\n" +
            ":bus: `301` `" + Estimate["301"][3] + "`\n" +
            ":bus: `368` `" + Estimate["368"][3] + "`\n\n"
        , color=0xfff700)
        embed.set_footer(text="更新時間：" + current_time + "\n" + "資料來源：https://tdx.transportdata.tw")
        message = await bot.get_channel().fetch_message()
        await message.edit(embed=embed)
        # channel = bot.get_channel()
        # await channel.send(embed=embed)
    except Exception as e:
        print(e)
```
### 完成
![](https://hackmd.io/_uploads/r1EZV8fMp.png)

## 下次討論事項
- 期中考暫停兩周討論 Discord Bot 開發(六)
    - 公車查詢
    - 按鈕與定時任務整合