Feed of DMs sent to a discord.py bot - python

I have this code:
#client.event
async def on_message(message):
print(message.author)
print(message.content)
this code prints a feed of all of the messages send from channels that the bot has permissions to see. basically i'm trying to write code that does the same with dms.
and I can't figure out how.

To check if a message is a dm, check if the Guild is None.
if message.guild is None:
print(f"DM: {message.content}")

You can also make the bot send DMs to a specific channel using the following -
Just make sure to replace 1234567890 with channel id you want the bot to send the DMs to.
#client.event
async def on_message(message):
if isinstance(message.channel, discord.DMChannel):
emb=discord.Embed(title=message.author, description=message.content)
channel = client.get_channel(1234567890)
await channel.send(embed=emb)```

You could use:
if isinstance(message.channel, discord.DMChannel):
print(message.author)
print(message.content)

As Stijndcl said above, you want to check if the message is sent in a guild, but you also want to check if the bot sends the message.
if message.author == client.user:
return
if not message.guild:
print(f"DM: {message.content}")
If you code your bot further you might end up DM'ing users, and you don't want to log your own messages.

Related

Im trying to make a event so that when someone makes a message it replys to it

So far like I said I'm trying to make a bot so that when someone makes a message it responds with "Hello" and so on but when I try to do that I found the bot responding to itself.
My code:
#bot.event
async def on_message(message):
You just have to check whether the message.author is your bot.
#bot.event
async def on_message(message):
if message.author == bot.user: # check if the author of message is your bot
return
# rest of your code
await bot.process_commands(message) # to correctly process commands
You might also want to add await bot.process_commands(message) to make sure that your commands will work if you decide to use them. Check this link to see why do you have to use it

How do I transfer a message to a string in discord.py

Im trying to know how to make the bot remember the message a user send $equal message that user will say, and when the user says $message the bot will say the message the user send on $equal message that user will say.
It's really hard to understand what you want to achieve. Please add more description to your question, but even though I think you want to achieve something like this (if not add a further explanation and I'll try to help):
#client.event
async def on_message(message):
if message.author == client.user: #returning when the author of message is bot
return
msg = message.content #getting content of user's message
await message.channel.send(msg) #sending a message user sent
await client.process_commands(message) #proccesing commands (without this your #client.command won't work)
Remember that you have to enable intents.messages.
Discord.py Documentation - on_message() event
This answer is a complement to #RiveN 's answer.
keywords = ["um", "keyboard"]
grab_top = ["top", "t"]
#client.event
async def on_message(msg):
if msg.author == client.user:
return
if msg.content in keywords:
await msg.channel.send('This is a keyword')
if msg.content in grab_top:
await scrape_website()
if msg.content.startswith("~test()"):
await msg.channel.send('This is our test')
inside of discord:
Me: ~test()
Quaint Faint Saint BOT:
This is our test
Me: um
Quaint Faint Saint BOT:
This is a keyword

Discord.py library sending message upon member update

this is how I've already tried getting the message channel that I would presume the discord server uses for this bot, from having used its other functionality:
#client.event
async def on_message(message):
global message_channel
message_channel = message.channel
I want to send a message saying goodbye to users when they go offline using this function
#client.event
async def on_member_update(before, after):
print(str(before.status), str(after.status))
if str(before.status) == "online" and str(after.status) == "offline":
print("someone went offline")
try: await message_channel.send(f'Goodbye, {after.user}')
except: print('failed to send goodbye message')
I'd appreciate either finding a way to make this work (since currently nothing at all prints from the on_member_update() function, or if I could get the channel that the last message was sent to from the bot (meaning this would only be in place once the bot is used at least once)
I think you should make a own channel for the goodbye messages or define a extra channel for it. This would look like this:
#client.event
async def on_message(message):
pass#your code here
#client.event
async def on_member_update(before, after):
print(str(before.status), str(after.status))
if str(before.status) == "online" and str(after.status) == "offline":
channel = cliet.get_channel(channelId)
print("someone went offline")
try:
await channel.send(f'Goodbye, {after.user}')
except:
print('failed to send goodbye message')
If you want to write the goodbye message in the channel the user last wrote in you can simply make a txt with the users and their last channels. You can also do this with json. If you do it in on_message you get the channel that was last typed in by anyone on the server OR in the dms of the bot. So if userXYZ wrote the BOT "Hello World" via DM and then another user userABC went offline the BOT will send userXYZ a Goodbye message via DM.

How do I delete a dm message that was sent by my discord bot

I did a script where you can send a message to a specific dm using my discord bot
#client.command(pass_context=True)
async def dm(ctx, user: discord.User, *, message=None):
await ctx.channel.purge(limit=1)
message = message
await user.send(message)
But how am I to make a script that can delete all messages that was sent by the bot in a specific dm
You can iterate over the DMChannel.history() and delete the messages whose author is your client:
#client.command()
async def clear_dm(ctx, user: discord.User):
async for message in user.dm_channel.history():
if message.author == client.user:
await message.delete()
Keep in mind that you need read_message_history and manage_messages permissions respectively, otherwise a Forbidden exception will be raised.
Also, maybe it's a good idea to catch HTTPException as well, to continue the iteration if the removal of any message fails for some reason.
Never mind I fixed it. Here is the script
#client.command()
async def cleardm(ctx, user: discord.User):
#await ctx.channel.purge(limit=1) remove '#' if you want the bot to delete the command you typed in the discord server
async for message in user.history():
if message.author == client.user:
await message.delete()

How to get discord.py bot to DM a specific user

I have searched around a lot for this answer, and I haven't found it. I want to use a suggestion command, that whenever someone uses it to suggest an idea, it DMs me, and me only.
You'll have to use the send_message method. Prior to that, you have to find which User correspond to yourself.
#client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
# can be cached...
me = await client.get_user_info('MY_SNOWFLAKE_ID')
await client.send_message(me, "Hello!")
#client.event
async def on_message(message):
if message.content.startswith("#whatever you want it to be")
await client.send_message(message.author, "#The message")
Replace the hashtagged things with the words that you want it to be. eg.: #whatever you want it to be could be "!help". #The message could be "The commands are...".
discord.py v1.0.0+
Since v1.0.0 it's no longer client.send_message to send a message, instead you use send() of abc.Messageable which implements the following:
discord.TextChannel
discord.DMChannel
discord.GroupChannel
discord.User
discord.Member
commands.Context
Example
With bot.command() (recommended):
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
#bot.command()
async def suggest(ctx, *, text: str):
me = bot.get_user(YOUR_ID)
await me.send(text) # or whatever you want to send here
With on_message:
from discord.ext import commands
bot = commands.Bot()
#bot.event
async def on_message(message: discord.Message):
if message.content.startswith("!suggest"):
text = message.content.replace("!suggest", "")
me = bot.get_user(YOUR_ID)
await me.send(text) # or whatever you want to send here

Categories