首页 > 解决方案 > Discordpy,Praw,获取链接的 img 预览,或者如果没有链接并且附加了一个 img,则嵌入该链接

问题描述

我正在使用 discordpy 和 Praw 模块来访问 Reddit。我想知道如何发送附加到 reddit 提交的文章的图像预览,或者,如果没有 reddit 链接而是附有图像,我如何发送。

这是我当前的代码:

@client.command()
@cooldown(1, 5, BucketType.user) #Command can only be used once every 5 seconds
async def webdev(ctx):
    subreddit = reddit.subreddit("webdev") #Subreddit name 
    all_subs = []

    hot = subreddit.hot(limit = 100)

    for submission in hot: #Iterating through the submissions in hot
        all_subs.append(submission) #Appending the submissions to the all_subs variable list

    random_sub = random.choice(all_subs) #Using the random module to randomly select one

    name = random_sub.title #Title of the submission
    body = random_sub.selftext #Body text of the submission
    link = random_sub.shortlink #Link to the submission
    url = random_sub.url #image of the submission
    img = random_sub.thumbnail #thumbnail of an exterior link (if there is one)

    em = discord.Embed(title = name) #Creating discordpy embed
    em.description = body #Setting the descriptiong to the body variable
    em.set_image(url = url) or em.set_image(url = img) #Attempting to send either the image attachment, or a link preview image
    em.add_field(name = f"Link to post:", value = link, inline= False) #Adding the submission link
    


    await ctx.send(embed = em) #Sending the embed

谢谢

标签: discorddiscord.pydiscord.py-rewriteredditpraw

解决方案


为了让您发送图像,它必须托管在某个地方。使用 Discord 机器人,您可以通过链接发送图像,也可以发送由机器人在本地托管的图像。

您可以像使用代码一样发送带有链接的图像。否则,您必须将图像保存在主机上,然后从那里发送。

要将图像保存在主机上,可以使用 PIL 模块。将您获得的图像转换为可保存的文件,然后使用img.save("name.png")然后您可以使用:file = discord.File("name.png")要获取图像然后使用它set_image(),您只需以这种方式发送嵌入:await ctx.send(embed = em, file = file)


推荐阅读