I would just like to send a DM to my friend via python code.
This is my code, but it does not work.
Code:
import discord
client = discord.Client(token="MY_TOKEN")
async def sendDm():
user = client.get_user("USER_ID")
await user.send("Hello there!")
Your bot might now have the user in its cache. Then use fetch_user
instead of get_user (fetch requests the Discord API instead of
its internal cache):
async def sendDm():
user = await client.fetch_user("USER_ID")
await user.send("Hello there!")
You can run it with on_ready event:
#client.event
async def on_ready():
user = await client.fetch_user("USER_ID")
await user.send("Hello there!")
Copy and paste:
import discord
client = discord.Client()
#client.event
async def on_ready():
user = await client.fetch_user("USER_ID")
await user.send("Hello there!")
client.run("MY_TOKEN")
So are you trying to do this with a command? If so here is that
#bot.command()
async def dm(ctx, user: discord.User = None, *, value = None):
if user == ctx.message.author:
await ctx.send("You can't DM yourself goofy")
else:
await ctx.message.delete()
if user == None:
await ctx.send(f'**{ctx.message.author},** Please mention somebody to DM.')
else:
if value == None:
await ctx.send(f'**{ctx.message.author},** Please send a message to DM.')
else:
` await user.send(value)
Trying to add role once someone has joined and got the "y" confirmation from someone in the same channel
Not sure if I can add another async in the middle...
Sorry if it is a very obvious question but most answers I got online were quite outdated and the docs didn't answer all my questions
This is my attempt
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = discord.ext.commands.Bot(command_prefix="$", intents=intents)
#bot.event
async def on_member_join(member):
await channel.send("{} has just joined. \nDo you know them (y/n)?".format(member.name))
print("someone joined")
async def on_message(message):
if "y" in message.content:
role = get(message.guild.roles, name="Hey i know you")
await member.add_roles(role, atomic=True)
await message.channel.send("added Hey i know you to {}".format(member.name))
One way of doing this is by using the wait_for function.
#client.event
async def on_member_join(member):
channel = client.get_channel(your channel id)
guild = client.get_guild(your guild id)
await channel.send(f"{member.mention} joined!")
await asyncio.sleep(3)
await channel.send("{} has just joined. \nDo you know them (y/n)?".format(member.name))
msg = await client.wait_for("message")
if msg.content == "y":
role = guild.get_role(your rold id)
await member.add_roles(role)
await channel.send("Added role!")
elif msg.content == "n":
await channel.send("i wont add the role!")
return
I tried to run this code (please see my code below).
Code:
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix="!")
#client.event
async def on_ready():
Channel = client.get_channel('406473869424328736')
Text= "REACT TO ME"
Moji = await Client.send_message(Channel, Text)
await client.add_reaction(Moji, emoji='question')
#client.event
async def on_reaction_add(reaction, user):
Channel = client.get_channel('406473869424328736')
if reaction.message.channel.id != Channel:
return
if reaction.emoji == "question":
Role = discord.utils.get(user.server.roles, name="test")
await client.add_roles(user, Role)
client.run("NzcxMDQxMzcwNjU5MjI1NjMw.X5mWPA.oiEvo4otmA3lThVzCBxQHunugO4")
Moji = await client.send_message(Channel, Text)
However, I received an error that is as follows
Error:
AttributeError: 'Client' object has no attribute 'send_message'
client.send_message() has been deprecated.
It is replaced with:
await ctx.message.channel.send('message')
or you can shorten it to
await ctx.send('message')
Also, please do not reveal your bot token to the internet. I urge you to refresh your token asap.
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
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)