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

Discord机器人:将文件夹名指令从on_message改造为bot.command的实现问询

把Discord机器人指令改成@bot.command()形式的实现方案

我来帮你把原来基于on_message的图片发送逻辑改成@bot.command()的形式,这样不仅更贴合discord.py的设计规范,后续新增类似指令(比如新增kiss文件夹)也会更省心。

完整实现代码

首先确保你已经正确导入所需模块,然后按下面的结构编写代码:

import random
import os
import discord
from discord.ext import commands

# 初始化Bot,记得替换成你的前缀和token
bot = commands.Bot(command_prefix=".", intents=discord.Intents.all())

# 封装重复逻辑:从指定文件夹随机获取图片并发送
async def send_random_image(ctx, folder_name):
    # 检查文件夹是否存在
    if not os.path.exists(folder_name):
        await ctx.send(f"哎呀,`{folder_name}`文件夹找不到啦!")
        return
    
    # 获取文件夹里的所有文件,过滤掉非图片(可选,按你的需求调整)
    image_files = [f for f in os.listdir(folder_name) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif'))]
    if not image_files:
        await ctx.send(f"`{folder_name}`文件夹里没有图片哦!")
        return
    
    # 随机选一张图片
    chosen_image = random.choice(image_files)
    image_path = os.path.join(folder_name, chosen_image)  # 跨系统兼容的路径拼接
    
    # 构造Embed和文件对象
    embed = discord.Embed(color=0xff9e00)
    file = discord.File(image_path, filename=chosen_image)
    embed.set_image(url=f"attachment://{chosen_image}")
    
    # 发送消息
    await ctx.send(embed=embed, file=file)
    print(f"{chosen_image} sent in response to {ctx.author}.")
    print("----------")

# 定义hug命令
@bot.command(name="hug")
async def hug_command(ctx):
    await send_random_image(ctx, "hug")

# 定义headpat命令
@bot.command(name="headpat")
async def headpat_command(ctx):
    await send_random_image(ctx, "headpat")

# 运行Bot,替换成你的token
bot.run("YOUR_BOT_TOKEN_HERE")

关键改动说明

  • 封装重复逻辑:把选图、发送的通用代码放到send_random_image辅助函数里,两个命令只需要调用这个函数并传入对应文件夹名,避免代码冗余。
  • 路径兼容性:用os.path.join替代硬编码的\,这样代码在Windows、Linux、Mac上都能正常运行。
  • 错误处理:新增了文件夹不存在、文件夹无图片的提示,让机器人的反馈更友好。
  • 符合命令规范:每个指令对应一个@bot.command()装饰器的函数,discord.py会自动处理指令匹配、上下文(ctx)传递,比on_message里手动判断内容更可靠。

使用方式

和之前一样,在Discord里发送.hug或者.headpat,机器人就会从对应文件夹随机选一张图片发送啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:57:35