如何用discord.py实现客户端本地下载文件的Discord机器人按钮
问题
我在View类中编写了如下按钮代码:
# Create Download Button downlaodButton = Button(style=discord.ButtonStyle.grey, label='Download', row=1) downlaodButton.callback = self.download self.add_item(downlaodButton) async def download(self, interaction: discord.Interaction): # Change Button Color And Accessbility After Clicking it self.children[-2].style = discord.ButtonStyle.blurple await interaction.response.edit_message(view=self) response = requests.get(self.image_url) with open('my_photo.png','wb') as f: f.write(response.content)
当前代码可将图片下载至我的项目目录,但我希望用户点击按钮后,图片能直接下载到其本地电脑。请问能否用discord.py实现该功能?
解答
当然可以实现。核心逻辑是把图片作为Discord附件发送给用户,让用户直接从聊天界面下载,无需在你的服务器存储文件。具体修改方案如下:
修改思路
- 用
io.BytesIO在内存中存储图片数据,避免写入本地文件 - 用
discord.File包装内存中的图片数据,转为Discord可识别的附件格式 - 通过交互响应将附件发送给用户(优先用私信,避免频道刷屏)
修改后的代码示例
import io import requests import discord from discord.ui import View, Button class ImageDownloadView(View): def __init__(self, image_url): super().__init__() self.image_url = image_url # 创建下载按钮 download_button = Button(style=discord.ButtonStyle.grey, label='Download', row=1) download_button.callback = self.download self.add_item(download_button) async def download(self, interaction: discord.Interaction): # 修改按钮状态,避免重复点击 self.children[0].style = discord.ButtonStyle.blurple self.children[0].disabled = True await interaction.response.edit_message(view=self) # 请求图片数据 try: response = requests.get(self.image_url) response.raise_for_status() except requests.exceptions.RequestException: await interaction.followup.send("图片下载失败,请稍后重试", ephemeral=True) return # 内存中处理图片数据 image_buffer = io.BytesIO(response.content) # 自动识别图片后缀(也可手动指定) file_suffix = self.image_url.split('.')[-1] if '.' in self.image_url else 'png' discord_file = discord.File(fp=image_buffer, filename=f"download.{file_suffix}") # 发送附件给用户 try: await interaction.user.send(file=discord_file) await interaction.followup.send("图片已发送至你的私信,可直接下载", ephemeral=True) except discord.Forbidden: await interaction.followup.send("无法发送私信,请检查你的隐私设置", ephemeral=True)
关键细节
- 禁用按钮防止用户重复触发下载请求,减轻服务器压力
- 加入异常捕获,处理图片请求失败、无法发送私信等场景
- 用内存缓存替代本地文件写入,避免服务器产生无用文件
内容的提问来源于stack exchange,提问作者Gap
相关产品推荐
相关产品推荐

