You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编程新手求助:如何使用Python Hikari库从文件夹随机发送图片并修改现有代码

How to Send Random Images from a Folder with Hikari (Python)

Hey there! As someone who’s worked with Hikari before, I can confirm you absolutely can send random images from a folder using this library. Let’s tweak your code to make that happen smoothly.

Here’s what we’ll adjust:

  • Import two standard Python modules to handle file system tasks and random selection: os and random
  • Modify your command to scan your target folder for valid image files
  • Add a safety check for empty folders or missing images
  • Pick a random image and send it to the channel

Modified Full Code

import os
import random
import hikari
import lightbulb

# Make sure your bot initialization is set up correctly here
bot = lightbulb.BotApp(token="YOUR_BOT_TOKEN", prefix="!")

@lightbulb.command('img', 'Send a random image from the target folder')
@lightbulb.implements(lightbulb.PrefixCommand)
async def image(ctx):
    # Update this path to your actual image folder
    image_folder = "C:/Users/User/Desktop/folder"
    
    # Filter for common image file extensions (add/remove as needed)
    valid_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.webp')
    all_images = [
        file for file in os.listdir(image_folder)
        if file.lower().endswith(valid_extensions)
    ]
    
    # Handle empty folder or no valid images
    if not all_images:
        await ctx.respond("Whoops! No images found in the target folder.")
        return
    
    # Pick a random image and build its full path
    random_img = random.choice(all_images)
    full_img_path = os.path.join(image_folder, random_img)
    
    # Send the selected image
    await ctx.respond(hikari.File(full_img_path))

# Start the bot
bot.run()

Key Notes:

  • Folder Path: Replace image_folder with your actual folder location. Using os.path.join() ensures the path works across Windows/macOS/Linux without manual path separator fixes.
  • Image Filter: The valid_extensions tuple covers most common image types—feel free to add others (like .bmp) if you need to.
  • Error Safety: The check for empty all_images prevents the bot from crashing if there’s nothing to send, and gives users a clear message instead.
  • Permissions: Double-check that your bot has the "Attach Files" permission enabled in the channel you’re testing this command in!

内容的提问来源于stack exchange,提问作者Kukieezi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:07:31