---
# System prepended metadata

title: 10/12 Discord Bot 開發(三)

---

# 10/12 Discord Bot 開發(三)

:::info
時間:2023/10/12 21:30 ~ 2023/10/13 00:10
地點:線上會議(Discord)
參與:xiaojie4082、wei、StarLeisure

![](https://hackmd.io/_uploads/HJMR59SZ6.png)
:::

## 本次討論事項
- 定時發布天氣資訊
- ~~使用應用程式指令~~
- 講解選課相關指令

## 定時發布
- 錯誤版本
    ```python
    import discord
    from discord.ext import tasks

    import datetime

    # 創建 Discord intents 物件並啟用訊息內容 (message_content) 的接收
    intents = discord.Intents.default()
    intents.message_content = True

    # 載入環境變數從 .env 檔案中
    load_dotenv()
    # 獲取 Discord 機器人令牌從環境變數
    bot_token = os.getenv("DISCORD_TOKEN")
    # 設置命令前綴和 intents
    bot = commands.Bot(command_prefix='!', intents=intents)

    @bot.event
    async def on_ready():
        # 設定每日 00:00 執行 `send_message()` 函式
        send_message.start()

    @tasks.loop(hours=24)
    # 每天上午 9:00 @tasks.loop(hours=24, time="09:00")
    async def send_message():
        # 發送每日訊息
        await bot.get_channel(channel_id).send("今日日期：" + datetime.datetime.now().strftime("%Y-%m-%d"))

    client.run(bot_token)
    ```
- 修正版
    ```python
    # 匯入 time 模組
    import time
    import datetime
    
    # 匯入 asyncio 模組 (非同步I/O)
    import asyncio 

    # 匯入讀取 .env 檔案的相關套件
    import os
    from dotenv import load_dotenv

    # 匯入 discord.py 套件
    import discord
    from discord.ext import commands, tasks

    # 創建 Discord intents 物件並啟用訊息內容 (message_content) 的接收
    intents = discord.Intents.default()
    intents.message_content = True

    # 載入環境變數從 .env 檔案中
    load_dotenv()
    # 獲取 Discord 機器人令牌從環境變數
    bot_token = os.getenv("DISCORD_TOKEN")
    # 設置命令前綴和 intents
    bot = commands.Bot(command_prefix='&', intents=intents)

    # 時區設定
    utc = datetime.timezone(datetime.timedelta(hours=8))
    # 定時執行
    times = [
        datetime.time(hour=23, minute=10, tzinfo=utc),
        datetime.time(hour=23, minute=11, tzinfo=utc),
        datetime.time(hour=23, minute=12, tzinfo=utc),
        datetime.time(hour=23, minute=13, tzinfo=utc),
        datetime.time(hour=23, minute=14, tzinfo=utc),
    ]

    @tasks.loop(time=times)
    async def background_task():
        channel = bot.get_channel(1158443986294423556)  # 替換成你的頻道 ID
        await channel.send('!!!!!!!')

    @bot.event
    async def on_ready():
        print(f"Logged in as {bot.user}")

        # 開始定時任務
        background_task.start()

    @bot.command()
    async def ping(ctx):
        start = time.time()
        message = await ctx.send('pong...')
        end = time.time()
        latency = (end - start) * 1000
        await message.edit(content=f'{latency:.1f} ms')

    @bot.slash_command(name="ping", description="檢查機器人的延遲") 
    async def ping(ctx): 
        start = time.time()
        message = await ctx.respond('等待中...')
        end = time.time()
        latency = (end - start) * 1000
        await message.edit_original_response(content=f'{latency:.1f} ms')

    bot.run(bot_token)
    ```

## 定時發布天氣資訊
- 添加套件
```python
import datetime
from discord.ext import tasks
```

```python
# 時區設定
utc = datetime.timezone(datetime.timedelta(hours=8))

# 定時執行
times = [
    datetime.time(hour=6, minute=1, tzinfo=utc),
    datetime.time(hour=18, minute=1, tzinfo=utc),
]

@tasks.loop(time=times)
async def weather_background_task():
    weather, info, url = today_weather()
    embed=discord.Embed(title="天氣資訊 (沙鹿區)", description=info, color=0xffffff)
    embed.set_thumbnail(url=url)
    embed.add_field(name="天氣狀況", value=weather[0]["Wx"]["parameterName"], inline=True)
    embed.add_field(name="最高低溫", value=weather[0]["MinT"]["parameterName"] + " ~ " + weather[0]["MaxT"]["parameterName"] + " °C", inline=True)
    embed.add_field(name="降雨機率", value=weather[0]["PoP"]["parameterName"] + " %", inline=True)
    # embed.add_field(name="體感狀態", value=weather[0]["CI"]["parameterName"], inline=False)
    embed.set_footer(text="資料來源：https://opendata.cwa.gov.tw/")
    channel = bot.get_channel(1162046869170573343)
    await channel.send(embed=embed)
```

## 下次會議討論事項
- 10/17 晚上 20:00 Discord Bot 開發(四)
    - 公車資訊
    - 講解選課相關指令
- 10/14 或 15 晚上 20:00 PUHub 網頁(一)
    - 調整統整
