guild.members not working properly in discord.py - discord.py

I'm tryin to code a Discord bot, and I need to get a list of all the members of a guild. I'm using guild.members for this, but this returns a list with only the bot itself.
Here is the manner I proceed:
class MyClient(discord.client):
async def on_ready(self):
print("The bot is ready!")
async def on_message(self, message):
if message.content.startswith(<name of the command>):
<code of the command>
if message.content.startswith(<name of the command>):
<code of the command>
async def <event>(self, <parameters>):
<code>
client = MyClient()
client.run("<token>")
Does anyone know why this is happening, and how to fix it?

It's probably happening because you didn't enable intents. Discord restricts you from getting some information by default. To change it:
Go to Discord Developer Portal, choose your app, go to "Bot".
Under "Privileged Gateway Intents" you will see "Server Members Intent" - enable it.
Then inside your code add this:
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix="!", intents=intents) #add intents=intents to your client
Now you should be able to get a list with other members too.
Edit:
Change:
client = MyClient()
to:
client = MyClient(command_prefix="!", intents=intents)

Related

Count total guild's bots Discord.py

I am trying to make server info command that also counts bots that are in the current server. I tried doing something like that:
#bot.command(name="serverinfo")
async def serverinfo(ctx: commands.Context):
await ctx.send(ctx.guild.bot_count)
But guild object doesn't have attribute bot_count.
bot_count is not a predefined attribute to guilds in discord.py so you kind of have to create something for that yourself. This can be done by iterating through all the server members and checking to see if each member is a bot account or not. Below is how I would attempt to do so.
import discord
from discord.ext import commands
BOT_TOKEN = "BOT TOKEN HERE"
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix = "$", intents = intents)
#bot.command(name="serverinfo")
async def serverinfo(ctx: commands.Context):
bot_counter = 0
for member in ctx.guild.members: # Iterate through all the members in the server
if member.bot: # Checking to see if the member is a bot account or not
bot_counter += 1
await ctx.send(bot_counter)
bot.run(BOT_TOKEN)
Note: In order to use the guild.members attribute, you will need to have intents.members enabled on your bot and as well as defined in your code.
You can see all the attributes the guild object allows you to access through discord.py on their guild object documentation

How do you make a discord bot that send a message if another user send a message? discord.py

Hi I need help in making a bot that can send a message if a specific user send one.
ex.
Arikakate: hi guys
Bot: yo wassup
this is the code i managed to write but doesn't work:
#client.event
async def on_message(message):
me = '<user id>'
if message.author.id == me:
await message.channel.send("yo wassup")
else:
return
It's not working because the ID's are integers, also message.author can be None if you don't have intents.members enabled
#client.event
async def on_message(message):
me = 6817239871982378981
if message.author.id == me:
await message.channel.send('yo wassup')
What are intents?
Discord requires users to declare what sort of information (i.e. events) they will require for their bot to operate. This is done via form of intents.
You can read more about intents here
What are privileged intents?
With the API change requiring bot authors to specify intents, some intents were restricted further and require more manual steps. These intents are called privileged intents.
How do I enable intents?
intents = discord.Intents.default()
bot = commands.Bot(..., intents=intents)
# or if you're using `discord.Client`
client = discord.Client(intents=intents)
How do I enable privileged intents?
intents = discord.Intents.all() # If you want both members and presences
# if you only want members or presences
intents = discord.Intents.default()
intents.members = True
Also make sure to enable privileged member intents in the developer portal. here's how
Creating a command that checks if the author of the message id is '2130947502309247'.
If it isn't the bot sends a message that says "That id does not belong to you", if the id does belong to the author the bot says "That id belong to you"
#client.command()
async def test(ctx):
if ctx.author.id != 2130947502309247:
await ctx.send("That id does not belong to you")
else:
await ctx.send("That id belong to you")
Quite simple

How to make a Reaction role command with discord.py

