Embed an image for discord using embeds - python

I'm trying to make an embed image command, something like $embed (image link)
This is my code:
async def image(ctx, link):
await ctx.message.delete()
embd = discord.Embed("")
embed.set_image(url=link)
await ctx.channel.send(embed=embd)
But it doesn't work, how can I fix it?

You spelled your variables incorrectly. Try this out:
async def image(ctx, link):
await ctx.message.delete()
embed = discord.Embed("")
embed.set_image(url=link)
await ctx.send(embed=embed)

Related

Send images in embeds discord.py

I'm trying to send embeds in discord.py, but whenever i run the code nothing gets sent. No errors nothing. Here is my code:
from variables.variables import client, token
import discord
#client.command()
async def test(ctx):
imageURL = "https://discordapp.com/assets/e4923594e694a21542a489471ecffa50.svg"
embed = discord.Embed()
embed.set_image(url=imageURL)
await ctx.send(embed=embed)
client.run(token)
This is what the embed looks like using above code:
Thanks!
.svg is not supported. Here's the same image in .png format:
#client.command()
async def test(ctx):
imageURL = "https://cdn.discordapp.com/attachments/744631318578462740/755866713182044240/ezgif-4-6eba1fde99f2.png"
embed = discord.Embed()
embed.set_image(url=imageURL)
await ctx.send(embed=embed)

How to make a NSFW command in discord.py?

I am making a discord bot and I want a NSFW command in, so I used a command that's puts a random image of a NSFW subreddit, but I need help with the detection of a NSFW channel, so this command can't be used in channels that are not nsfw, and also send a message that says "You need to use this command in a nsfw channel!"
Here's my command, but there's a error in the part of "else:"
async def nsfw(ctx):
if ctx.channel.is_nsfw():
embed = discord.Embed(title="test", description="test")
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/nsfw/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed)
else:
await ctx.send("You need to use this command in a nsfw channel!"
You can add a check to see if the channel the command is being used in is NSFW
#commands.command()
#commands.is_nsfw()
async def your_nfsw_command(self, ctx):
#your-command
As for throwing an error if the command is used in a non-nsfw channel, you can use a error handler such as
#commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.errors.NSFWChannelRequired):
msg.title = "NSFW Command"
msg.description = error.args[0]
return await ctx.send(embed=msg)
Alternatively you may also add an error-handler by doing
commandname.error and using the same logic.
Possible corrections to code may involve:
if ctx.channel.is_nsfw():
#logic
async with aiohttp.ClientSession() as cs:
#this line seems to be not indented correctly
else:
#logic
Your error is likely thrown by an else without an if.
probably you are missing paranthesis in else statement
Code
async def nsfw(ctx):
if ctx.channel.is_nsfw():
embed = discord.Embed(title="test", description="test")
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/nsfw/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed)
else:
await ctx.send("You need to use this command in a nsfw channel!")
This is my solution, I used to get the same thing before, but researching I found the solution, I hope it helps you.
#bot.command()
#commands.is_nsfw()
async def nsfw(ctx):
embed = discord.Embed(title="test", description="test")
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/nsfw/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed)
#nsfw.error(ctx, error):
if isinstance(error, NSFWChannelRequired):
await ctx.send(f"Hey! {ctx.author.mention}, sorry but i can't submit nsfw content without nsfw category.")

How to edit a message in discord.py

I would like to have my bot edit a message if it detects a keyword, i'm not sure how to edit the message though.
I've looked through the documentation but can't seem to figure it out. I'm using discord.py with python 3.6.
This is the code:
#bot.event
async def on_message(message):
if 'test' in message.content:
await edit(message, "testtest")
This is the error:
File "testthing.py", line 67, in on_message
await edit(message, "test")
NameError: name 'edit' is not defined
I would like the bot to edit a message to "testtest" if the message contains the word test, but i just get an error.
You can use the Message.edit coroutine. The arguments must be passed as keyword arguments content, embed, or delete_after. You may only edit messages that you have sent.
await message.edit(content="newcontent")
Here's a solution that worked for me.
#client.command()
async def test(ctx):
message = await ctx.send("hello")
await asyncio.sleep(1)
await message.edit(content="newcontent")
Did you do this:
from discord import edit
or this:
from discord import *
before using message.edit function?
If you did it, maybe the problem is with your discord.py version.
Try this:
print(discord.__version__)
If you are wanting to update responses in discord.py you have to use:
#tree.command(name = 'foobar', description = 'Send the word foo and update it to say bar')
async def self(interaction: discord.Interaction):
await interaction.response.send_message(f'foo', ephemeral = True)
time.sleep(1)
await interaction.edit_original_response(content=f'bar')
Assign the original message to a variable. Reference the variable with .edit(content='content').
(You need "content=" in there).
#bot.command()
async def test(ctx):
msg = await ctx.send('test')
await msg.edit(content='this message has been edited')
#bot.event
async def on_message(message):
if message.content == 'test':
messages=await message.channel.send("CONTENT")
await asyncio.sleep(INT)
await messages.edit(content="NEW CONTENT")
Please try to add def to your code like this:
#bot.event
async def on_message(message):
if 'test' in message.content:
await edit(message, "edited !")
This is what I did:
#bot.event
async def on_message(message):
if message.content == 'test':
await message.channel.send('Hello World!')
await message.edit(content='testtest')
I don't know if this will work for you, but try and see.

