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

如何用Python Requests获取Discord DM ID并实现DM接收Webhook通知

实现Discord私信监控与通知的Python方案

前提准备

  • 你的Discord用户Token(注意:绝对不要分享给任何人,泄露会导致账号被盗)
  • 预警服务器的Webhook URL

代码实现

import requests
import time
from typing import List

# 配置参数
DISCORD_TOKEN = "你的Discord用户Token"
WEBHOOK_URL = "你的预警服务器Webhook地址"
CHECK_INTERVAL = 10  # 检测间隔(秒),不要设太频繁避免被限流

# 请求头配置
headers = {
    "Authorization": DISCORD_TOKEN,
    "Content-Type": "application/json"
}

def get_all_dm_channel_ids() -> List[str]:
    """获取所有已存在的私信频道ID"""
    dm_ids = []
    url = "https://discord.com/api/v9/users/@me/channels"
    while url:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        data = response.json()
        # 筛选一对一私信频道(排除群聊)
        for channel in data:
            if channel["type"] == 1:
                dm_ids.append(channel["id"])
        # 处理分页结果
        url = response.links.get("next", {}).get("url")
    return dm_ids

def send_webhook_notification(channel_id: str, username: str):
    """通过Webhook发送新私信通知"""
    payload = {
        "content": f"⚠️ 收到新私信!私信频道ID:`{channel_id}`,发信人:*{username}*"
    }
    try:
        requests.post(WEBHOOK_URL, json=payload)
    except Exception as e:
        print(f"发送通知失败: {str(e)}")

def check_new_dms(existing_ids: List[str]) -> List[str]:
    """检测新出现的私信频道"""
    current_ids = get_all_dm_channel_ids()
    new_ids = [cid for cid in current_ids if cid not in existing_ids]
    return new_ids

def get_dm_channel_username(channel_id: str) -> str:
    """获取私信频道对应的对方用户名"""
    url = f"https://discord.com/api/v9/channels/{channel_id}"
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    channel_data = response.json()
    # 提取对方用户信息
    return channel_data["recipients"][0]["username"]

if __name__ == "__main__":
    print("启动私信监控...")
    existing_dm_ids = get_all_dm_channel_ids()
    print(f"已获取初始私信频道数量:{len(existing_dm_ids)}")
    
    while True:
        try:
            new_dms = check_new_dms(existing_dm_ids)
            if new_dms:
                print(f"检测到{len(new_dms)}条新私信")
                for dm_id in new_dms:
                    username = get_dm_channel_username(dm_id)
                    send_webhook_notification(dm_id, username)
                    existing_dm_ids.append(dm_id)
            time.sleep(CHECK_INTERVAL)
        except Exception as e:
            print(f"监控过程出错: {str(e)}")
            time.sleep(CHECK_INTERVAL)

关键说明

  • Token安全:Discord Token等同于账号密码,绝对不要硬编码在公开代码里,建议用环境变量加载(比如os.getenv("DISCORD_TOKEN"))
  • API限流:Discord API有请求频率限制,CHECK_INTERVAL不要设置低于5秒,避免触发限流导致请求失败
  • 频道类型判断:Discord中一对一私信的频道类型为1,代码通过这个筛选排除群聊私信
  • 错误处理:代码加入基础异常捕获,避免单次请求失败导致整个监控进程崩溃

注意事项

  • 该方案依赖Discord用户API,若API端点或权限要求调整,需对应修改代码
  • 请勿用此代码执行违反Discord服务条款的操作,否则可能导致账号封禁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 07:37:08