Python开发Telegram Bot发送PDF/G-drive链接报错求助
问题
我用Python开发Telegram Bot,想让Bot发送PDF文件或Google Drive链接,但运行时报错,报错信息如下:
No error handlers are registered, logging exception. Traceback (most recent call last): File "/home/murgod/.local/lib/python3.9/site-packages/telegram/ext/dispatcher.py", line 557, in process_update handler.handle_update(update, self, check, context) File "/home/murgod/.local/lib/python3.9/site-packages/telegram/ext/handler.py", line 199, in handle_update return self.callback(update, context) File "/home/murgod/KubeBot/KubeBot-4/GKEbot.py", line 217, in send_resume bot.send_document( File "/home/murgod/.local/lib/python3.9/site-packages/telegram/bot.py", line 133, in decorator result = func(*args, **kwargs) File "/home/murgod/.local/lib/python3.9/site-packages/telegram/bot.py", line 976, in send_document return self._message( # type: ignore[return-value] File "/home/murgod/.local/lib/python3.9/site-packages/telegram/bot.py", line 339, in _message result = self._post(endpoint, data, timeout=timeout, api_kwargs=api_kwargs) File "/home/murgod/.local/lib/python3.9/site-packages/telegram/bot.py", line 298, in _post return self.request.post( File "/home/murgod/.local/lib/python3.9/site-packages/telegram/utils/request.py", line 361, in post result = self._request_wrapper( File "/home/murgod/.local/lib/python3.9/site-packages/telegram/utils/request.py", line 279, in _request_wrapper raise BadRequest(message) telegram.error.BadRequest: Wrong file identifier/http url specified
对应的实现代码:
def xyz(update, context): resume_url = '' bot.send_document( chat_id=update.effective_chat.id, document=xyz_url, filename='xyz.pdf', ) xyz_handler = CommandHandler('xyz', xyz) dispatcher.add_handler(xyz_handler)
解决建议
- 修正变量错误:代码里定义的是
resume_url,调用时却用了未定义的xyz_url,且resume_url是空字符串,这直接导致URL无效。先统一变量名,填入有效的文件URL或本地文件路径。 - 处理Google Drive链接:普通G-drive分享链接无法被Telegram Bot识别,需要转换为可直接下载的格式:
- 提取链接中的
FILE_ID,将原链接/file/d/[FILE_ID]/view格式,替换为/uc?id=[FILE_ID]&export=download - 确保目标文件已设置为公开可下载权限,否则Bot无法访问
- 提取链接中的
- 发送本地PDF文件:如果是本地文件,直接传入文件路径即可,比如
document='/home/xxx/xyz.pdf',无需使用URL - 验证URL有效性:先在浏览器打开目标URL,确认能直接下载PDF后,再放到代码中测试
- 添加错误捕获:在函数中加入异常捕获,方便定位问题:
from telegram.error import BadRequest def xyz(update, context): try: # 替换为有效的URL或本地路径 valid_doc = "https://xxx.com/xyz.pdf" context.bot.send_document( chat_id=update.effective_chat.id, document=valid_doc, filename='xyz.pdf' ) except BadRequest as e: update.message.reply_text(f"发送失败:{str(e)}") - 使用context.bot调用方法:推荐用
context.bot替代全局bot变量,避免全局变量引发的潜在问题
内容的提问来源于stack exchange,提问作者Nani
相关产品推荐
相关产品推荐

