Discord does not embed link when sent by my bot

旧时模样 提交于 2021-01-28 05:36:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!