使用Discord.py的@client.tree.command与Interaction发送文件报错求助
解决Discord Interaction发送文件的AttributeError问题
报错原因
你遇到的AttributeError: 'str' object has no attribute 'to_dict',核心原因是interaction.followup.send()的file参数要求传入discord.File对象,而非单纯的文件名字符串。discord.py内部需要调用文件对象的to_dict()方法处理附件,传入字符串会直接触发该错误。
修复后的代码
修改发送文件的逻辑,使用discord.File包装文件路径,同时利用yd.download()返回的完整路径避免手动拼接的错误:
import discord from pytube import YouTube @client.tree.command() async def download(interaction: discord.Interaction, link: str): await interaction.response.defer(ephemeral=True) yt = YouTube(link) yd = yt.streams.get_highest_resolution() # 指定文件保存路径,download方法会返回完整的文件路径 save_dir = "C:\\Users\\phili\\OneDrive\\code\\discord bot" full_file_path = yd.download(output_path=save_dir) # 用discord.File包装文件路径后发送 await interaction.followup.send(file=discord.File(full_file_path))
额外注意事项
- 优先使用
yd.download()返回的完整路径,避免视频标题包含特殊字符(空格、标点等)导致手动拼接文件名时找不到文件。 - 确保机器人运行账户对
save_dir目录有读写权限,否则会出现文件下载或读取失败的问题。 - 如需自定义发送时显示的文件名,可给
discord.File添加filename参数:await interaction.followup.send(file=discord.File(full_file_path, filename="我的视频.mp4"))
内容的提问来源于stack exchange,提问作者Omegaking
相关产品推荐
相关产品推荐

