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

Discord.py无需调用命令即可获取机器人所有服务器全部成员的方案

Discord.py 启动时自动获取全服务器成员的实现方案

核心问题原因

你之前调用失败的核心原因是currency_update是被@client.command()修饰的命令函数,强制要求传入上下文参数ctx,无参调用必然报错。且无需额外将client作为参数传入函数,只要函数定义在client初始化后的作用域内,可直接访问该全局对象。

前置配置要求

除代码中已开启的intents.members外,必须前往Discord开发者门户的对应Bot管理页,在「Privileged Gateway Intents」分类下开启Server Members Intent权限,否则无法获取完整的服务器成员列表。

修改后可运行代码

import discord
from discord.ext import commands
import asyncio

intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix="%", intents = intents)

# 启动锁,避免on_ready事件多次触发导致重复启动任务
task_running = False

async def currency_update_task():
    while True:
        # 直接访问全局client对象读取服务器、成员数据
        for guild in client.guilds:
            for member in guild.members:
                print(member)
        # 间隔1小时执行一次
        await asyncio.sleep(3600)

# 若无需保留原%currency_update命令可直接删除本段
@client.command()
async def currency_update(ctx):
    await ctx.send("成员更新任务已触发")
    await currency_update_task()

@client.event
async def on_ready():
    global task_running
    print("Bot is up and running")
    await check() # 保留你原有的check函数调用
    if not task_running:
        task_running = True
        # 用create_task启动后台任务,不会阻塞后续逻辑
        client.loop.create_task(currency_update_task())

client.run("替换为你的Bot Token")

补充说明

用无限循环替代原有的递归调用逻辑,可避免长时间运行后触发Python递归深度上限报错。如果不需要保留手动触发的命令,直接删除@client.command()修饰的currency_update函数即可,不影响启动自动执行的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 16:51:03