Discord.py - 获取随机 imgur 图像

问题描述 投票:0回答:4

我正在尝试让机器人发送来自 imgur 的嵌入链接,特别是 https://imgur.com/t/dank_memes

我已经可以发送 random.choice 链接了,但是很快就会用完,而且太乏味了

我到目前为止:

 @commands.command()
 async def meme(self, ctx):
  images=["links go here"]

  embed=discord.Embed(colour=discord.Colour.orange())

  embed.set_image(url=random.choice(images))

  await ctx.send(embed=embed)

我不确定我将如何做到这一点,因为我没有发现其他任何东西,而且如果我必须使用 API,您不妨在不和谐中添加我并解释如何: Jakaboii 博士#2019

python python-3.x discord.py
4个回答
1
投票

顺便说一句,这是我用于自己的机器人的命令(在cog内),但您可以将

@commands.command
更改为
@client.command
(如果您使用普通文件)。您将从这里获取API密钥,并且您可以在这里找到有关API的更多信息,以便您了解更多信息。

希望这对您有帮助!

    @commands.command(name='imgur', pass_context=True)
    async def imgur(self, ctx, *text: str):
        """Allows the user to search for an image from imgur"""
        rand = r.randint(0, 29)
        if text == ():
            await ctx.send('**Please enter a search term**')
        elif text[0] != ():
            items = imgur.gallery_search(" ".join(text[0:len(text)]), advanced=None, sort='viral', window='all',page=0)
            await ctx.send(items[rand].link)

记得戴在上面:

import discord
from discord.ext import commands
import random as r
from imgurpython import ImgurClient

imgur = ImgurClient("Client ID","Client Secret")

0
投票

如果您想从 imgur 中提取随机图像,您可以使用 url https://imgur.com/random 生成一个随机图像,然后您可以检索该图像。

如果您希望专门从

dank_memes
url 检索随机图像,那么您可以使用 BeautifulSoup 和请求进行网页抓取,并专门从具有
<img>
标签且源 url 以
https://i.imgur.com 开头的 HTML 页面中检索元素
然后将它们随机化。

使用 BS4 抓取 imgur 图像的基本指南

单击

此处获取 BS4 文档

编码快乐!


0
投票
您可以将其设为 random.randint ,并针对每个可能的数字,使用不同的链接运行此代码。漫长而简单。


0
投票
您的 Discord 的 imgur 命令似乎可以在 Imgur 上搜索图像。但是,我注意到您可以对干净和优化的代码进行一些改进:

条件 elif text[0] != (): 不是必需的。您可以使用 else 代替,因为您已经在第一个 if 语句中检查了空文本。

直接使用text即可,而不是text[0:len(text)]。

这是更新后的代码:

@commands.command(name='imgur', pass_context=True) async def imgur(self, ctx, *text: str): """Allows the user to search for an image from Imgur""" rand = r.randint(0, 29) if not text: await ctx.send('**Please enter a search term**') else: items = imgur.gallery_search(" ".join(text), advanced=None, sort='viral', window='all', page=0) await ctx.send(items[rand].link)
    
© www.soinside.com 2019 - 2024. All rights reserved.