'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 1:[1]
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.
Solution 2:[2]
There is a key difference between the get
and the fetch
methods defined in the Client
class. That difference is: get
returns a cached result by the bot, while fetch
returns an API call, aka a request made that provides global information on the requested item.
This comes with a few downsides.
using fetch
usually returns objects/instances with much less attributes to use since global information is not as much as cached information, which essentially is items that the bot itself can see. In short:
Client.get_channel(some_id) # returns a cached channel, has all the documented attributes
# not the same as below
await Client.fetch_channel(some_id) # returns a channel fetched directly from the API, does lack a few of the documented attributes
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Bimi |