1
votes

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
@bboll Nope not a duplicate. Please read my question. I am not trying to send an embedded message, I am trying to have Discord embed the link I am sending with the bot. Completely different things. - Mark W
Read the API. You are trying to send an embedded message because it will not automatically create one for you. I found another duplicate question that perhaps helps you better. e.set_image(url=soup). Then you would call it with a different parameter passing your embed object: await bot.send_message(message.channel, embed=e) - bboll
Unrelated to your question, but - you could replace the five lines starting with "soup" with simply url = response.json()['message']. BeautifulSoup is doing nothing here besides mangling the JSON response from the api. - Nathan Vērzemnieks
@bboll you still are confusing the difference between an embedded message and an embedded image. Please see the difference between an embedded message and an embed of an image here: imgur.com/a/7xXJS I understand how to send an embedded message. Very simple. But when a link is sent in discord, Discord automatically embeds the image in the chat. When my bot posts the link to - Mark W

1 Answers

0
votes

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.