Discord.py Send DM to specific User ID - python

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)

Related

discord.py ban command does not do anything

It only seems like the ban command is not working here. The "hello" and "insult me" responses work and it prints out the bot name and server name when running.
Full main.py:
import os
import random
import discord
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
PREFIX = os.getenv('DISCORD_PREFIX')
client = discord.Client()
bot = commands.Bot(command_prefix='!',
help_command=None) # help_command to disable the default one created by this library.
#client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})'
)
#client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(
f'Hi {member.name}, welcome to my Discord server!'
)
#client.event
async def on_message(message):
reponse = ''
if message.author == client.user:
return
greeting = [
f"Hello there, {message.author.mention}",
f"hi!!",
'Penis enlargement pills are on their way!',
f"You're stupid, {message.author.mention}",
]
insult = [
"You're a dumb dumb!",
"You stupid meanie face!",
"Go eat a dick, you stupid mudblood!"
]
if "hello" in message.content:
response = random.choice(greeting)
await message.channel.send(response)
if 'insult me' in message.content:
response = random.choice(insult)
await message.channel.send(response)
#bans a user with a reason
#bot.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!")
client.run(TOKEN)
I believe the most relevant parts are:
client = discord.Client()
bot = commands.Bot(command_prefix='$',
help_command=None) # help_command to disable the default one created by this library.
and
#bans a user with a reason
#bot.command()
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!")
I'm sure that i'm just incorrectly implementing the bot/command in the code somewhere, but I'm not sure where.
I don't get any errors at all when I try to either run the bot or type the command in chat.
You make a client and bot but you only use client for your code. Commands registered in the bot never get called because it is not even running.
You should look at tutorials and ask for help in the discord.py Discord server
I am not sure but you need to return the reason if there is no reasons typed and reason = reason is better. So your code should look like something like this:
async def ban (ctx, member:discord.User=None, reason = reason):
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!"
return
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!")

Discord.py how to delete all roles in server

I'm trying to delete all roles in my discord server, but it takes a huge amount of time. So I decided to do this task with discord.py bot, but I'm getting this error:
discord.errors.HTTPException: 400 Bad Request (error code: 50028): Invalid Role
Here's my code:
#client.command()
async def delroles(ctx):
for role in ctx.guild.roles:
await role.delete()
The problem is that all users have an "invisible role" called #everyone, which is impossible to remove.
Do:
async def delroles(ctx):
for role in ctx.guild.roles:
try:
await role.delete()
except:
await ctx.send(f"Cannot delete {role.name}")
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='>')
#client.event
async def on_ready():
print("Log : "+str(client.user))
#client.command()
async def delete(ctx):
for role in ctx.guild.roles:
try:
await role.delete()
except:
pass
client.run("token")

How to DM a user without them doing anything in the server

I'm creating a simple DM part of a bot and I've tried this method but it keeps giving me an error.
Code:
import discord
from discord.ext import commands
TOKEN = "Token Here"
#client.event
async def on_message(message):
if message.author == client.user:
return
me = await client.get_user_info('Snowflake ID Here')
await client.send_message(me, "Message Here")
client.run(TOKEN)
It keeps giving me this error:
NameError: name 'client' is not defined
This method seems like the user needs to send a message but is there a way to do it without the user needing to send a message.
import discord
from discord.ext import commands
client = disord.Client(intents=discord.Intents.all()) # define client
# could also be commands.Bot()
#client.event
async def on_message(message):
if message.author == client.user:
return
me = client.get_user(1234) # user id, must be int type
await me.send("Message Here") # client.send(me, "message here") doesnt work in discord.py version 1.x
client.run("TOKEN")
Client Example
import discord
class MyClient(discord.Client): # defineding client
async def on_ready(self): # event
print('Logged on as', self.user)
async def on_message(self, message): # event
if message.author == self.user:
return
you = self.get_user(1234)
await you.create_dm() # go to DM
await you.send("Message Here")
client = MyClient()
client.run('token')
Bot Example
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='>') # defineding client
#bot.event
async def on_ready():
print('Logged on as', bot.user)
#bot.event
async def on_message(message):
if message.author == bot.user:
return
you = bot.get_user(1234)
await you.create_dm() # go to DM
await you.send("Message Here")
bot.run('token')

Verification using Python Discord

I'm making a bot with python and I need help with two things.
Making a welcome message for users that include mentioning the user and mentioning the channel
Making a command that will remove the role "Unverified" and add 4 other roles. I also need it to send a message in the verification channel to make sure the person has been verified and send an embed in general chat telling the user to get self roles.
Well you could try
import discord
from discord.ext import commands
from discord.utils import get
client = commands.Bot(command_prefix=".")
confirmEmoji = '\U00002705'
#client.event()
async def on_ready():
print("[Status] Ready")
#client.event()
async def on_member_join(ctx, member):
channel = get(ctx.guild.channels,name="Welcome")
await channel.send(f"{member.mention} has joined")
#client.command()
async def ConfirmMessage(ctx):
global confirmEmoji
message = await ctx.send("Confirm")
await message.add_reaction(emoji=confirmEmoji)
def check(reaction, user):
if reaction.emoji == confirmEmoji:
return True
else:
return False
while True:
try:
reaction, user = await client.wait_for("reaction_add", check=check, timeout=10)
roleToRemove = get(ctx.guild.roles,name="unverified")
memberToRemoveRole = get(ctx.guild.members,name=user.display_name)
await memberToRemoveRole.remove_roles(roleToRemove)
Now all you have to do is go to the channel and enter .ConfirmMessage

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

Categories

Resources