如何实现Discord机器人接收路径与文件名并发送指定文件
完善Discord机器人的!importFile命令实现
核心解决思路
- 使用
bot.wait_for监听命令发起者的回复,避免无关消息干扰 - 用
os.path.join安全拼接文件路径,兼容不同系统的路径分隔符 - 添加多场景错误处理,覆盖超时、文件不存在、权限问题等情况
完整实现代码
import discord from discord.ext import commands import os import asyncio import ctypes # 修复原代码未导入ctypes的问题 TOKEN = "Tokengg83" lib = ctypes.windll.kernel32 intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='!', intents=intents) @bot.command() async def importFile(ctx): # 定义消息检查规则:仅接收命令发起者在同一频道的消息 def check(msg): return msg.author == ctx.author and msg.channel == ctx.channel try: # 询问文件路径并等待用户回复 await ctx.send("请输入文件所在路径(例如:C:\\Users\\user\\Desktop):") path_msg = await bot.wait_for('message', check=check, timeout=60) file_path = path_msg.content.strip() # 询问文件名并等待用户回复 await ctx.send("请输入文件名(例如:OverFlow.exe):") filename_msg = await bot.wait_for('message', check=check, timeout=60) filename = filename_msg.content.strip() # 安全拼接完整文件路径 full_file_path = os.path.join(file_path, filename) # 验证文件有效性 if not os.path.exists(full_file_path): await ctx.send("错误:指定的文件不存在,请检查路径和文件名是否正确。") return if not os.path.isfile(full_file_path): await ctx.send("错误:指定路径指向的不是文件,请重新输入。") return # 发送目标文件 await ctx.send(content="这是你请求的文件:", file=discord.File(full_file_path)) except asyncio.TimeoutError: await ctx.send("超时:你未在60秒内回复,请重新执行命令。") except PermissionError: await ctx.send("权限错误:机器人没有访问该文件的权限,请检查文件权限设置。") except Exception as e: await ctx.send(f"发生未知错误:{str(e)}") bot.run(TOKEN)
关键功能说明
- 消息过滤:通过
check函数确保机器人只响应命令发起者的消息,避免其他用户的输入干扰流程 - 超时控制:设置60秒超时时间,若用户未及时回复则自动终止命令
- 路径安全:
os.path.join会根据系统自动处理路径分隔符,避免手动拼接导致的格式错误 - 异常处理:覆盖超时、文件不存在、权限不足等常见问题,给用户明确的错误提示
内容的提问来源于stack exchange,提问作者BRH
相关产品推荐
相关产品推荐

