You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py实现Webhook定时每小时发送消息方案咨询

实现Discord Webhook每小时发送消息的可行方案

核心:发送Discord消息的函数

先编写基础的消息发送逻辑,通过requests库调用Discord Webhook接口:

import requests

def send_discord_message(webhook_url, message):
    payload = {"content": message}
    try:
        response = requests.post(webhook_url, json=payload)
        response.raise_for_status()  # 捕获HTTP请求错误
        print("消息发送成功")
    except requests.exceptions.RequestException as e:
        print(f"发送失败: {e}")

方法一:用datetime+time实现精准定时

这种方法会计算距离下一个整点的时间,避免循环sleep产生的累计误差:

import time
from datetime import datetime, timedelta

# 替换为你的Webhook地址和消息内容
WEBHOOK_URL = "https://discord.com/api/webhooks/xxx/xxx"
MESSAGE = "这是每小时推送的定时消息"

while True:
    send_discord_message(WEBHOOK_URL, MESSAGE)
    # 计算到下一个整点的等待时长
    now = datetime.now()
    next_hour = now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)
    wait_seconds = (next_hour - now).total_seconds()
    time.sleep(wait_seconds)

方法二:用schedule库简化定时逻辑

schedule是更简洁的定时任务库,先安装依赖:

pip install schedule

然后编写代码:

import schedule
import time
import requests
from datetime import datetime

def send_discord_message(webhook_url, message):
    payload = {"content": message}
    try:
        response = requests.post(webhook_url, json=payload)
        response.raise_for_status()
        print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 消息发送成功")
    except requests.exceptions.RequestException as e:
        print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 发送失败: {e}")

WEBHOOK_URL = "https://discord.com/api/webhooks/xxx/xxx"
MESSAGE = "每小时定时推送的消息"

# 配置每小时执行一次任务
schedule.every().hour.do(send_discord_message, WEBHOOK_URL, MESSAGE)

# 启动任务循环
while True:
    schedule.run_pending()
    time.sleep(1)

注意事项

  • 替换代码中的WEBHOOK_URL为你自己的Discord Webhook地址(在Discord频道设置-集成-Webhooks中创建)
  • 确保脚本持续运行:可以用后台进程工具(如nohup)或把脚本注册为系统服务
  • Discord Webhook有速率限制,每小时发送1条完全在限制范围内,无需担心触发限制

内容的提问来源于stack exchange,提问作者1HC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 16:25:11