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

Python开发Discord bot实现指令发送带图消息功能故障修复咨询

问题修复方案

核心故障原因

  • 你同时创建了discord.Client和commands.Bot两个独立的运行实例,最终仅启动了client,所有通过bot注册的指令完全不会被触发
  • commands.Bot本身是discord.Client的子类,无需额外创建Client实例,所有功能可统一通过commands.Bot实现
  • 若使用discord.py 2.x及以上版本,需要手动开启消息内容意图,否则无法读取非斜杠指令的消息内容
  • 自定义on_message事件后没有添加指令处理逻辑,会导致所有注册的前缀指令被拦截失效

修复后完整代码

import discord
import os
from replit import db
from discord.ext import commands
import datetime as dt

# 开启必要意图,discord.py v2.x必须配置
intents = discord.Intents.default()
intents.message_content = True
intents.members = True

# 统一使用commands.Bot实例,同时支持!和$前缀,适配原有$hello指令
bot = commands.Bot(command_prefix=['!', '$'], intents=intents)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user}')

@bot.event 
async def on_message(message):
    if message.author == bot.user:
        return
    # 原有$hello逻辑保留
    if message.content.startswith('$hello'):
        await message.channel.send('hello!')
    # 必须加这行,否则所有前缀指令会被on_message拦截
    await bot.process_commands(message)

# 测试发送本地图片指令,触发方式!test
@bot.command()
async def test(ctx):
    # 确保image.png上传到Replit代码根目录
    await ctx.send('Working!', file=discord.File('image.png'))

# 你需要的!publish指令,支持文本+上传附件
@bot.command()
async def publish(ctx, *, content=None):
    # 处理用户上传的附件
    files = []
    for attachment in ctx.message.attachments:
        # 转成可发送的File对象
        file = await attachment.to_file()
        files.append(file)
    # 发送内容,没有文本就只发文件,没有文件就只发文本
    await ctx.send(content=content, files=files)

bot.run(os.environ['TOKEN'])

操作注意事项

  1. 先进入Discord开发者平台的Bot管理页面,在「Privileged Gateway Intents」区域开启Message Content Intent权限,否则指令无法被识别
  2. 测试本地图片发送时,需要把image.png上传到Replit的代码根目录,和主代码文件同层级
  3. 如果需要发送网络图片,可直接用嵌入消息实现,示例如下:
@bot.command()
async def send_url_img(ctx):
    embed = discord.Embed()
    embed.set_image(url="你的网络图片直链")
    await ctx.send(embed=embed)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 18:06:03