How to retrieve a specific message by ID (tried fetch_message(id)) - python

#client.command()
async def edit(ctx, message_id, *, new_message) :
channel, chan, guild = None, list_channels("saved_channels.csv"), ctx.guild.id
message = await fetch_message(message_id)
await message.edit(new_message)
embed=discord.Embed(color=0x00ca1f)
embed.add_field(name="Success :white_check_mark:", value=f"Le message a bien été édité dans {message.channel.mention}", inline=False)
await ctx.send(embed = embed)
I'm trying to edit a specific message my bot sent in another channel by taking the message id with fetch_message() (supposed to be in the new discord API) but it gives me the NameError: name 'fetch_message' is not defined... is there something I did wrong ?

You need to specify the channel where bot should edit the message from.
For example,
channel = client.get_channel(channel_id)
message = await channel.fetch_message(message_id)
Also, when editing a message you need to specify the content as follows:
await message.edit(content=new_message)

Related

discord.py - adding reaction as part of command

I'm writing a custom help command that sends a embed DM to a user, that all works fine. As part of the command, I'm trying to make the bot react to the command message but I cannot get it to work, I've read the documentation but I still can't seem to get it to react as part of a command. Below is the what I'm trying to achieve:
#client.command(pass_context=True)
async def help(ctx):
# React to the message
author = ctx.message.author
help_e = discord.Embed(
colour=discord.Colour.orange()
)
help_e.set_author(name='The bot\'s prefix is !')
help_e.add_field(name='!latency', value='Displayes the latency of the bot', inline=False)
help_e.add_field(name='!owo, !uwu, !rawr', value='Blursed commands', inline=False)
await author.send(embed=help_e)```
You can use message.add_reaction() and also you can use ctx.message to add reaction to the message. Here is what you can do:
#client.command(pass_context=True)
async def help(ctx):
# React to the message
await ctx.message.add_reaction('✅')
author = ctx.message.author
help_e = discord.Embed(
colour=discord.Colour.orange()
)
help_e.set_author(name='The bot\'s prefix is !')
help_e.add_field(name='!latency', value='Displayes the latency of the bot', inline=False)
help_e.add_field(name='!owo, !uwu, !rawr', value='Blursed commands', inline=False)
sent_embed = await author.send(embed=help_e)

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')

DMing The Member Joins The Server - Discord.Py

#client.event
async def on_member_join(member):
channel = client.get_channel(659080736229294130)
await channel.send(f'{member.mention} Katıldı, Hoşgeldin! {channel.guild.member_count} Kişiyiz!')
role = get(member.guild.roles, name=ROLE)
await member.add_roles(role)
print(f"{member} Katıldı!")
if member.guild is None and not member.author.bot:
async with member.typing():
await asyncio.sleep(0.7)
embed = discord.Embed(
title="Hoşgeldin!",
colour=discord.Colour.blue(),
)
embed.set_thumbnail(
url="https://cdn.discordapp.com/avatars/649985273249398784/493fe440660d331687e426ba976da8f4.webp?size=1024")
embed.add_field(name="‎",
value="**TEXT**",
inline=False)
embed.add_field(name="TEXT",
value= "TEXT", )
embed.set_footer(text="© #MakufonSkifto#0432")
await member.send(embed=embed)
The code you see is under
#client.event
async def on_member_join(member):
I want my bot to DM the person who joins the server. I have made a command that welcomes the newcomer thru the welceme channel but I couldn't make DM work. And as the bot didn't know what message is, It makes the text red. When I put message on the top It says "message is a required context that is missing" when someone joins. I don't know how to proceed but I definitely need you guys help! I can give the full on_member_joins event if you guys want
You can send personal messages to a user through member.send(...) where member is the user in the context (joined the server).
The <destination>.send(<content>) function sends the content(your message) to the given destination which can be a channel, a group or a member(in this case),etc.
Here is a sample code(your code with some changes) which send an embed to the joining user's DM:
#client.event
async def on_member_join(member):
print ("{} joined!".format(member.name))
print (f'{member.guild.name}')
await member.send("Welcome!")
role = member.guild.roles
# member.guild.roles returns an object of type <class 'list'>
if member.guild and not member.bot:
async with member.typing():
embed = discord.Embed(
title="Hoşgeldin!",
colour=discord.Colour.blue(),
)
embed.set_thumbnail(
url="https://cdn.discordapp.com/avatars/649985273249398784/493fe440660d331687e426ba976da8f4.webp?size=1024")
embed.add_field(name="something",
value="**TEXT**",
inline=False)
embed.add_field(name="TEXT",
value="TEXT")
embed.set_footer(text="© #MakufonSkifto#0432")
await member.send(embed=embed)

How do I get the message class using the message's ID? [duplicate]

#client.command()
async def edit(ctx, message_id, *, new_message) :
channel, chan, guild = None, list_channels("saved_channels.csv"), ctx.guild.id
message = await fetch_message(message_id)
await message.edit(new_message)
embed=discord.Embed(color=0x00ca1f)
embed.add_field(name="Success :white_check_mark:", value=f"Le message a bien été édité dans {message.channel.mention}", inline=False)
await ctx.send(embed = embed)
I'm trying to edit a specific message my bot sent in another channel by taking the message id with fetch_message() (supposed to be in the new discord API) but it gives me the NameError: name 'fetch_message' is not defined... is there something I did wrong ?
You need to specify the channel where bot should edit the message from.
For example,
channel = client.get_channel(channel_id)
message = await channel.fetch_message(message_id)
Also, when editing a message you need to specify the content as follows:
await message.edit(content=new_message)

Log embed thinks it's empty (on_message_edit)

To start with, I'm trying to make my bot log message editing. Basically that code works and logs messages that were edited, but it causes some problems in the terminal:
discord.errors.HTTPException: 400 BAD REQUEST (error code: 50035): Invalid Form Body
In embed.fields.0.value: This field is required
In embed.fields.1.value: This field is required
Here's my code:
#client.event
async def on_message_edit(before, after):
editembed = discord.Embed(
timestamp=after.created_at,
description = f"<#!{before.author.id}>**'s message was edited in** <#{before.channel.id}>.",
colour = discord.Colour(0x00FF00)
)
editembed.set_author(name=f'{before.author.name}#{before.author.discriminator}', icon_url=before.author.avatar_url)
editembed.set_footer(text=f"Author ID:{before.author.id} • Message ID: {before.id}")
editembed.add_field(name='Before:', value=before.content, inline=False)
editembed.add_field(name="After:", value=after.content, inline=False)
channel = client.get_channel(665307525897519105)
await channel.send(embed=editembed)
I can't understand why it decides that the value is empty. Can someone help to fix these errors?
I had the same problem but I searched around on google for some time and found a solution which was by adding + "\u200b" after both value=before.content and value=after.content. I also used embed instead of editembed. So try this:
#bot.event
async def on_message_edit(before, after):
embed = discord.Embed(
timestamp=after.created_at,
description = f"<#!{before.author.id}>**'s message was edited in** <#{before.channel.id}>.",
colour = discord.Colour(0x00FF00)
)
embed.set_author(name=f'{before.author.name}#{before.author.discriminator}', icon_url=before.author.avatar_url)
embed.set_footer(text=f"Author ID:{before.author.id} • Message ID: {before.id}")
embed.add_field(name='Before:', value=before.content + "\u200b", inline=False)
embed.add_field(name="After:", value=after.content + "\u200b", inline=False)
channel = bot.get_channel(665307525897519105)
await channel.send(embed=embed)
Link to the github page that helped me: https://github.com/Rapptz/discord.py/issues/643
You are using the wrong variables try this:
#bot.event
async def on_message_edit(before, after):
embed = discord.Embed(
timestamp=after.created_at,
description = f"<#!{before.author.id}>**'s message was edited in** <#{before.channel.id}>.",
colour = discord.Colour(0x00FF00)
)
embed.set_author(name=f'{before.author.name}#{before.author.discriminator}', icon_url=before.author.avatar_url)
embed.set_footer(text=f"Author ID:{before.author.id} • Message ID: {before.id}")
embed.add_field(name='Before:', value=before.content, inline=False)
embed.add_field(name="After:", value=after.content, inline=False)
channel = bot.get_channel(665307525897519105)
await channel.send(embed=embed)

Categories