name 'create_dm' is not defined - python

How can I send messages to the users after they got kicked from servers? Whenever I try the following code, it doesn't work properly.
import discord
from discord.ext import commands
intents = discord.Intents(messages=True, guilds=True, reactions=True, members=True,presences=True,guild_messages=True)
client = commands.Bot(command_prefix="!dc ", intents=intents)
#client.event
async def on_ready():
print("I am ready!")
#client.command(aliases=["ban"])
#commands.has_role("admin")
async def ban_user(self,ctx, member: discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f"{member} has been kicked from server.")
dm_channel = await create_dm(member) #These two code lines are where I got this error
await dm_channel.send("You've been banned from the server.You won't join the server until admin opens your ban.")
#commands.command(aliases=["kick"])
#commands.has_role("admin")
async def kick_user(self,ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f"{member} has been kicked from the server.")
client.run(myToken)

According to your question, I am assuming that you want to dm the user who was banned. To do this you can,
async def ban(self, ctx, member: discord.Member, *, reason=None):
await ctx.send(f'{member} has banned from the server.') # sends the message in the server
await member.send(f'You have been banned from {member.guild.name}.') #dms the member that he has been banned.
await member.ban(reason = reason) #bans the user from the server.
Note: If you first ban the member, and then try to send the message in the server and dm, you will get an error as the member would not be found.

You can use the DMChannel function,
the code would look like this:
# put this on top:
from discord import DMChannel
# some stuff
async def ban_user(self, ctx, member: discord.Member=None, *, reason=None):
if member is None:
# if the user don't inform a name to ban, returns this message:
return await ctx.send(f'You need to inform which member you want to ban')
# bans the user from the server:
await member.ban(reason = reason)
# sends the message in the server:
await ctx.send(f'{member} has banned from the server.')
# dm the member
await DMChannel.send(member, f'You have been banned from {member.guild.name}.')

Related

Not able to ban members out of the server .py cog

#commands.command()
#commands.guild_only()
#commands.has_guild_permissions(ban_members=True)
async def ban(self, ctx, member: discord.Member, *, reason=None):
if member.top_role >= ctx.author.top_role:
await ctx.send(f"You can only ban members below your role.")
return
channel = self.bot.get_channel(864083000211406849)
embed = discord.Embed(title=f"{ctx.author.name} banned: {member.name}", description=reason)
await channel.send(embed=embed)
await ctx.send(embed=embed)
await member.send(f"You've been banned from : `{ctx.guild}` for `reason`: {reason}.")
await ctx.guild.ban(user=member, reason=reason)
#ban.error
async def ban_error(self,ctx, error):
if isinstance(error, commands.CheckFailure):
title=f"{ctx.author.mention} you do not have the required permission(s)/role(s) to run this command!"
await ctx.send(title)
So I want my code to basically kick a member that has left my server using their ID. Ive looked in to previous questions but it seems to be no help for me.
You are converting the member input to a discord.Member, which needs to be in the server. Instead convert it to a discord.User, who does not need to be in your server.
async def ban(self, ctx, member: discord.User, *, reason=None):
Please keep in mind that your top role lookup and comparison will not work when you use the discord.User, you will have to get the actual member beforehand, like this:
server_member = ctx.guild.get_member(member.id)
if server_member != None:
if server_member.top_role >= ctx.author.top_role:
await ctx.send(f"You can only ban members below your role.")
return
Also you will get an error trying to message someone who does not share a server with your bot, or has blocked your bot etc., I would just use a try/except block for this:
try:
await member.send(f"You've been banned from : `{ctx.guild}` for `reason`: {reason}.")
except discord.errors.Forbidden:
pass

Discord.py send a dm to a user

So I made a dm command for my bot which works well but I can't dm a user with a space in user name. Does anyone know how to do this?
#client.command(pass_context=True)
#commands.is_owner()
async def dm(ctx, user: discord.User, *, message=None):
message = message or "Message from bot owner"
embed = discord.Embed(title="Message from bot owner", description=message, color = 0)
await user.send(embed = embed)
When I was trying to dm a user with a space for example: =dm Special user#1234 My terminal says that user Special is not found.
You could do
#client.command(pass_context=True)
#commands.is_owner()
async def dm(ctx, user, *, message=None):
if message is None:
await ctx.send("You need to specify the message to send!")
return
user = client.fetch_user(user)
await user.send(embed=discord.Embed(title="Message from bot owner", description=message, color = 0))
In this case, you should have a separate way to define the message variable, since the member variable might take in spaces. Here is how I would define the function:
#commands.command()
async def dm(self, ctx, *, member: discord.Member):
await ctx.send('Enter a message to DM in the chat...')
msg = await self.bot.wait_for('message', check=lambda message: message.author == ctx.author)
await member.send(msg.content)

