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

如何在discord.py中实现用户使用机器人时发送私信更新日志?

在discord.py中触发命令时发送更新日志私信的实现方案

discord.py 提供了 on_command 事件,正好可以满足你的需求——每当用户调用机器人的命令时,这个事件就会被触发。你可以在该事件的处理函数中,向调用命令的用户发送更新日志私信。

基础实现代码

import discord
from discord.ext import commands

# 初始化机器人,开启必要的消息内容意图
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)

# 定义更新日志内容
UPDATE_LOG = """
**机器人v1.2.0更新日志**
- 新增用户反馈收集命令
- 修复了部分命令响应延迟问题
- 优化了私信发送的容错处理
"""

@bot.event
async def on_command(ctx):
    # 获取发起命令的用户
    target_user = ctx.author
    try:
        # 发送更新日志私信
        await target_user.send(UPDATE_LOG)
    except discord.Forbidden:
        # 处理用户关闭私信权限的情况
        await ctx.send("无法向你发送更新日志,请检查是否开启了私信权限。")

# 示例测试命令
@bot.command()
async def test(ctx):
    await ctx.send("测试命令执行成功!")

bot.run("你的机器人TOKEN")

进阶优化:避免重复发送

如果不想用户每次使用命令都收到重复的更新日志,可以维护一个已发送用户的集合,只给用户发送一次:

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)

UPDATE_LOG = """
**机器人v1.2.0更新日志**
- 新增用户反馈收集命令
- 修复了部分命令响应延迟问题
- 优化了私信发送的容错处理
"""

# 存储已发送过更新日志的用户ID
sent_user_ids = set()

@bot.event
async def on_command(ctx):
    user_id = ctx.author.id
    if user_id not in sent_user_ids:
        try:
            await ctx.author.send(UPDATE_LOG)
            sent_user_ids.add(user_id)
        except discord.Forbidden:
            await ctx.send("无法发送更新日志,请开启私信权限。")

@bot.command()
async def test(ctx):
    await ctx.send("测试命令执行成功!")

bot.run("你的机器人TOKEN")

注意:如果机器人重启,sent_user_ids 集合会被清空,若需要持久化记录,可以使用文件、SQLite等数据库存储已发送的用户ID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 08:24:20