Search code examples
pythondiscorddiscord.py

Why is Guild.get_channel returning a none object sometimes in discord.py


So i got this code, but the get_channel often returns a none object but sometime it replies the discord channel object. Why is this like that? Is there a better way? The script is for showing stats of the server in the channels.

#Checking the channels & Server Stats
@bot.event
async def on_connect():

    while True:
        #Checking the channels
        filename = "/home/pi/discordbot/CCreated.json"
        with open('/home/pi/discordbot/CCreated.json', 'r') as f:
            channels_created = json.load(f)
                
        for content in channels_created['timers']:
            # find raiding
            Guild = bot.get_guild(771495836701425725)
            channel_id = int(content)

            # finds the members ([] when noone is in)
            voice_channel = bot.get_channel(channel_id)
            voice_ch_str = str(voice_channel.members)
            #Testing if someone is in there
            if voice_ch_str == "[]":
                channel_get = bot.get_channel(channel_id)
                await channel_get.delete()

                with open("/home/pi/discordbot/CCreated.json", "r") as f:
                    data = json.load(f)

                    data["timers"].pop(f"{data['timers'][content]['channel_id']}")

                with open("/home/pi/discordbot/CCreated.json", "w") as f:
                    json.dump(data, f, indent=2)

#Server Stats

#Getting User Count
Guild = bot.get_guild(771495836701425725)
member_count = len(Guild.members)  # includes bots
true_member_count = len([m for m in Guild.members if not m.bot])  # doesn't include bots

#Getting Streamer Count
role = Guild.get_role(841596562689097729)
#print(type(role))
#print(len(role.members))
streamer_count = len(role.members)

#Setting the new Stats
streamer_stats = Guild.get_channel(968570363103568012)
await streamer_stats.edit(name=f"\U0001F4CA STREAMER: {streamer_count}")

Solution

  • I fixed it. I put the role check in the member update and "filtered" for the specific role and everytime someone gets it or loses it, it checks how many users the role have and sets then the channel name.

    The User Count is now in on_member_remove /join and everytime this happens the bot checks how many user are on the Server and sets the channel name.