【问题标题】:Discord bot to send a random image from the chosen fileDiscord bot 从所选文件发送随机图像
【发布时间】:2020-08-18 08:05:12
【问题描述】:

我正在制作一个不和谐机器人,它随机选择与 python 文件 (cats.py) 位于同一目录 (Cats) 中的图像 (images)。这就是我的代码现在的样子:

Cats = os.path.join(os.path.dirname(__file__), "/images")

@client.command()
async def cat(ctx, **kwargs):
    await ctx.send(choice(Cats))

我没有收到任何错误。该机器人上线,当我用 ~cat 对其进行 ping 操作时,它会吐出随机字母。我知道我的问题在于异步(可能是 kwargs)和等待线,但无法准确指出问题所在。我是使用 Python 编程机器人的新手,所以可能有一个我忽略的愚蠢错误,所以任何领导都将不胜感激!

【问题讨论】:

  • 你有一个名为 images 的子目录,里面有一堆猫的图像文件吗?

标签: python discord discord.py


【解决方案1】:

如果您直接通过在频道上调用send 直接发送,您很可能会发送文件的原始文本,而不是作为图像上传。

documentation 你应该这样做:

Cats = os.path.join(os.path.dirname(__file__), "/images")

@client.command()
async def cat(ctx, **kwargs):
    await ctx.send(file=discord.File(choice(Cats)))

注意Cats 必须是一个字符串,即文件的路径。

【讨论】:

  • Cats 保证是一个字符串(这就是os.path.join 返回的内容)。我对choice 是什么更感兴趣!
  • 我假设 random.choice @AdamSmith
  • 但如果是这种情况,那么它将调用discord.File,并使用字符串Cats中的随机字符作为参数。
【解决方案2】:

关于您的代码的一些项目。

  1. Cats = os.path.join(os.path.dirname(__file__), "/images"),只返回“/images”,这可能不起作用,因为开头的斜杠“/”表示绝对路径,而您想要的目录不太可能位于根目录。如果要使用绝对路径,则需要使用 - Cats = os.path.join(os.path.dirname(__file__), "images/") - 在文件名之前加上斜线。当然,您可以轻松地使用“images/”的相对路径,因为图像与脚本位于同一文件夹中。
  2. await ctx.send(choice(Cats)) - "choice(Cats)" 只是一个字符串,choice 会从该字符串返回一个随机字母。您需要从目录中获取图像/图片以进行选择。您可以使用以下内容创建图像列表 - cat_list = [Cats + c for c in listdir(Cats)](需要 from os import listdir, path
  3. 您需要使用File 在消息中发送图像。 (需要from discord import File
  4. 不确定您在使用 **kwargs 做什么,因此将其排除在此解决方案之外。

试试:

Cats = path.join(path.dirname(__file__), "images/")
# Cats = "images/" - to just use the relative path
cat_list = [Cats + c for c in listdir(Cats)]


@bot.command()
async def cat(ctx):
    await ctx.send(file=File((choice(cat_list))))

结果:

【讨论】:

  • 感谢您的帮助!我最终这样做了:# Bot sends an image of a cat when pinged with cat @commands.command(pass_context=True) async def surprise(ctx): chosen_image = random.choice(embedlinks.catLinks) embed = discord.Embed(color=0xff69b4) embed.set_image(url=chosen_image) embed.set_footer(text=f"Requested by: {ctx.author.name}") await ctx.send(embed=embed) 创建了另一个名为 embedlinks.py 的文件并将所有链接放入其中。
猜你喜欢
  • 2020-05-13
  • 2021-06-05
  • 2019-10-19
  • 1970-01-01
  • 2020-11-10
  • 2020-11-18
  • 2019-06-07
  • 2021-12-21
  • 2021-06-25
相关资源
最近更新 更多