Discord.py bot doesn't dm new members - python

I'm using the event on_member_join to attempt to dm new members, but when I tested with my alt, it didn't send a message.
#bot.event
async def on_member_join(member):
embed = discord.Embed(title="Welcome to my server!", description=None, color = discord.Color.magenta())
embed.add_field(name="To get started:", value="•Invite some friends!\n•Check out some of the channels and get engaged with the community!\n•Have fun!", inline=True)
channel = bot.get_channel(803703488499810326)
userDM = member.create_dm()
await userDM.send(embed=embed)

You don't need to do member.create_dm() because when you DM a user it's not needed.
You also don't need to define description to None, you simply don't even need to specify a description.
In order for the bot to even find the members, you need members intent turned on in your bot. You can do that using the image below.
Now, you just need to provide the code in the bot so that the bot can use the intents.
Here is the code that you need to add to your main bot file.
intents = discord.Intents.default() # Gets the default intents from discord.
intents.members = True # enables members intents on the bot.
bot = commands.Bot(command_prefix=prefix, intents=intents)
After all of that here is your fixed code.
#bot.event
async def on_member_join(member):
embed = discord.Embed(title="Welcome to my server!", description=None, color = discord.Color.magenta())
embed.add_field(name="To get started:", value="•Invite some friends!\n•Check out some of the channels and get engaged with the community!\n•Have fun!", inline=True)
await member.send(embed=embed)
I hope this helped, Have a nice day, Best of luck on your bot.
Here is a Discord Server for Beginners.
🔗 Discord.py For Beginners : https://discord.gg/C8zFM3D2rn

Related

How do you give every member in a discord server a role at one time discord.py

I'm trying to give all members in my server a role with this command, but it doesn't seem to work. It doesn't give the role to all the members, but just to the client. It also doesn't show any errors in the console.
#client.command()
async def assignall(ctx, *, role: discord.Role):
await ctx.reply("Attempting to assign all members that role...")
for member in ctx.guild.members:
await member.add_roles(role)
await ctx.reply("I have successfully assigned all members that role!")
Ensure that you have enabled the GUILD_MEMBERS Intent from your Discord Developer Portal and initialized your client with the proper intents.
from discord import Intents
from discord.ext.commands import Bot
client = Bot(intents=Intents.all())
•Go to https://discord.com/developers/applications
•Select your bot
•Go to the bot section
•Scroll down and enable all the intents(Technically you need only server members' intent but if you do all it will help you)
•Replace your client=commands.Bot(command_prefix="your_prefix") to
intents = discord.Intents.default()
intents.message_content = True
client=commands.Bot(command_prefix="your_prefix",intents=intents)

Make discord.py bot react to emoji added in dm

I'm trying to make a simple test bot that could do something when a reaction is added to a message that the bot send to the user dm. Now I'm stuck after the intial trigger that send the dm and add the emoji to react to. Any help to make that work?
import discord
import time
client = discord.Client()
intents = discord.Intents.default()
intents.members = True
#client.event
async def on_ready():
print("testing")
#client.event
async def on_raw_reaction_add(payload):
message_id = payload.message_id
if message_id == 968972405206827028:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
if payload.emoji.name == '✅':
role = discord.utils.get(guild.roles, name='role')
user = await client.fetch_user(payload.user_id)
embedVar = discord.Embed(title="Some order", description='Welcome to your order, %s \n Please select your payment method of choice:' % (payload.member.name), color=0x00ff00)
dm = await user.send(embed=embedVar)
await dm.add_reaction(some_emoji)
await dm.add_reaction(some_emoji)
client.run("MY_TOKEN")
Your code is trying to get a particular guild from the payload guild_id attribute, which in a DM doesn't exist.
In discord.py, DMs aren't considered guilds, hence there is no particular ID. If you're setting this system up for a particular server, I'd recommend you use something as client.get_guild(your_id_here), which will give you the Guild object if the bot is in that guild.
In short terms, guild_id is invalid since DMs are not guilds (servers). Find a way to work around that.
My solutions would be:
is it for a specific server? Get the guild by ID and perform your operations
is it for any server? Perhaps use databases to store IDs and perform accordingly
Hope this helps!

Discord Py Bot users Status

#client.event
async def on_ready():
await client.wait_until_ready()
await client.change_presence(activity=Activity(name=f".help auf {len(client.guilds)} Servers",
type=ActivityType.playing))
I want to show the status of the total amount of members. How can I do this?
Axiumin's answer is correct but that requires you to have the intent.members enabled.
An example of enabling it can be done like so
intents = discord.Intents()
intents.all()
client = commands.Bot(command_prefix=".", intents=intents)
#client.event
async def on_ready():
await client.wait_until_ready()
await client.change_presence(activity=Activity(name=f".help auf {len(client.users)} Users", type=ActivityType.playing))
You will have to enable it here. Select the application you want it on -> Select Bot -> SERVER MEMBERS INTENT and then make sure it shows blue next to it. Then click Save Changes. Since you are developing your bot you might want to enable Presence intent as well to save you time later.
However, if your bot is not allowed it(if your bot is in 100+ servers and discord rejected it's request) you can get around this by doing:
#client.event
async def on_ready():
await client.wait_until_ready()
total_members = 0
for guild in client.guilds:
total_members += guild.member_count
await client.change_presence(activity=Activity(name=f".help auf {total_members} members", type=ActivityType.playing))
NOTE: This counts the total amount of users in all servers the bot is in, not how many are using the bot at that time. In order to do that, you'd have to use a counter and increment it each time a new user uses the bot, which I won't go into unless that's what you're trying to do.
This should work: len(client.users). You'd use it in your change_presence code like this:
await client.change_presence(activity=Activity(name=f".help auf {len(client.users)} Users", type=ActivityType.playing))

discord.py join message embed not getting sent

I was just trying to code a welcome message for new members who join the server. I wanted to send an embed everytime a new member joins. However, the embed is not getting sent. Could someone please help me out?
This is my code:
async def on_member_join(member):
mention = member.mention
guild = member.guild
embed = discord.Embed(title="**New Member Joined!**", description=f"{mention} joined {guild}!", color = discord.Colour.purple())
embed.set_thumbnail(url=f"{member.avatar.url}")
channel = discord.utils.get(member.guild.channels, id=Channel_ID)
await channel.send(embed=embed)
Thanks!
In the new version of discord.py(1.5.x), there're some updates about Intents. Intents are similar to permissions, you have to define Intents to get channels, members and some events etc. You have to define it before defining the client = discord.Bot(prefix='').
import discord
intents = discord.Intents().all()
client = discord.Bot(prefix='', intents=intents)
Also, you have to activate Intents from your bot application in Discord Developer Portal.
If you want to get more information about Intents, you can look at the API References.

How to read reactions from a DM channel on discord using discord.py

While programming a discord bot, I realized that I needed to read reactions that the bot dmed to different users.
Code:
#client.event
async def on_reaction_add(reaction, user):
channel = reaction.message.channel
await channel.send('{} has added {} to the message: {}'.format(user.name, reaction.emoji, reaction.message.content))
This reads a message from basically any channel that the bot is in (e.g. in guilds), as opposed to just DM channels. Is there a fix for this?
Thanks in advance
I came to this realization just before so I'll add it as an answer.
You can just use isinstance to check the channel type as dpy has different internal class's for all channels.
#bot.event
async def on_reaction_add(reaction, user):
if not isinstance(reaction.message.channel, discord.DMChannel):
# Not a dm
return
print("Hey this should be a dm")
That code will only ever run in dms.
Alternately, you could remove the not and put your dm code within the if statement

Categories

Resources