如何为Discord机器人制作可变embed列表并实现随机发送功能
随机Embed发送功能实现方案
以下方案基于最常用的discord.py v2.x版本编写,如果你用的是其他Discord机器人库,逻辑完全通用。
可直接运行的代码示例
import random import discord from discord.ext import commands # 配置Bot权限,注意开启message_content权限 intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix="!", intents=intents) @bot.command(name="随机卡片") async def send_random_embed(ctx): # 逐个定义所有需要用到的Embed对象 embed_1 = discord.Embed( title="今日运势:大吉", description="你今天打游戏把把五杀,喝奶茶全糖不胖", color=discord.Color.gold() ) # 替换为你自己的有效图片直链 embed_1.set_image(url="替换为你的图片1直链") embed_2 = discord.Embed( title="今日运势:中吉", description="你今天外卖会提前送到,抽卡能出四星", color=discord.Color.green() ) embed_2.set_image(url="替换为你的图片2直链") embed_3 = discord.Embed( title="今日运势:小凶", description="你今天喝奶茶会漏糖,打游戏遇演员", color=discord.Color.red() ) embed_3.set_image(url="替换为你的图片3直链") # 将所有Embed存入列表 all_embeds = [embed_1, embed_2, embed_3] # 随机选取一个 target_embed = random.choice(all_embeds) # 发送选中的Embed await ctx.send(embed=target_embed) # 替换为你自己的Bot令牌 bot.run("你的Bot令牌")
常见问题排查
- 确保存入列表的是
discord.Embed类的实例,不要误将配置参数、字典或者字符串放入列表 - 图片链接必须是直链,粘贴到浏览器地址栏打开后只显示图片即为有效,不能是图片所在的网页链接
- 确认你的机器人在对应服务器内拥有「嵌入链接」「发送消息」的权限
- 如果使用Discord.js开发,逻辑完全一致:先构造多个
EmbedBuilder实例存入数组,再通过Math.random()选取后发送即可
内容的提问来源于stack exchange,提问作者OliveOli246
相关产品推荐
相关产品推荐

