1

I'm trying to make a random fact send at certain times. It worked before I implemented a dict to hold the random facts and it should work now, the only problem I'm running into is I can't access the guild id inside the on_ready() event. Here is what I have:

    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()

If I were able to somehow get the guild id then I'm sure it would work correctly, I just can't figure out how.

EDIT: This is what I have working so far

    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()
5
  • Try using the loop function built into Cogs
    – user12171726
    Nov 15, 2020 at 7:28
  • Like looping through the guild id's in the dict?
    – MrMetacom
    Nov 15, 2020 at 8:45
  • Is it a private bot? Dec 29, 2020 at 20:17
  • Is your bot in only one server or is it on multiple servers?
    – Nurqm
    Dec 29, 2020 at 22:28
  • Don't do extensive code in on_ready: Discord has a high chance to completely disconnect you during the READY or GUILD_CREATE events (1006 close code) and there is nothing you can do to prevent it. It can also be called multiple times. You should use tasks
    – Buster
    Jan 1, 2021 at 12:20

3 Answers 3

3

If your bot is on only one server, you can simply get the guild object by using 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)

If it's on multiple servers, you have to loop through the guilds and send the messages one by one.

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)
5
  • I previously tried for guild_id in guild_settings: but that sent the random fact twice since the bot was added to two servers. In other words the number of servers the bot is in it send the fact that many times to all the servers that don't have an empty random facts list.
    – MrMetacom
    Dec 31, 2020 at 1:18
  • Have you tried the code in the answer? This is supposed to work. This code should not send as many messages as the guild count unless you add the same guild more than once.
    – Nurqm
    Dec 31, 2020 at 1:27
  • in random_messages = guild_settings[guild_id]["random_facts"].value() it says Unresolved reference 'guild_id'
    – MrMetacom
    Dec 31, 2020 at 1:39
  • I edited the answer. Just put . instead of _ in guild_id.
    – Nurqm
    Dec 31, 2020 at 2:34
  • My fault I realized I added hour and minute it's sent from a dict and had the scheduler running inside the for loop getting the guild ID in the on_ready() as well, which is why it was sending two facts instead of one. I've edited my original post and will confirm if this works for sure or not when it sends next.
    – MrMetacom
    Dec 31, 2020 at 2:36
2
+50

As @ŁukaszKwieciński said, you can just do this:

async def func():
    for guild in client.guilds:
        print(guild.id) #Do something with each ID

Or you can waste time and memory doing this (which was my initial approach 😔):

guildIDs = set()

@client.event
async def on_ready():
    for guild in client.guilds:
        guildIDs.add(guild.id)

@client.event
async def on_guild_join(guild):
    guildIDs.add(guild.id)

@client.event
async def on_guild_remove(guild):
    guildIDs.remove(guild.id)

guildIDs is an integer set that will contain all the IDs of all the guilds that the bot is present in. The reason I used a set is to prevent repetition of IDs.

You can then use each ID in a function like this:

async def func():
    for guildID in guildIDs:
        print(guildID) #Do something with each ID
3
  • or you can simply use client.guilds Dec 30, 2020 at 13:45
  • 1
    @ŁukaszKwieciński damn... I feel stupid now... 🤦
    – Sujit
    Dec 30, 2020 at 13:47
  • 1
    @ŁukaszKwieciński yeah, I added that to my answer.
    – Sujit
    Dec 30, 2020 at 13:51
0

I recommend using tasks extension of discord.py

If you'd like to get the code, here it is.

    @tasks.loop(hours=10)
    async def func():
        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)

    @tasks.loop(minutes=15)
    async def update_interval():
        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
        func.cancel()
        func.change_interval(hours=hour, minutes=minute)

I hope this is helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.