我正在尝试让机器人发送来自 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
顺便说一句,这是我用于自己的机器人的命令(在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")
如果您想从 imgur 中提取随机图像,您可以使用 url https://imgur.com/random 生成一个随机图像,然后您可以检索该图像。
如果您希望专门从
dank_memes
url 检索随机图像,那么您可以使用 BeautifulSoup 和请求进行网页抓取,并专门从具有 <img>
标签且源 url 以 https://i.imgur.com
开头的 HTML 页面中检索元素
然后将它们随机化。
使用 BS4 抓取 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)