问题
My code works fine and the bot sends the link, but Discord does not recognize it as one and does not embed it. When I copy and paste it myself, it then recognizes it as a link and embed the image. Here is my code:
import requests
from bs4 import BeautifulSoup
if message.content.startswith(".dog"):
response = requests.get("https://dog.ceo/api/breeds/image/random")
soupRaw = BeautifulSoup(response.text, 'lxml')
soupBackend = str(soupRaw).split("message")
soup2 = soupBackend[1]
soup3 = soup2[3:]
soup = soup3[:-20]
await bot.send_message(message.channel, soup)
Here is an example: https://imgur.com/m9GM2wQ
Does anyone know how to make it embed the link when it is sent by my bot? Thanks for the help!
Edit: I am not trying to send an embedded message, I am trying to send a link that will BE embedded by Discord, as shown in my example. This is not a duplicate question.
回答1:
Very late answer, but if anyone is viewing this answer for later; I believe the problem is that your variable soup
contains escape characters (backward slashes) for every forward slash, e.g. https:\\/\\/images.dog.ceo\\/breeds\\/maltese\\/n02085936_4480.jpg
.
Sending this as a message (even as a regular user) shows the link as it should look, but does not automatically create an embed for it. You can replace the backslashes with the function soup.replace("\\", "")
.
I would however recommend a completely different approach as the response
object has a .content
attribute which is in json format and can easily be parsed, and used as a python dict
, using the builtin import json
library (It will automatically leave the escape codes for you and you don't have to worry about string length for response.text).
soup = json.loads(response.content).get("message")
should do the trick.
来源:https://stackoverflow.com/questions/48252094/discord-does-not-embed-link-when-sent-by-my-bot