如何使用Python从URL下载PDF文件并直接作为附件发送到Discord?
从URL下载PDF并发送到Discord附件实现方案
现有代码问题
- 变量未定义:代码中传入
discord.File的file变量没有被赋值,实际请求获取到的内容存储在sendAttachement变量中,二者没有关联 - 参数使用错误:
ctx.send方法不存在url传参,发送附件需要使用file或files参数 - 缺少类文件对象转换:
discord.File仅支持接收本地文件路径或类文件对象,无法直接识别requests请求返回的响应体
正确实现
首先需要导入io.BytesIO用于包装二进制文件内容,完整可运行代码如下:
import requests import io import discord # 保留你原有的bot初始化、命令注册等其他代码 urls = [f'https://documents.pse.com.ph/market_report/{monthf}%20{dayf},%20{year}-EOD.pdf'] for eodfiles in urls: sendAttachement = requests.get(eodfiles) if sendAttachement.status_code == 200: # 将请求返回的二进制PDF内容包装为类文件对象 pdf_binary = io.BytesIO(sendAttachement.content) # 构造Discord支持的文件对象 send_file = discord.File(pdf_binary, filename="EOD.pdf") # 传入file参数发送附件 await ctx.send(file=send_file) else: await ctx.send("No file available")
异步优化建议
如果你的项目使用discord.py 2.0+版本,为避免同步请求requests阻塞事件循环,可改用异步请求库aiohttp实现:
import aiohttp import io import discord # 保留原有其他代码 urls = [f'https://documents.pse.com.ph/market_report/{monthf}%20{dayf},%20{year}-EOD.pdf'] for eodfiles in urls: async with aiohttp.ClientSession() as session: async with session.get(eodfiles) as resp: if resp.status == 200: pdf_binary = io.BytesIO(await resp.read()) send_file = discord.File(pdf_binary, filename="EOD.pdf") await ctx.send(file=send_file) else: await ctx.send("No file available")
内容的提问来源于stack exchange,提问作者awt
相关产品推荐
相关产品推荐