So I'm trying to make a Reaction role via discord.py but i don't know how to do it. Also there is no tutorial on YT, I want the bot to send a message and react to that message so the user when react to that get the role.
Okay,
This uses cogs and a bot instead of a client.
message = await ctx.send(" Click the ✅ reaction to verify yourself")
This piece sends the message (You can change it to whatever you want).
if not get(ctx.guild.roles, name="Verified"):
perms = discord.Permissions()
perms.general()
perms.text()
perms.voice()
await ctx.guild.create_role(name="Verified", permissions=perms, colour=discord.Colour(0x00bd09))
This piece will just check whever the role exists or not. If it doesnt it will create one.
await message.add_reaction("✅")
This adds this reaction to the message(So the user doesnt have to scroll around for it). If you dont want the bot have the role, you can add a check (If the user is a bot or not) in the on_raw_reaction_add() function.
#commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
guild = self.bot.get_guild(payload.guild_id)
role = discord.utils.get(guild.roles, name="Verified")
await payload.member.add_roles(role, reason="Verified Self", atomic=True)
This is the function to check when someone adds a reaction to the message. We want to use on_raw_reaction_add() instead of on_reaction_add() because the second one check the cache for adding a reaction, and if the thing isnt in chache it wont work. Thus the 1st one is less probable to create problems.
Here's the whole piece.
from discord.ext import commands
from discord.utils import get
import discord
from discord.ext.commands import has_permissions, CheckFailure
class Verification(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command(name='generate_verification', help='Generates verification message')
async def generate_verification(self, ctx):
message = await ctx.send(" Click the ✅ reaction to verify yourself")
verification_message_id = message.id
# Check if Verification role already exists
if not get(ctx.guild.roles, name="Verified"):
perms = discord.Permissions()
perms.general()
perms.text()
perms.voice()
await ctx.guild.create_role(name="Verified", permissions=perms, colour=discord.Colour(0x00bd09))
await message.add_reaction("✅")
#commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
guild = self.bot.get_guild(payload.guild_id)
role = discord.utils.get(guild.roles, name="Verified")
await payload.member.add_roles(role, reason="Verified Self", atomic=True)
def setup(bot):
bot.add_cog(Verification(bot))
If you're creating a verification command, then you probably would like to store the amount of verification messages sent in a file. This would stop people from generating the message a lot of times. To this you also probably want a command to clear the data from the file, so if the adming wants to create the message again he just needs to clear the file.

Discord Bot sending more than one message

So I am creating a simple bot that detects when somebody joins a server and when somebody leaves the server.
I added a command to show people's avatars, but any time I do it, or when somebody joins or leaves, it sends the message more than once.
I've searched and I can't find the problem.
Can you guys help me?
Here's my code
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="?")
#client.event
async def on_ready():
print("Ready")
#client.event
async def on_member_join(member):
channel = discord.utils.get(member.guild.text_channels, name="entradas")
await channel.send(f"{member} is new on the server, everyone say hi")
show_avatar = discord.Embed(color = discord.Color.blue())
show_avatar.set_image(url="{}".format(member.avatar_url))
await channel.send(embed=show_avatar)
#client.event
async def on_member_remove(member):
channel = discord.utils.get(member.guild.text_channels, name="saidas")
await channel.send(f"{member} left the server, press F to pay respects")
#client.command()
async def avatar(ctx, member: discord.Member):
show_avatar = discord.Embed(color = discord.Color.blue())
show_avatar.set_image(url="{}".format(member.avatar_url))
await ctx.send(embed=show_avatar)
You should check if you are running 2 bots.
If you are running your bot on Linux with screen, simply check with
screen -ls
on windows, just check the task-manager and look under something like Python.
It's btw possible to have the same bot running twice.

How To count total number of members on my Discord server by python

i'm trying this code but it is not working
from discord.ext import commands
#commands.command(pass_context=True)
async def myid(ctx):
print(ctx.guild.member_count)
client.run(my token)
can you provide me right code
I found a solution for the problem statement, if we need to find name of total members of our servers. then use this code.
import discord
client = discord.Client()
token = 'your token'
#client.event
async def on_ready():
users = client.users
print(users)
#or
guilds = client.get_guild
for guild in client.guilds:
print(guild.name)
for member in guild.members:
print(member)
client.run(token)
As what Patrick Haugh said, you did not define your client yet. Also, pass_context is no longer needed in discord rewrite.
The most basic code would look something like this:
from discord.ext import commands
client = commands.Bot(command_prefix = 'PREFIX')
#client.command()
async def myid(ctx):
print(ctx.guild.member_count)
client.run('TOKEN')
Where PREFIX is whatever command prefix you want and TOKEN is your bot token
I suggest reading the discord.py documentation for more information
#bot.command()
async def members(ctx):
embedVar = discord.Embed(title=f'There Are {ctx.guild.member_count} Members In This Server', color=0xFF0000)
await ctx.send(embed=embedVar)
This also works but sends in server, not console.

Resources