Discord bot can't mention everyone despite having its permission

Here is the sendMessage function:
async def sendMessage(color, title, value, should_delete=True, channel=""):
embed = discord.Embed(color=color)
embed.add_field(name=title, value=value, inline=False)
if channel == "":
msg = await client.send_message(message_obj.channel, embed=embed)
else:
msg = await client.send_message(client.get_channel(channel), embed=embed)
if should_delete:
await delete_msg(msg)
The bot can mention anyone but everyone and here. Despite having mention everyone permission.
sendMessage(OK_COLOR_HASH, "title", "Hello #everyone")
Edit: When I converted the message type to the normal one instead of embed one, it worked.
You can try to sending a mention to everyone through the default_role attribute
#bot.command(pass_context=True)
async def evy(msg):
await bot.say(msg.message.server.default_role)
You can try this block code. roles return a list all guild's roles, but first role always a default guild role (default_role) and that's why you must use slicing function.
#bot.command()
async def test(ctx):
await ctx.send(ctx.message.guild.roles[0])
Or you can do something like this.
#bot.command()
async def test(ctx):
await ctx.send(ctx.message.guild.default_role)

How can I send an embed via my Discord bot, w/python?

I've been working a new Discord bot.
I've learnt a few stuff,and, now, I'd like to make the things a little more custom.
I've been trying to make the bot send embeds, instead, of a common message.
embed=discord.Embed(title="Tile", description="Desc", color=0x00ff00)
embed.add_field(name="Fiel1", value="hi", inline=False)
embed.add_field(name="Field2", value="hi2", inline=False)
await self.bot.say(embed=embed)
When executing this code, I get the error that 'Embed' is not a valid member of the module 'discord'. All websites, show me this code, and I have no idea of any other way to send a embed.
To get it to work I changed your send_message line to
await message.channel.send(embed=embed)
Here is a full example bit of code to show how it all fits:
#client.event
async def on_message(message):
if message.content.startswith('!hello'):
embedVar = discord.Embed(title="Title", description="Desc", color=0x00ff00)
embedVar.add_field(name="Field1", value="hi", inline=False)
embedVar.add_field(name="Field2", value="hi2", inline=False)
await message.channel.send(embed=embedVar)
I used the discord.py docs to help find this.
https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.send for the layout of the send method.
https://discordpy.readthedocs.io/en/latest/api.html#embed for the Embed class.
Before version 1.0: If you're using a version before 1.0, use the method await client.send_message(message.channel, embed=embed) instead.
When executing this code, I get the error that 'Embed' is not a valid member of the module 'discord'. All websites, show me this code, and I have no idea of any other way to send a embed.
This means you're out of date. Use pip to update your version of the library.
pip install --upgrade discord.py
#bot.command()
async def displayembed(ctx):
embed = discord.Embed(title="Your title here", description="Your desc here") #,color=Hex code
embed.add_field(name="Name", value="you can make as much as fields you like to")
embed.set_footer(name="footer") #if you like to
await ctx.send(embed=embed)
how about put #client.event instead of the #bot.command() it fixed everything when I put #client.event... #bot.command() does not work you can type
#client.event
async def displayembed(ctx):
embed = discord.Embed(title="Your title here", description="Your desc here") #,color=Hex code
embed.add_field(name="Name", value="you can make as much as fields you like to")
embed.set_footer(name="footer") #if you like to
await ctx.send(embed=embed)
For anyone coming across this in 2022:
how about put #client.event instead of the #bot.command() it fixed everything when I put #client.event... #bot.command() does not work you can type
To this ^, I don't recommend using #client.event / #bot.event as you'd want to register your commands as a command.
If you want to simply make a command with an embed in your main.py file, make sure you have something like:
import discord
from discord.ext import commands
intents = discord.Itents.default()
bot = commands.Bot(command_prefix='YOURPREFIX', description='description', intents=intents)
#bot.command(name="embed")
async def embed(ctx):
embed = discord.Embed(title='Title', description='Desc', color=discord.Color.random())
embed.add_field(name="Name", value="Value", inline=False)
await ctx.send(embed=embed)
However, I personally like separating my commands into a /commands folder and with separate files for all of them as it's good practice for neater code.
For that, I use cogs.
/commands/embed.py
from discord.ext import commands
import discord
class EmbedCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command(name="embed")
async def embed(self, ctx):
embed = discord.Embed(title='Title', description='Desc', color=discord.Color.random())
embed.add_field(name="Name", value="Value", inline=False)
await ctx.send(embed=embed)
Then import it all into your main.py file:
from commands.embed import EmbedCog
bot.add_cog(EmbedCog(bot))
Before using embed
embed (Embed) – The rich embed for the content to send. This cannot be mixed with embeds parameter.
embeds (List[Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the embed
TypeError – You specified both embed and embeds or file and files or thread and thread_name.
#client.event
async def on_message(message):
if message.content.startswith('!hi'):
embed = discord.Embed(title="This is title of embedded element", description="Desc", color=0x00ff00)
embed.add_field(name="Like header in HTML", value="Text of field 1", inline=False)
embed.add_field(name="Like header in html", value="text of field 2", inline=False)
await message.channel.send(embed=embed)
Reference

Categories

Resources