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

如何使用discord.py向机器人所在的所有服务器发送embed消息

discord.py 向所有已加入服务器发送Embed消息实现方案

核心实现逻辑:

  • 首先构造符合需求的discord.Embed实例
  • 遍历客户端实例的guilds属性获取所有已加入的服务器
  • 对每个服务器筛选出机器人拥有发送消息和嵌入链接权限的文本频道发送

可直接运行的代码示例(适配discord.py v2.x版本)

import discord
import asyncio
from discord.ext import commands

# 初始化机器人,需开启对应Intents
intents = discord.Intents.default()
intents.guilds = True
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

@bot.event
async def on_ready():
    print(f"已登录为 {bot.user},当前加入 {len(bot.guilds)} 个服务器")

# 发送Embed的触发指令,默认仅机器人所有者可调用
@bot.command()
@commands.is_owner()
async def send_embed(ctx: commands.Context):
    # 1. 构造Embed实例
    embed = discord.Embed(
        title="通知标题",
        description="这是通知的正文内容,可自定义修改",
        color=discord.Color.green() # 自定义Embed侧边栏颜色
    )
    # 可选:添加字段
    embed.add_field(name="字段标题1", value="字段对应内容1", inline=False)
    embed.add_field(name="字段标题2", value="字段对应内容2", inline=True)
    # 可选:添加页脚、缩略图等
    embed.set_footer(text="自定义页脚内容")
    # embed.set_thumbnail(url="替换为你要使用的缩略图链接")

    send_success = 0
    send_failed = 0

    # 2. 遍历所有已加入的服务器
    for guild in bot.guilds:
        target_channel = None
        # 优先使用服务器默认系统频道
        if guild.system_channel:
            perms = guild.system_channel.permissions_for(guild.me)
            if perms.send_messages and perms.embed_links:
                target_channel = guild.system_channel
        # 无可用系统频道则遍历所有文本频道找第一个有权限的
        if not target_channel:
            for channel in guild.text_channels:
                perms = channel.permissions_for(guild.me)
                if perms.send_messages and perms.embed_links:
                    target_channel = channel
                    break
        
        if target_channel:
            try:
                await target_channel.send(embed=embed)
                send_success += 1
                # 加延迟避免触发Discord速率限制
                await asyncio.sleep(1.2)
            except Exception as e:
                print(f"服务器 {guild.name}(ID:{guild.id}) 发送失败:{str(e)}")
                send_failed += 1
        else:
            print(f"服务器 {guild.name}(ID:{guild.id}) 无可用发送频道")
            send_failed += 1
    
    # 给指令调用者返回结果
    await ctx.send(f"发送完成:成功 {send_success} 个,失败 {send_failed} 个")

bot.run("替换为你自己的机器人Token")

注意事项

  • 机器人需要在Discord开发者后台开启Guilds网关意图,否则无法获取服务器列表
  • 发送Embed必须在目标频道同时拥有发送消息和嵌入链接两个权限,缺一不可
  • 短时间内向大量服务器发送消息会触发速率限制,严重会导致机器人账号被封禁,建议单次发送间隔不低于1秒,大批量发送建议进一步拉长间隔
  • 务必加上调用权限限制,避免被恶意调用发送垃圾信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:15:03