Discord.py 随机图像发送到 ctx.message.channel [英] Discord.py random image to send to ctx.message.channel
问题描述
所以我正在尝试编写一小段代码从文件夹发送随机图像我正在使用 discord.py我不知道怎么做所以我认为stackoverflow可以帮助我!对不起,伙计们,但我实际上对 python 编码有点陌生我真的很烂
So i'm trying to make a lil piece of code that sends a random image from a folder im using discord.py i dunno how to do it so i thought stackoverflow could help me! i'm sorry guys but i'm actually kinda new to python coding and i really suck
推荐答案
使用您使用的 discord.py 发送图像
to send images with discord.py you use
await channel.send(file=discord.File('my_file.png'))
如果您想发送随机图像,您可以将每个文件名保存到一个列表中,然后在命令中从该列表发送一个随机文件:
If you want to send a random image, you could save every filename to a list and on a command send a random file from that list:
import random
files = ['img1.png', 'img2.png', 'img3.png']
@bot.command()
async def image(ctx):
file = random.choice(files)
await channel.send(file=discord.File(file))
如果您想自动将每个图像文件添加到与运行机器人的 .py 文件相同的目录中,您可以使用 os 模块:
if you want to automatically add every image file in the same directory as the .py file the bot is running from, you can use the os module:
import os
files = []
for file in os.listdir():
if file.endswith('.png'):
files.append(file)
这篇关于Discord.py 随机图像发送到 ctx.message.channel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!