Discord webhook

Votes

Upvotes

1

Upvotes: 1

Downvotes

0

Downvotes: 0

Net votes

+1

Prompt

python要怎麼用discord的webhook做提醒

Response

你可以把 Discord webhook 當成「一個可被 HTTP POST 呼叫的網址」,Python 到時間就打這個網址送訊息,就完成「提醒」。

1) 先拿到 Webhook URL(Discord 端)

在你要收提醒的頻道: Channel Settings → Integrations → Webhooks → Create Webhook → Copy Webhook URL

Webhook 本質就是可以直接發訊息到該頻道的入口(不用 bot token)。(Discord Documentation) (Webhook URL 當密碼保管,別貼公開。)

2) 最小可用:Python 發一則提醒訊息

安裝套件:

pip install requests

程式(send_webhook.py):

import os
import requests

WEBHOOK_URL = os.environ["DISCORD_WEBHOOK_URL"]

def send_reminder(text: str):
    payload = {
        "content": text,                      # 文字訊息(最多 2000 字)
        "username": "Reminder",               # 可選:覆蓋 webhook 名稱
        "allowed_mentions": {"parse": []},    # 防止不小心 @everyone/@here
    }
    r = requests.post(WEBHOOK_URL, json=payload, timeout=10)
    r.raise_for_status()

if __name__ == "__main__":
    send_reminder("⏰ 提醒:去喝水 / 起來動一動!")

執行:

export DISCORD_WEBHOOK_URL="https://discord.com/api/webhooks/...."
python send_webhook.py

官方文件也有說:送訊息時至少要提供 contentembeds 等其中一種,而且 content 上限 2000 字、embeds 一次最多 10 個。(Discord Documentation)

3) 真的「到時間提醒」:用 APScheduler 排程

安裝:

pip install requests apscheduler

每天 09:00(台北時間)提醒一次(reminder_cron.py):

import os
import requests
from datetime import datetime
from zoneinfo import ZoneInfo
from apscheduler.schedulers.blocking import BlockingScheduler

WEBHOOK_URL = os.environ["DISCORD_WEBHOOK_URL"]

def send(text: str):
    payload = {
        "content": text,
        "username": "Reminder",
        "allowed_mentions": {"parse": []},
    }
    r = requests.post(WEBHOOK_URL, json=payload, timeout=10)
    r.raise_for_status()

def job():
    now = datetime.now(ZoneInfo("Asia/Taipei"))
    send(f"⏰ 每日提醒:現在是 {now:%Y-%m-%d %H:%M}(台北)")

if __name__ == "__main__":
    sched = BlockingScheduler(timezone="Asia/Taipei")
    sched.add_job(job, "cron", hour=9, minute=0)
    sched.start()

4) 小技巧:讓時間自動顯示成每個人的時區

Discord 支援動態時間戳:

  • <t:UNIX:R> 顯示「相對時間」(例如:in 2 hours)
  • <t:UNIX:f> 顯示完整日期時間

這樣提醒貼出去,每個人看到的時間會自動換成本地時區。(Gist)

5) 注意:Webhook 只能「發送」,不能互動收回覆

Webhook 主要就是單向輸出;如果你要做指令互動/收使用者回覆,通常要做 bot。(Discord)

如果你跟我說你想要的提醒型態(例如:一次性倒數 30 分鐘、每天固定時間、或讀你的 TODO 清單逐條提醒),我可以直接把完整腳本整理成一個可跑的檔案(含設定檔/環境變數/systemd 或 cron 範例)。

Comments

Login to add a comment.

No comments yet.