How do I make a bot where if u react, it will give u a role with python?

so, Ive been doing this:
from discord.ext import commands
from discord.utils import get
client = commands.Bot(command_prefix='><')
#client.event
async def on_ready():
print("I am ready Winson or not Winson :D")
#client.event
async def on_member_join(member):
channel = client.get_channel(744440768667844698)
message = await channel.send(f"Welcome to HaveNoFaith {member}, happy to be friends with you")
#client.command()
async def ping(ctx):
await ctx.send(f"Your Ping is {round(client.latency *1000)}ms")
#client.command()
async def Help(ctx2):
await ctx2.send("Hi, Im WelcomeBot v1.0...\n\nPrefix: ><\n\nCommands: ping\n help")
#and then Im trying to do like at the message "Welcome etc" if they react with the "check reaction" in that message, they will get a role in the discord server...
you can make a command named addrr(add reaction role), which will look like this -
#client.command()
#commands.guild_only()
#commands.has_permissions(administrator=True)
async def addrr(self, ctx, channel: discord.TextChannel, message: discord.Message, emoji: discord.Emoji,
role: discord.Role):
await ctx.send(f"Setting up the reaction roles in {channel.mention}.")
await message.add_reaction(emoji)
def check1(reaction, user):
return user.id is not self.client.user.id and str(reaction.emoji) in [f"{emoji}"]
while True:
try:
reaction, user = await self.client.wait_for("reaction_add", check=check1)
if str(reaction.emoji) == f"{emoji}":
await user.add_roles(role)
await message.remove_reaction(reaction, user)
else:
await message.remove_reaction(reaction, user)
except:
await message.delete()
break
It will work like this -
><addrr <#channel mention> <message ID> <Emoji> <#Role Mention>
So you can add a reaction to the messages that was sended and use wait_for to wait for a reaction on that message. I recommend you to add the timeout. If you dont want to have this timeout, simply just send these message, save it into a list and in the raw_reaction_add event check if the emoji is the one and the message is one of the messages in your list

Discord bot python DM message before kicking

I'm pretty new to discord bots so i wondered if someone here could help me, I wrote a code for kicking and i want to add something that DM's the person before he gets kicked but after the !kick command was given.
#bot.command()
async def kick(ctx, member: discord.Member=None):
if not member:
await ctx.send('Please mention a member')
return
await member.kick()
await ctx.send(f'{member.display_name}\'s was kicked from the server')
You just need to create a dm channel and send the message.
Try adding the two lines below:
#bot.command()
async def kick(ctx, member: discord.Member = None):
if member is None:
await ctx.send(f'{ctx.author.mention} Please mention a member')
return
channel = await member.create_dm() # line 1 create channel
await channel.send('You are getting kicked') # line 2 send the message
await member.kick()
await ctx.send(f'{member.display_name}\'s was kicked from the server')

Discord.py ban command

