'Discord Bot can only see itself and no other users in guild
I have recently been following this tutorial to get myself started with Discord's API. Unfortunately, when I got the part about printing all the users in the guild I hit a wall.
When I try to print all users' names it only prints the name of the bot and nothing else. For reference, there are six total users in the guild. The bot has Administrator privileges.
import os
import discord
TOKEN = os.environ.get('TOKEN')
client = discord.Client()
@client.event
async def on_ready():
for guild in client.guilds:
print(guild, [member.name for member in guild.members])
client.run(TOKEN)
Solution 1:[1]
As of discord.py v1.5.0, you are required to use Intents
for your bot, you can read more about them by clicking here
In other words, you need to do the following changes in your code -
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
intents = discord.Intents.all()
client = discord.Client(intents=intents)
@client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to the following guild: \n'
f'{guild.name} (id: {guild.id})'
)
# just trying to debug here
for guild in client.guilds:
for member in guild.members:
print(member.name, ' ')
members = '\n - '.join([member.name for member in guild.members])
print(f'Guild Members:\n - {members}')
client.run(TOKEN)
Solution 2:[2]
Enable the server members intent near the bottom of the Bot tab of your Discord Developer Portal:
Change the line
client = discord.Client()
to this:intents = discord.Intents.default() intents.members = True client = discord.Client(intents=intents)
This makes your bot request the "members" gateway intent.
What are gateway intents? Intents allow you to subscribe to certain events. For example, if you set intents.typing = False
your bot won't be sent typing events which can save resources.
What are privileged intents? Privileged intents (like members and presences) are considered sensitive and require verification by Discord for bots in over 100 servers. For bots that are in less than 100 servers you just need to opt-in at the page shown above.
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 | Videro |
Solution 2 |