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

Discord.py机器人:如何返回随机颜色图片而非RGB数值

实现Discord机器人返回随机颜色图片的方法
  • 先安装依赖库:pip install pillow
  • 修改指令逻辑,通过Pillow生成纯色图片并作为附件发送

完整代码示例

import discord
from discord.ext import commands
import random
from PIL import Image
import io

# 初始化机器人,根据实际前缀和意图调整
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

def random_color():
    return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

@bot.command(name="rcolor")
async def send_random_color(ctx):
    rgb = random_color()
    # 创建150x150的纯色图片,尺寸可自行调整
    color_img = Image.new("RGB", (150, 150), rgb)
    # 将图片写入内存字节流,避免本地文件操作
    img_buffer = io.BytesIO()
    color_img.save(img_buffer, format="PNG")
    img_buffer.seek(0)
    
    # 包装成Discord可发送的附件
    color_file = discord.File(img_buffer, filename="random_color.png")
    # 发送消息,同时带上RGB数值和颜色图片
    await ctx.send(f"随机颜色:{rgb}", file=color_file)

# 替换成你的机器人令牌
bot.run("YOUR_BOT_TOKEN")

关键逻辑说明

  • 用Image.new生成指定尺寸的纯色图片,第二个参数是图片宽高,第三个是RGB元组
  • 通过io.BytesIO将图片数据存在内存中,不需要生成本地文件,更高效
  • 用discord.File包装内存中的图片数据,设置文件名后作为附件发送,Discord会自动显示该图片

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:02:03