if message.content.upper().startswith('!BAN'):
if "449706643710541824" in [role.id for role in message.author.roles]:
await
I have the base setup so only admins can ban. I want to make the ban command, but I'm not sure how to do it.
Try this:
import discord #Imports the discord module.
from discord.ext import commands #Imports discord extensions.
#The below code verifies the "client".
client = commands.Bot(command_prefix='pb?')
#The below code stores the token.
token = "Your token"
'''
The below code displays if you have any errors publicly. This is useful if you don't want to display them in your output shell.
'''
#client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Please pass in all requirements :rolling_eyes:.')
if isinstance(error, commands.MissingPermissions):
await ctx.send("You dont have all the requirements :angry:")
#The below code bans player.
#client.command()
#commands.has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *, reason = None):
await member.ban(reason = reason)
#The below code unbans player.
#client.command()
#commands.has_permissions(administrator = True)
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split("#")
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f'Unbanned {user.mention}')
return
#The below code runs the bot.
client.run(token)
I hope this helps, good luck on your bot!
My ban command i got for my bot is , obviously dont keep the comment out for the ban part, I just put that there when i didn't know how to lock it to roles
#bans a user with a reason
#client.command()
#commands.has_any_role("Keyblade Master","Foretellers")
async def ban (ctx, member:discord.User=None, reason =None):
if member == None or member == ctx.message.author:
await ctx.channel.send("You cannot ban yourself")
return
if reason == None:
reason = "For being a jerk!"
message = f"You have been banned from {ctx.guild.name} for {reason}"
await member.send(message)
# await ctx.guild.ban(member, reason=reason)
await ctx.channel.send(f"{member} is banned!")
This is the best one
async def ban(ctx, member : discord.Member, reason=None):
"""Bans a user"""
if reason == None:
await ctx.send(f"Woah {ctx.author.mention}, Make sure you provide a reason!")
else:
messageok = f"You have been banned from {ctx.guild.name} for {reason}"
await member.send(messageok)
await member.ban(reason=reason)
I'd recommend to use discord.ext.commands to make commands, it's easier to use. The function to ban is discord.Client.ban(member, delete_message_days = 1). This is an example using discord.ext.commands:
bot = commands.Bot(command_prefix = "!")
#bot.command(pass_context = True)
async def ban(member: discord.Member, days: int = 1):
if "449706643710541824" in [role.id for role in message.author.roles]:
await bot.ban(member, days)
else:
await bot.say("You don't have permission to use this command.")
bot.run("<TOKEN>")
A ban command? It's actually very easy!
#commands.has_permissions(ban_members=True)
#bot.command()
async def ban(ctx, user: discord.Member, *, reason="No reason provided"):
await user.ban(reason=reason)
ban = discord.Embed(title=f":boom: Banned {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}")
await ctx.message.delete()
await ctx.channel.send(embed=ban)
await user.send(embed=ban)
if you know kick you just need to change the user.kick into a user.ban because user.kick will kick a member so that means user.ban will ban a member.
According to Discord Official Documentation:-
#bot.command(name="ban", help="command to ban user")
#commands.has_permissions(ban_members=True)
async def _ban(ctx, member: discord.Member, *, reason=None):
""" command to ban user. Check !help ban """
try:
await member.ban(reason=reason)
await ctx.message.delete()
await ctx.channel.send(f'{member.name} has been banned from server'
f'Reason: {reason}')
except Exception:
await ctx.channel.send(f"Bot doesn't have enough permission to ban someone. Upgrade the Permissions")
#bot.command(name="unban", help="command to unban user")
#commands.has_permissions(administrator=True)
async def _unban(ctx, *, member_id: int):
""" command to unban user. check !help unban """
await ctx.guild.unban(discord.Object(id=member_id))
await ctx.send(f"Unban {member_id}")
#bot.command()
#commands.has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *,reason=None):
if member == None or member == ctx.message.author:
await ctx.channel.send("You cannot ban yourself")
return
if reason == None:
reason = "For being a jerk!"
message = f"You have been banned from {ctx.guild.name} for {reason}"
await member.send(message)
await member.ban(reason=reason)
await ctx.send(f"{member} is banned!")
This is a ban command I use and it works perfectly fine for me. You have full permission to use the whole thing if you'd like.
async def ban(self, ctx, member:discord.Member, *, reason=None):
guild = ctx.guild
author = ctx.message.author
if author.guild_permissions.administrator == False:
embed4=discord.Embed(color=discord.Colour.red(), timestamp=datetime.datetime.utcnow(), title="Missing Permissions!", description="You don't have the required permissions to use this command!")
message1 = await ctx.send(embed=embed4)
sleeper=5
await asyncio.sleep(sleeper)
await message1.delete()
return
if member.guild_permissions.administrator and member != None:
embed=discord.Embed(color=discord.Colour.red(), title="Administrator", description="This user is an administrator and is not allowed to be banned.")
message2 = await ctx.send(embed=embed)
sleeper=5
await asyncio.sleep(sleeper)
await message2.delete()
return
if reason == None:
embed1=discord.Embed(color=discord.Colour.red(), title="Reason Required!", description="You must enter a reason to ban this member.")
message3 = ctx.send(embed=embed1)
sleeper=5
await asyncio.sleep(sleeper)
await message3.delete()
return
else:
guild = ctx.guild
await member.ban()
embed2=discord.Embed(color=discord.Colour.green(), timestamp=datetime.datetime.utcnow(), title="Member Banned", description=f"Banned: {member.mention}\n Moderator: **{author}** \n Reason: **{reason}**")
embed3=discord.Embed(color=discord.Colour.green(), timestamp=datetime.datetime.utcnow(), title=f"You've been banned from **{guild}**!", description=f"Target: {member.mention}\nModerator: **{author.mention}** \n Reason: **{reason}**")
message4 = await ctx.send(embed=embed2)
message5 = await ctx.send("✔ User has been notified.")
sleeper=5
await asyncio.sleep(sleeper)
await message4.delete()
await message5.delete()
await member.send(embed=embed3)

Categories

Resources