首页 > 解决方案 > 在 on_ready() 中查找公会 ID - Discord.py

问题描述

我正在尝试在特定时间发送随机事实。它在我实现一个 dict 来保存随机事实之前工作,它现在应该工作,我遇到的唯一问题是我无法访问 on_ready() 事件中的公会 ID。这是我所拥有的:

    async def func(self):
        await bot.wait_until_ready()
        with open('guild_settings.json', 'r') as file:
            guild_settings = json.loads(file.read())
------> guild_id = NEED
        channel = bot.get_channel(guild_settings[guild_id]["random_facts_channel_id"])

        random_messages = guild_settings[guild_id]["random_facts"].value()
        if random_messages is None:
            await channel.send(f"You need to add a fact first.")
        else:
            random_messages = random.choice(random_messages)
            await channel.send(random_messages)

    @commands.Cog.listener()
    async def on_ready(self):
        print("Bot is ready.")

        with open('guild_settings.json', 'r') as file:
            guild_settings = json.loads(file.read())
        # Initializing scheduler
        scheduler = AsyncIOScheduler()
        hour = 12
        minute = 0
        for guild in bot.guilds:
            guild_id = str(guild.id)
            try:
                hour = guild_settings[str(guild_id)]["random_facts_send_time"]["hour"]
                minute = guild_settings[str(guild_id)]["random_facts_send_time"]["minute"]
            except KeyError:
                print(f"{guild_id} has a KeyError with the random fact feature.")
                continue

        # Sends "Your Message" at 12PM and 18PM (Local Time)
        scheduler.add_job(self.func, CronTrigger(hour=hour, minute=minute, second="0"))

        # Starting the scheduler
        scheduler.start()

如果我能够以某种方式获得公会 ID,那么我确信它会正常工作,我只是不知道如何。

编辑:这是我迄今为止的工作

    async def func(self):
        await bot.wait_until_ready()
        with open('guild_settings.json', 'r') as file:
            guild_settings = json.loads(file.read())
        for guild_id in guild_settings:
            channel = bot.get_channel(guild_settings[guild_id]["random_facts_channel_id"])
            if guild_settings[guild_id]["random_facts"] is not None:
                random_facts = []
                for values in guild_settings[guild_id]["random_facts"].values():
                    random_fact = values.split("\n")
                    random_facts += random_fact
                try:
                    random_choice = random.choice(random_facts)
                except IndexError:
                    continue
                await channel.send(random_choice)
   @commands.Cog.listener()
    async def on_ready(self):
        print("Bot is ready.")

        with open('guild_settings.json', 'r') as file:
            guild_settings = json.loads(file.read())
        # Initializing scheduler
        scheduler = AsyncIOScheduler()
        hour = 12
        minute = 0
        for guild in bot.guilds:
            guild_id = str(guild.id)
            try:
                hour = guild_settings[str(guild_id)]["random_facts_send_time"]["hour"]
                minute = guild_settings[str(guild_id)]["random_facts_send_time"]["minute"]
            except KeyError:
                print(f"{guild_id} has a KeyError with the random fact feature.")
                continue

        # Sends "Your Message" at 12PM and 18PM (Local Time)
        scheduler.add_job(self.func, CronTrigger(hour=hour, minute=minute, second="0"))

        # Starting the scheduler
        scheduler.start()

标签: pythonjsonpython-3.xdiscorddiscord.py

解决方案


如果您的机器人仅在一台服务器上,您可以简单地使用discord.utils.get.

async def func(self):
    await bot.wait_until_ready()
    with open('guild_settings.json', 'r') as file:
        guild_settings = json.loads(file.read())
    guild = discord.utils.get(bot.guilds, name="guild's name")
    channel = bot.get_channel(guild_settings[guild.id]["random_facts_channel_id"])

    random_messages = guild_settings[guild.id]["random_facts"].value()
    if random_messages is None:
        await channel.send(f"You need to add a fact first.")
    else:
        random_messages = random.choice(random_messages)
        await channel.send(random_messages)

如果它在多个服务器上,则必须遍历行会并一一发送消息。

async def func(self):
    await bot.wait_until_ready()
    with open('guild_settings.json', 'r') as file:
        guild_settings = json.loads(file.read())
    for guild in bot.guilds:
        channel = bot.get_channel(guild_settings[guild.id]["random_facts_channel_id"])
        random_messages = guild_settings[guild.id]["random_facts"].value()

        if random_messages is None:
            await channel.send(f"You need to add a fact first.")
        else:
            random_messages = random.choice(random_messages)
            await channel.send(random_messages)

推荐阅读