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

如何通过外部脚本触发Discord Bot发送私信?求示例代码

实现Discord Bot触发私信功能的示例代码

前提准备

  1. 安装依赖库:pip install discord.py
  2. 在Discord开发者门户中,为你的Bot开启Message Content Intent和Server Members Intent权限,并获取Bot令牌。
  3. 将Bot邀请到你的Discord服务器(发私信不需要服务器权限,但需确保Bot能正常登录)。

方案1:文件触发(适合同机器运行的脚本1和Bot)

通过脚本1写入用户ID到文件,Bot轮询文件并处理私信发送。

Discord Bot 代码

import discord
from discord.ext import commands
import asyncio
import os

# 配置Bot意图
intents = discord.Intents.default()
intents.message_content = True
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)
# 存储待处理用户ID的文件路径
PENDING_FILE = "pending_users.txt"

@bot.event
async def on_ready():
    print(f"Bot已登录:{bot.user}")
    # 启动轮询任务
    bot.loop.create_task(check_pending_tasks())

async def check_pending_tasks():
    while True:
        if os.path.exists(PENDING_FILE):
            # 读取并清空文件
            with open(PENDING_FILE, "r") as f:
                user_ids = [line.strip() for line in f if line.strip()]
            open(PENDING_FILE, "w").close()

            # 逐个处理用户ID
            for user_id_str in user_ids:
                try:
                    user_id = int(user_id_str)
                    user = await bot.fetch_user(user_id)
                    # 发送包含用户ID的私信
                    await user.send(f"您好!您的Discord用户ID是:{user_id}")
                    print(f"已成功发送私信给用户 {user_id}")
                except discord.NotFound:
                    print(f"错误:未找到用户ID {user_id_str}")
                except discord.Forbidden:
                    print(f"错误:无法向用户 {user_id_str} 发送私信(用户可能屏蔽了Bot或关闭了私信)")
                except ValueError:
                    print(f"错误:无效的用户ID格式 {user_id_str}")
                except Exception as e:
                    print(f"发送私信失败:{str(e)}")
        # 每10秒检查一次文件
        await asyncio.sleep(10)

# 替换为你的Bot令牌
bot.run("YOUR_BOT_TOKEN")

脚本1 代码(任务完成后触发)

import os

def main():
    # --- 这里是脚本1的任务逻辑 ---
    # 假设任务完成后获取到目标用户的ID、名称/标签
    target_user_id = "123456789012345678"  # 替换为实际获取的用户ID
    # ---------------------------

    # 将用户ID写入文件,触发Bot处理
    with open("pending_users.txt", "a") as f:
        f.write(f"{target_user_id}\n")
    print(f"已触发Bot向用户ID {target_user_id} 发送私信")

if __name__ == "__main__":
    main()

方案2:HTTP接口触发(适合跨机器或需要实时触发的场景)

通过在Bot中搭建一个简单的HTTP接口,脚本1发送请求触发私信发送。

Discord Bot 代码(带HTTP接口)

import discord
from discord.ext import commands
from fastapi import FastAPI
import uvicorn
import asyncio

intents = discord.Intents.default()
intents.message_content = True
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)
app = FastAPI()

# 定义触发私信的接口
@app.post("/send_dm")
async def send_dm(user_id: str):
    try:
        user_id = int(user_id)
        user = await bot.fetch_user(user_id)
        await user.send(f"您好!您的Discord用户ID是:{user_id}")
        return {"status": "success", "msg": f"已向用户 {user_id} 发送私信"}
    except discord.NotFound:
        return {"status": "error", "msg": f"未找到用户ID {user_id}"}
    except discord.Forbidden:
        return {"status": "error", "msg": f"无法向用户 {user_id} 发送私信"}
    except ValueError:
        return {"status": "error", "msg": f"无效的用户ID格式"}
    except Exception as e:
        return {"status": "error", "msg": str(e)}

@bot.event
async def on_ready():
    print(f"Bot已登录:{bot.user}")
    # 启动HTTP服务
    loop = asyncio.get_event_loop()
    loop.create_task(uvicorn.run(app, host="0.0.0.0", port=8000))

# 替换为你的Bot令牌
bot.run("YOUR_BOT_TOKEN")

脚本1 代码(通过HTTP请求触发)

import requests

def main():
    # --- 脚本1任务逻辑 ---
    target_user_id = "123456789012345678"
    # -------------------

    # 发送请求到Bot的接口
    resp = requests.post("http://localhost:8000/send_dm", params={"user_id": target_user_id})
    print(resp.json())

if __name__ == "__main__":
    main()

注意事项

  • 确保Bot令牌保密,不要泄露到公共代码库中。
  • 如果使用HTTP接口,注意防火墙设置,避免未授权的请求触发Bot。
  • 若用户关闭了“允许来自服务器成员的私信”或屏蔽了Bot,Bot将无法发送私信。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:21:02