问题描述
我正在制作一个不和谐的bot,它会随机选择与python文件(cats.py)位于同一目录(Cats)中的一个或多个图像.这是我的代码现在的样子:
Cats = os.path.join(os.path.dirname(__ file__),"/images")@ client.command()异步def cat(ctx,** kwargs):等待ctx.send(choice(Cats))
我没有收到任何错误.该机器人已联机,当我使用〜cat对其进行ping操作时,它会吐出随机字母.我知道我的问题与异步(可能是kwargs)和等待线有关,但是无法确切指出问题所在.我是Python编程机器人的新手,所以我可能忽略了一个愚蠢的错误,因此不胜感激!
一些与您的代码有关的项目.
-
Cats = os.path.join(os.path.dirname(__ file__),"/images")
,仅返回"/images",由于斜杠开头可能不起作用"/"表示绝对路径,并且您所需的目录不可能在根目录下.如果要使用绝对路径,则需要使用-Cats = os.path.join(os.path.dirname(__ file__),"images/")
-在开始之前加上斜杠文件名.当然,您可以轻松地使用"images/"的相对路径,因为图像与脚本位于同一文件夹中. -
等待ctx.send(choice(Cats))
-"choice(Cats)"只是一个字符串,选择将返回该字符串中的随机字母.您需要从目录中获取图像/图片以进行选择.您可以使用以下内容创建图像列表-cat_list = [Cats + c for listdir(Cats)中的c]
(需要from os import listdir,path
) - 您需要使用
I am making a discord bot that randomly chooses an image (images) which is in the same directory (Cats) as the python file(cats.py). This is what my code looks like right now:
Cats = os.path.join(os.path.dirname(__file__), "/images") @client.command() async def cat(ctx, **kwargs): await ctx.send(choice(Cats))
I am not getting any errors. The bot goes online and when I ping it with ~cat it spits out random letters. I know my issue is with the async (possibly the kwargs) and await line, but cannot pin point exactly what is the issue. I am new to programming bots in Python so there might be a silly mistake that I am overlooking so any lead would be much appreciated!
解决方案Some items regarding your code.
Cats = os.path.join(os.path.dirname(__file__), "/images")
, returns just "/images", which probably won't work because the beginning slash "/" indicates an absolute path and your desired directory isn't likely at the root. If you want to use an absolute path you need to use -Cats = os.path.join(os.path.dirname(__file__), "images/")
- with a slash after to go before the file name. Of course you could easily just use a relative path of "images/" since images in the same folder as the script.await ctx.send(choice(Cats))
- "choice(Cats)" is just a string and choice will return a random letter from that string. You need to get the images/pics from the directory to make a selection. You can create a list of images with something like -cat_list = [Cats + c for c in listdir(Cats)]
(needfrom os import listdir, path
)- You need to use File to send an image in a message. (need
from discord import File
) - Not sure what you're doing with
**kwargs
, so excluded it from this solution.
Try:
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))))
Result:
这篇关于Discord bot从所选文件中发送随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!