Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Discord bot从所选文件发送随机图像_Python_Discord_Discord.py - Fatal编程技术网

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

Python Discord bot从所选文件发送随机图像,python,discord,discord.py,Python,Discord,Discord.py,我正在制作一个discord机器人,它随机选择一个与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

我正在制作一个discord机器人,它随机选择一个与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编程机器人的新手,所以可能有一个愚蠢的错误我忽略了,所以任何潜在客户都会非常感激

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

从中可以看出,您应该这样做:

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(os.path.dirname(\uuuu file\uuu),“/images”)
    只返回“/images”,这可能不起作用,因为开头的斜杠“/”表示绝对路径,并且所需目录不可能位于根目录。如果要使用绝对路径,则需要使用-
    Cats=os.path.join(os.path.dirname(\uuuu file\uuuu),“images/”
    ——在文件名之前加一个斜杠。当然,您可以轻松地使用相对路径“images/”,因为图像与脚本位于同一文件夹中
  • wait ctx.send(choice(Cats))
    -“choice(Cats)”只是一个字符串,choice将从该字符串返回一个随机字母。您需要从目录中获取图像/图片以进行选择。您可以创建一个具有以下内容的图像列表-
    cat\u list=[Cats+c代表listdir中的c(Cats)]
    (需要从操作系统导入listdir,路径
  • 您需要使用发送消息中的图像。(需要从discord导入文件
  • 不确定您正在使用
    **kwargs
    做什么,因此将其从该解决方案中排除
  • 尝试:

    结果:


    是否有一个名为images的子目录,其中包含一组cat图像文件?
    Cats
    保证是字符串(这就是
    os.path.join
    返回的内容)。我对什么是
    choice
    更感兴趣!我假设random.choice@adamsmith,但如果是这种情况,那么它将调用
    discord.File
    ,参数为字符串
    Cats
    中的随机字符。感谢您的帮助!我最后是这样做的:
    #当用cat@commands进行ping时,Bot会发送一个cat的图像。command(pass_context=True)async def惊奇(ctx):selected_image=random.choice(embedlinks.catLinks)embed=discord.embed(color=0xff69b4)embed.set_image(url=selected_image)embed.set_footer(text=f“请求者:{.ctx.author.name}”)wait ctx.send(embed=embed)
    创建了另一个名为embedlinks.py的文件,并将所有链接都放入其中。
    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))))