Issue with sending dm messages discord.py - python

I have a command in my bot that allows a user to dm an anonymous message to me. However, when I tested the command my bot only sends the first word of the message to me.
#commands.command(name='msgetika', aliases=['msgmax'])
async def msgetika(self, ctx, message1=None):
'''Send an annonymous message to discord'''
if message1 is None:
await ctx.send('Please specify a message')
maxid = await self.bot.fetch_user('643945264868098049')
await maxid.send('Anonymous message: ' + message1)
msg = await ctx.send('Sending message to max.')
await ctx.message.delete()
await asyncio.sleep(5)
await msg.delete()

You need to add a * if you want to catch the entire phrase. View the docs here about using this and have a look at the example working beneath the code.
#commands.command(name='msgetika', aliases=['msgmax'])
async def msgetika(self, ctx, *, message1=None):
Also, unless you are using an older version of discord.py, user ids are ints.
maxid = await self.bot.fetch_user(USER ID HERE)

Related

discord.py kick command thats sends a dm to user that is kicked

I am trying to make a discord.py bot with a kick command. So when you do ;kick (member) it will kick the mentioned user and send that user a dm telling them they are kicked from the server. However it only dms the user if the dm is a normal message and not embed. I'm still pretty new to python so I don't understand whats wrong with the code. Here is my code:
#commands.guild_only()
#has_permissions(kick_members = True)
async def kick(self, ctx, member : discord.Member=None, *, reason="No reason was provided"):
aA=ctx.author.avatar_url
desc1=f"You are missing the following argument(s): `Member`\n```{prefix}kick <member> [reason]```"
embed1=discord.Embed(title="Missing Argument",description=desc1,color=rC)
embed1.set_author(name="Error",icon_url=aA)
try:
if member == None:
await ctx.send(embed=embed1)
return
if member == ctx.author:
await ctx.send(f"You can't kick yourself.")
return
try:
em1=discord.Embed(description=f"You were kicked out from **{ctx.guild.name}**\nReason: `{reason}`.",color=rC)
em1.set_author(icon_url=aA)
await member.send(embed=em1)
except:
pass
em2=discord.Embed(description=f"{tick} {member.mention} has been kicked out of **{ctx.guild.name}**. Reason: `{reason}`",color=gC)
await member.kick(reason = reason)
await ctx.send(embed=em2)
except:
await ctx.send("An unknown error occured.)
There isn't any errors sent in the console when I run the bot or use the command
you can use:
await member.send(embed=em2)
ctx will send in the channel where the command was done.

Remove a message that the bot waited for using discord.py

Basically, im trying to make an autorole bot that takes a message from the user and then deletes the message and updates the role message after. The code I have so far is:
#commands.command()
#commands.has_any_role(786342585479593984, 787715167437324330)
async def rrtest(self, ctx, *, msg):
loop = True
j = "\n"
messagetext = [msg]
rolemessage = await ctx.send(f"```{j.join(messagetext)}```")
message = await ctx.send("Hold on!")
time.sleep(2)
while loop:
await message.edit(content="```Type the role you want to assign \n\nNo need to mention, just type the role name```")
msg = await self.client.wait_for('message', check=self.check(ctx.author), timeout=30)
# ^^^ this is the message i want to delete
what code would i use to delete msg?
Use the method .delete()
await msg.delete()
Also use await asyncio.sleep instead of time.sleep so it doesn't block you whole code.

How to check if a message contains a channel mention (Discord.py)

So here is my code, I want to create a command through discord.py that writes a message with "say [message]" and writes a message in a channel with "say [channel] [message]". For the most part, I got it out. The problem I have is that I would like to check whether the first argument after the command "say" is a channel mention.
client = commands.Bot(command_prefix="_")
#client.command(aliases=['echo', 'print'], description="say <message>")
async def say(ctx, channel, *, message=""):
await ctx.message.delete()
if not channel:
await ctx.send("What do you want me to say?")
else:
if channel == discord.TextChannel.mention:
await ctx.send("test")
else:
await ctx.send(str(channel) + " " + message)
I already tried using discord.textchannel, discord.message.channel_mentions and a few others, but I can't figure it out.
We can use some of the fancy converter features to have the command parsing machinery do this for us:
from typing import Optional
from discord import TextChannel
#client.command(aliases=['echo', 'print'], description="say <message>")
async def say(ctx, channel: Optional[TextChannel], *, message=""):
channel = channel or ctx # default to ctx if we couldn't detect a channel
await channel.send(message)
await ctx.message.delete()

Message not sending to user when on_message issue

Hi I'm having an issue when sending a message from a channel to a users direct messages. The message when using #user followed by message should DM the user I'm not sure why this is not working.
The mention in the message should take the user object.
Here is the code:
#commands.Cog.listener()
async def on_message(self, message):
"""Send a message thread reply to user."""
for member in message.mentions: #get user object from mention in message?
if not member.dm_channel:
await member.create_dm()
try:
time = datetime.utcnow()
embed = discord.Embed(title=f"Reply", timestamp=time, colour=discord.Colour(0xff8100))
embed.add_field(name="Message:", value="test message")
await member.dm_channel.send(embed=embed)
except discord.Forbidden:
await message.channel.send(f"Reply cannot be sent because {member.name}'s direct messages are set to private.")
except discord.HTTPException:
await message.channel.send('I failed in sending the message.')
except Exception as e:
await message.channel.send(f'There\'s been a problem while sending the message that\'s not of type "Forbidden" or'
f' "HTTPException", but {e}.')
else:
await message.channel.send(f'Reply sent to {member.name}')
In discord.py you don't really have to create dm channels anymore. Just do a await ctx.author.send(# whatever message you want)
If you're trying to create a command that sends a SPECIFIC DM to the author of the message, you can try this
#client.command()
async def dm(ctx, *, message):
await ctx.author.send(f"This is your dm {message}")
It's extremely simple. Let me know in the comments if you have any questions or I misunderstood your problem.
EDIT:
If you're looking to send a dm to a SPECIFIC MEMBER, you can try this.
#client.command()
async def dm(ctx, member: discord.Member, *, message):
await member.send(message)
Hope your problem has been solved.
PS: In the future, please explain your questions/issues in more detail.

Discord.Py adding reactions to an embeded message

So I am trying to add three different reactions (emojis), to a message that the bot has sent in a text channel.
The user fills in a form in their DM, and the message then get sent into a text-channel called "admin-bug", the admins of the server can then react to three different emojis:
fixed
will not be fixed
not-a-bug
And then, depending on what emoji the admin press on, the message will be transferred to a text channel.
But! I can't seem to figure out how you actually add the reactions to the message itself, I have done a bunch of googling, but can't find the answer.
code:
import discord
from discord.ext import commands
TOKEN = '---'
bot = commands.Bot(command_prefix='!!')
reactions = [":white_check_mark:", ":stop_sign:", ":no_entry_sign:"]
#bot.event
async def on_ready():
print('Bot is ready.')
#bot.command()
async def bug(ctx, desc=None, rep=None):
user = ctx.author
await ctx.author.send('```Please explain the bug```')
responseDesc = await bot.wait_for('message', check=lambda message: message.author == ctx.author, timeout=300)
description = responseDesc.content
await ctx.author.send('````Please provide pictures/videos of this bug```')
responseRep = await bot.wait_for('message', check=lambda message: message.author == ctx.author, timeout=300)
replicate = responseRep.content
embed = discord.Embed(title='Bug Report', color=0x00ff00)
embed.add_field(name='Description', value=description, inline=False)
embed.add_field(name='Replicate', value=replicate, inline=True)
embed.add_field(name='Reported By', value=user, inline=True)
adminBug = bot.get_channel(733721953134837861)
await adminBug.send(embed=embed)
# Add 3 reaction (different emojis) here
bot.run(TOKEN)
Messagable.send returns the message it sends. So you can add reactions to it using that message object. Simply, you have to use a variable to define the message you sent by the bot.
embed = discord.Embed(title="Bug report")
embed.add_field(name="Name", value="value")
msg = await adminBug.send(embed=embed)
You can use msg to add reactions to that specific message
await msg.add_reaction("💖")
Read the discord.py documentation for detailed information.
Message.add_reaction
The discord.py docs have an FAQ post about adding reactions, it has multiple exampes and an indepth description, furthermore Messageable.send returns the message send so you can use Message.add_reaction on that. https://discordpy.readthedocs.io/en/neo-docs/faq.html#how-can-i-add-a-reaction-to-a-message
You need to save the embed as a variable, in this way you can add a reaction.
message = await adminBug.send(embed=embed) # save embed as "message"
await message.add_reaction('xxx') # add reaction to "message"
I'm not sure because I use nextcord (and it worked), but I think this can work :
#bot.command
async def testembed(ctx):
embed = discord.Embed(title='Test !', description='This is a test embed !')
msg = await ctx.send("", embed=embed)
msg = msg.fetch() # Notice this line ! It's important !
await msg.add_reaction('emoji_id')

Categories