I'm working on a User Discord Bot in Python .If the bot owner types !DM #user then the bot will DM the user that was mentioned by the owner.
#client.event
async def on_message(message):
if message.content.startswith('!DM'):
msg = 'This Message is send in DM'
await client.send_message(message.author, msg)
The easiest way to do this is with the discord.ext.commands extension. Here we use a converter to get the target user, and a keyword-only argument as an optional message to send them:
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix='!')
#bot.command(pass_context=True)
async def DM(ctx, user: discord.User, *, message=None):
message = message or "This Message is sent via DM"
await bot.send_message(user, message)
bot.run("TOKEN")
For the newer 1.0+ versions of discord.py, you should use send instead of send_message
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix='!')
#bot.command()
async def DM(ctx, user: discord.User, *, message=None):
message = message or "This Message is sent via DM"
await user.send(message)
bot.run("TOKEN")
Since the big migration to v1.0, send_message no longer exists.
Instead, they've migrated to .send() on each respective endpoint (members, guilds etc).
An example for v1.0 would be:
async def on_message(self, message):
if message.content == '!verify':
await message.author.send("Your message goes here")
Which would DM the sender of !verify. Like wise, you could do:
for guild in client.guilds:
for channel in guild.channels:
channel.send("Hey yall!")
If you wanted to send a "hi yall" message to all your servers and all the channels that the bot is in.
Since it might not have been entirely clear (judging by a comment), the tricky part might get the users identity handle from the client/session. If you need to send a message to a user that hasn't sent a message, and there for is outside of the on_message event. You will have to either:
Loop through your channels and grab the handle based on some criteria
Store user handles/entities and access them with a internal identifier
But the only way to send to a user, is through the client identity handle which, in on_message resides in message.author, or in a channel that's in guild.channels[index].members[index]. To better understand this, i recommend reading the official docs on how to send a DM?.
I used this command in the past and it in my opinion it works the best for me:
#bot.command(pass_context=True)
async def mall(ctx, *, message):
await ctx.message.delete()
for user in ctx.guild.members:
try:
await user.send(message)
print(f"Successfully DMed users!")
except:
print(f"Unsuccessfully DMed users, try again later.")
#bot.command()
async def dm(ctx, user: discord.User, *, message=None):
if message == None:
message = "Hi!"
embed = make_embed(title=f"Sent by {user}", desc=message)
await user.send(embed=embed)
await ctx.send("Message sent!")```
I have noticed that each code I put into my code lines they don't work completely, so I added my own bit to them and bam it works! When adding this to your bot's code, don't forget to add the bot's name where it says bot name here. It will only DM the person who sent it, but you can change what it says each day for a surprise for everyone that used the command. It works every time for me.
#client.command()
async def botdm(ctx):
await ctx.message.author.send('hi my name is *bot name here* and i am a bot!')
Related
So, I've never used discord.py, this is my first time using it, and I am very confused, I want to make a command so it'll send the help message on DMs, but it does not works, unless you mention yourself.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '$')
#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#client.command()
async def help(ctx, user:discord.Member, *, message=None):
message = 'test'
embed = discord.Embed(title=message)
await user.send(embed=embed)
So, if you do $help, it'll do nothing, but if u do $help #John Doe#0001 it'll DM John Doe or anyone you mention.
I am sorry if this sounds stupid..
If you want the bot to message you, the person who invoked the command, you shouldn't pass the user argument. However, if you still want to mention someone so you can send them your help message, you can make user=None, an optional argument, within the function itself.
Do note that in the code snippet I have provided I made message not an argument, but something already in the function. Do view the revised code below.
#client.command()
async def help(ctx, user:discord.Member=None):
if user == None: # if no user is passed..
user = ctx.author # ..make the command author the user
message = "test"
embed = discord.Embed(title=message)
await user.send(embed=embed)
Helpful Questions:
How to send a Private Message to the message author? - SO
How to DM commands? - SO
ctx - Discord.py Docs
Do you mean sending a help message to the person who used the command but didn't to mention the user?
Here's how:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '$')
#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#client.command()
async def help(ctx):
message = 'test'
embed = discord.Embed(title=message)
await ctx.author.send(embed=embed)
Use ctx.author.send to send a message to user used the command
Here is the code for the help gui to be sent in dms , if u want to send the help prompt in the command's channel as well as dms add await ctx.channel.send(embed=embed)
#client.command()
async def help(ctx):
embed = discord.Embed(color=0xFFFFFF)
embed.set_author(name='HELP MESSAGE' icon_url=ctx.author.avatar_url)
embed.add_field(name="help" , value='sends the help message in dms')
await ctx.author.send(embed=embed)
You can add ur custom embed instead of the embed in the above code .. Hope you understood .
#client.command()
async def help(ctx, user:discord.Member, *, message=None):
embed = discord.Embed(title=f"{message}", description=f"Sent by {ctx.author}")
await user.send(embed=embed)
I would try something like this.
discord.py 1.7.2
use case:
When a user joins my channel, I save their discord id in my database.
If a user sent a message with the word $sub foo they subscribe to one
of my services. When they subscribe to this service. They idea is for
them to get a private message every now and again based on the type
Code
import discord,os,asyncio
from discord.ext import commands, tasks
from Entity.notifications import Notification
from dotenv import load_dotenv
from discord.utils import get
bot = commands.Bot(command_prefix='$')
#bot.event
async def on_ready():
print('Bot is ready')
#tasks.loop(seconds=10)
async def user_notification():
print("foo") ##terminal shows the word foo
await bot.wait_until_ready()
user_sub_notifications= Notification().get_active_user_sub_notification()
if user_sub_notifications:
for notification in user_sub_notifications:
if "user_discord_id" in notification:
#get user
user = get(bot.get_all_members(), id=notification['user_discord_id'])
#get the message to sent to the user
message = notification['message']
#private message the user
#bot.send_message(user, message)
await asyncio.sleep(10)
load_dotenv()
user_notificarion.start()
bot.run(os.getenv('DISCORD_TOKEN'))
I have tried the follow
user = get(bot.get_all_members(), id=notification['discord_id']) #got NONE
bot.send_message(notification['user_discord_id'], message) ##bot has not attribute send_message
how can I private message the user? Thank you
Thanks to Rapptz from the discord.py github who answered this question. All credit goes to him.
In v1.7 you need to fetch the user first:
user = bot.get_user(user_id) or await bot.fetch_user(user_id)
await user.send('whatever')
In the future in v2.0 (still in development) you'll be able to open a DM directly via user ID:
dm = await client.create_dm(user_id)
await dm.send('whatever')
the actual method which works is the fetch_user
The best and easiest way I would say is to do:
await member.send("{message}")
This will automatically open a dm with the member that used the command, and you can type whatever message you want, similar to ctx.send
So, I've got a bot that can send a user a DM via a very simple command. All I do is "!DM #user message" and it sends them the message. However, people sometimes try responding to the bot in DMs with their questions, but the bot does nothing with that, and I cannot see their replies. Would there be a way for me to make it so that if a user sends a DM to the bot, it will forward their message to a certain channel in my server (Channel ID: 756830076544483339).
If possible, please can someone tell me what code I would have to use to make it forward on all DMs sent to it to my channel 756830076544483339.
Here is my current code:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
#bot.event
async def on_ready():
activity = discord.Game(name="DM's being sent", type=3)
await bot.change_presence(
activity=discord.Activity(
type=discord.ActivityType.watching,
name="Pokemon Go Discord Server!"))
print("Bot is ready!")
#bot.command()
async def DM(ctx, user: discord.User, *, message=None):
message = message or "This Message is sent via DM"
await user.send(message)
await ctx.send('DM Sent Succesfully.')
Thank you!
Note: I'm still quite new to discord.py coding, so please could you actually write out the code I would need to add to my script, rather than just telling me bits of it, as I often get confused about that. Thank you!
What you're looking for is the on_message event
#bot.event
async def on_message(message):
# Checking if its a dm channel
if isinstance(message.channel, discord.DMChannel):
# Getting the channel
channel = bot.get_channel(some_id)
await channel.send(f"{message.author} sent:\n```{message.content}```")
# Processing the message so commands will work
await bot.process_commands(message)
Reference
I'm currently trying to create a block user and send friend request command. However, I've hit a wall. It seems like the bot doesn't have permission or authorization to my account so it can't send friend requests or block users. How do I give it the permissions? Or maybe it isn't possible at all? Please let me know, I'd really appreciate it :>
My current code for the commands is below:
#client.command()
async def unfriend(ctx, *, user: discord.User):
await user.remove_friend()
await ctx.send('Friend has been removed')
#client.command()
async def sendrequest(ctx, *, user: discord.User):
await user.send_friend_request()
await ctx.author.send('Request sent')
#client.command()
async def block(ctx, *, user: discord.User):
await user.block()
await ctx.send(f'{member.mention} has been blocked by {ctx.author}')
#client.command()
async def unblock(ctx, *, user: discord.User):
await user.unblock()
await ctx.send(f"{member.mention} has been unblocked by {ctx.author}")
Unfortunately, Discord does not allow bot users to add, block, or remove friends. You can only perform these actions through a normal Discord user, and if you were to do this through the program, that would be self botting, which is against Discord's Terms of Service.
Read about this send_friend_request() method here:
https://discordpy.readthedocs.io/en/latest/api.html?highlight=add%20friend#discord.User.send_friend_request
Discord's stance on self botting:
https://support.discord.com/hc/en-us/articles/115002192352-Automated-user-accounts-self-bots-
I know that it is possible to DM someone with the bot if you have their ID, but how can I get the users ID's when they enter the server?
I was thinking:
#client.event
async def on_member_leave(member):
or
async def on_guild_remove(guild):
user = await client.fetch_user(**the id**)
await user.send("Your message")
There's no need to use fetch_user, you can simply use message.send -
#client.event
async def on_member_leave(member):
await member.send("Your message")
Also, if the member has no server common with the client or if the member has disabled direct messages, The message will not be sent.