Discord bot从所选文件发送随机图像

时间:2020-05-03 23:38:42

标签: python discord discord.py

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

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编程机器人的新手,所以我可能忽略了一个愚蠢的错误,因此不胜感激!

2 个答案:

答案 0 :(得分:0)

如果直接通过在频道上调用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必须有一个字符串,即文件的路径。

答案 1 :(得分:0)

一些与您的代码有关的项目。

  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. 创建图像列表。
  4. 您需要使用File来发送消息中的图像。 (需要from discord import File
  5. 不确定**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))))

结果:

enter image description here