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
Related
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)
I want to make a command for my bot in which we can configure the welcome message the bot can send. So, the configuration works like so: nb welcome <#channel_where_welcome_msg_to_be_shown> <#channel_to_be_mentioned_in_the_welcome_msg>.
The expected output being an embed where it is written
Hello <member>! Pls go to <#channel_to_be_mentioned_in_the_welcome_msg> to choose your roles.
Here is my code:
#client.command(aliases = ["welcome"])
async def _welcome(ctx, channel : discord.TextChannel, roles : discord.TextChannel = None):
global channel_welcome
global role_welcome
channel_welcome = channel
if roles != None:
role_welcome = roles
else:
role_welcome = None
await ctx.send("Ok, welcome message configured!")
#client.event
async def on_member_join(member):
global channel_welcome
global role_welcome
pfp = member.avatar_url
if role_welcome == None:
embedVar = discord.Embed(title="WELCOME!",description = "{}, you are welcome to this server!" . format(member.mention), color = 0xff9900)
embedVar.set_thumbnail(url = pfp)
await client.getchannel(channel_welcome).send(embed = embedVar)
else:
embedVar = discord.Embed(title="WELCOME!",description = "{}, you are welcome to this server! Go to {} to assign yourself some roles." . format(member.mention, role_welcome.mention), color = 0xff9900)
embedVar.set_thumbnail(url = pfp)
await client.getchannel(channel_welcome).send(embed = embedVar)
So, the welcome command is the configuration command. As you can see, the roles argument is optional and the user can use it if he/she wants.
Whenever I run the code and someone joins the server, it doesn't send the message or raises any error.
Any suggestions of how to fix this?
The reason why the bot does not react when a user joins, is probably because you did not define the appropriate intents for the bot.
First of all, you need to go to the Discord Developer Portal and enable the Server Members Intent
Now in the code, you need to define the intents
import discord
from discord.ext import commands
intents = discord.Intents().default()
intents.members = True
client = commands.Bot(prefix = "your_prefix", intents = intents)
This will allow the bot to listen to the on_member_join events.
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
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.
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.