首页 > 解决方案 > 随机图像发送者​​不和谐 py python 3.8

问题描述

我是 discord py 的新手,我想要一个命令,该命令将从文件中发送随机图像并发送它,但我可以让它工作我尝试使用Discord bot 从所选文件中发送随机图像,但仍然无法得到它工作,所以我尝试了这个,但如果有人可以帮助我,我仍然没有工作请做

#put your images into the image folder
#images that are uploaded will be moved to the sent_images folder so they won't be reposted

import discord,os,random,asyncio
from datetime import datetime
from discord.ext import commands

bot=commands.Bot(command_prefix='!')

send_time='12:00' #time is in 24hr format
image_channel_id='ChannelID' #channel ID to send images to, replace with your channel ID
image_types=('.jpg','.png','.gif','.jpeg') #add image types if needed


folders={'Image Folder':'images','Sent Folder':'sent_images'}
for folder in folders.values():
    if not os.path.isdir(folder):
        os.mkdir(folder)

@bot.event
async def on_ready():
    print(bot.user.name)
    print(bot.user.id)

async def send_image():
    for item in os.walk('./{}'.format(folders['Image Folder'])):
        images=list(pic for pic in item[2] if pic.lower().endswith(image_types))
    if len(images) == 0:
        await bot.send_message(image_channel,"Oops! I'm all out of images to send. Notify my owner!")
    else:
        image= random.choice(images)
        await bot.send_file(image_channel,'./{}/{}'.format(folders['Image Folder'],image))
        os.rename('./{}/{}'.format(folders['Image Folder'],image), './{}/{}'.format(folders['Sent Folder'],image))

async def time_check():
    global image_channel
    await bot.wait_until_ready()
    image_channel=bot.get_channel(image_channel_id)
    while not bot.is_closed:
        now=datetime.strftime(datetime.now(),'%H:%M')
        if now == send_time:
            await send_image()
        await asyncio.sleep(60)

bot.loop.create_task(time_check())

bot.run('TOKEN')```

标签: discord.py

解决方案


根据您的问题,我了解到您有一堆文件夹,其中包含一堆图像,并且您想要创建一个发送随机图像的命令。

import os, random

@bot.command()
async def random_image(ctx, category: str = None):
    root_dir = os.listdir('./images')
    # If the user doesn't specify a category send a random image from a random folder
    if category is None:
         # Getting a random directory and file
         dir = random.choice(root_dir)
         image = random.choice(os.listdir(os.path.join(root_dir, dir)))
         path = os.path.join(dir, image)
    
    elif category in root_dir:
        # Getting a random file from the category
        image = random.choice(os.listdir(os.path.join(root_dir, category)))
        path = os.path.join(dir, image)

    else:
        await ctx.send("Couldn't find that category")
        return
    
    # Sending the image in an embed
    file = discord.File(path)
    
    embed = discord.Embed(title=category.title(), colour=discord.Colour.greyple())
    embed.set_image(url=f'attachments://{image}')
    
    await ctx.send(file=file, embed=embed)

{prefix}random_image← 将从随机目录发送随机图像

{prefix}random_image dog← 将从./images/dogdir发送一个随机图像

让我知道这是否是您所要求的。


推荐阅读