discord.py 如何实现bot从指定文件夹随机选取图片发送的功能
discord.py 随机发送指定文件夹图片的实现方案
以下代码适配discord.py 2.x 版本,全程使用Python标准库实现文件扫描,不需要手动整理文件路径数组:
import discord from discord.ext import commands import os import random # 配置项,直接修改此处即可 # 你的图片文件夹路径,填相对路径或者绝对路径都可以 IMAGE_FOLDER = "./random_images" # 支持的图片格式,需要新增格式直接往里面加后缀就行 ALLOWED_EXTENSIONS = {".png", ".jpg", ".jpeg", ".bmp"} # 你的Bot令牌 BOT_TOKEN = "你自己的bot令牌" # 初始化Bot,开启必要的意图 intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix="!", intents=intents) @bot.event async def on_ready(): print(f"已登录为 {bot.user}") # 随机发图命令,触发前缀为!random_img,可以自己改 @bot.command(name="random_img") async def send_random_image(ctx): # 遍历文件夹获取所有符合格式的图片路径 image_list = [] for filename in os.listdir(IMAGE_FOLDER): # 取文件后缀转小写,避免大小写问题比如.PNG和.png都能识别 ext = os.path.splitext(filename)[1].lower() if ext in ALLOWED_EXTENSIONS: image_list.append(os.path.join(IMAGE_FOLDER, filename)) # 没有找到符合要求的图片时返回提示 if not image_list: await ctx.send("未找到可用的图片,请检查文件夹路径或支持的格式配置") return # 随机选一张图片发送 random_image_path = random.choice(image_list) await ctx.send(file=discord.File(random_image_path)) bot.run(BOT_TOKEN)
注意事项
- 请提前在Discord开发者后台的Bot设置页开启
Message Content Intent权限,否则2.x版本的discord.py无法正常读取消息命令 - 如果使用的是discord.py 1.x版本,只需要删除intents相关的配置代码即可,命令逻辑不需要修改
- 如果你把图片文件夹和bot启动文件放在同一目录下,直接填文件夹名作为相对路径即可,比如文件夹叫
img就填./img - 需要新增支持的图片格式时,直接往
ALLOWED_EXTENSIONS里加对应小写后缀即可,比如要支持webp就加".webp"
内容的提问来源于stack exchange,提问作者Dr. Glitchgo
相关产品推荐
相关产品推荐

