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

如何使用discord.py通过邀请链接获取Discord公会名称、在线人数等信息

用discord.py通过邀请链接获取公会信息

实现逻辑

你之前调用消息的attachments/embeds等属性无法获取数据,是因为邀请对应的公会信息不会直接附带在消息对象中,需要主动调用Discord的邀请解析接口拉取。
首先从消息文本中提取邀请码,再通过discord.py内置的fetch_invite方法拉取邀请详情,必须传入with_counts=True参数才能获取在线人数、总成员数这类统计数据。

完整代码示例

import re
import discord
from discord.ext import commands

# 匹配Discord邀请链接的正则规则
INVITE_PATTERN = re.compile(r'(?:https?://)?(?:www\.)?(?:discord(?:app)?\.(?:com/invite|gg)/)([a-zA-Z0-9]+)')

# 初始化机器人,注意开启所需Intents
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())

@bot.event
async def on_message(message):
    # 跳过机器人自身发送的消息
    if message.author.bot:
        return
    
    # 匹配消息中包含的邀请码
    match = INVITE_PATTERN.search(message.content)
    if match:
        invite_code = match.group(1)
        try:
            # 拉取邀请详情,with_counts参数必须设为True才能获取成员统计数据
            invite = await bot.fetch_invite(invite_code, with_counts=True)
            
            # 提取所需信息
            guild_name = invite.guild.name
            guild_id = invite.guild.id
            guild_icon_url = invite.guild.icon.url if invite.guild.icon else "该服务器未设置头像"
            online_count = invite.approximate_presence_count
            total_member_count = invite.approximate_member_count
            
            # 输出结果示例,可根据需求调整逻辑
            await message.channel.send(
                f"服务器名称:{guild_name}\n"
                f"服务器ID:{guild_id}\n"
                f"头像链接:{guild_icon_url}\n"
                f"在线人数:{online_count}\n"
                f"总成员数:{total_member_count}"
            )
        except discord.NotFound:
            await message.channel.send("该邀请链接已失效")
        except Exception as e:
            await message.channel.send(f"解析邀请失败:{str(e)}")
    await bot.process_commands(message)

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

返回属性对应说明

  • 服务器名称:对应invite.guild.name
  • 服务器ID:对应invite.guild.id
  • 服务器头像链接:对应invite.guild.icon.url(无头像时为None,需做判空处理)
  • 在线成员数:对应invite.approximate_presence_count
  • 总成员数:对应invite.approximate_member_count

注意事项

  • 需要在Discord开发者后台的机器人设置页开启Message Content Intent权限,否则机器人无法读取普通消息的文本内容
  • 不需要机器人加入对应服务器,即可拉取公开邀请的基础信息
  • 邀请链接失效、属于私人频道时会返回404错误,需提前做好异常捕获

内容的提问来源于stack exchange,提问作者Luís Garcia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 05:36:06