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

Python开发Discord机器人:如何转发私信中的图片至服务器频道?

如何让Discord机器人转发私信中的图片?

我开发了一款Discord机器人,用来接收私信并转发到指定服务器频道,目前文本转发功能正常,但遇到了图片转发的问题:当私信发送图片时,message.content返回空值,机器人无法转发图片。

原文本转发代码

# Post the message into the channel
await server_channel.send(f'**Complaint about the following**\n{message.content}')

解决方法

Discord私信中的图片属于消息附件,需要通过message.attachments属性获取,而不是仅依赖message.content。以下是实现图片转发的代码:

from io import BytesIO
import discord

# 获取目标服务器频道
server_channel = client.get_channel(int(CHANNEL_ID))

if message.attachments:
    # 获取第一个图片附件(可根据需求处理多个附件)
    image_file = message.attachments[0]
    # 读取图片内容为字节流
    image_bytes = await image_file.read()
    # 发送图片到服务器频道
    await server_channel.send(file=discord.File(fp=BytesIO(image_bytes), filename=image_file.filename))

如果需要同时支持文本+图片的混合转发,可以整合逻辑:

from io import BytesIO
import discord

server_channel = client.get_channel(int(CHANNEL_ID))
# 构造文本内容(如果有文本的话)
content = f'**Complaint about the following**\n{message.content}' if message.content else ''

# 处理文本和附件
if message.attachments:
    image_file = message.attachments[0]
    image_bytes = await image_file.read()
    await server_channel.send(content, file=discord.File(fp=BytesIO(image_bytes), filename=image_file.filename))
else:
    await server_channel.send(content)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:40:24