René's URL Explorer Experiment


Title: input_file = InputFile(f, read_file_handle=False) · Issue #4821 · python-telegram-bot/python-telegram-bot · GitHub

Open Graph Title: input_file = InputFile(f, read_file_handle=False) · Issue #4821 · python-telegram-bot/python-telegram-bot

X Title: input_file = InputFile(f, read_file_handle=False) · Issue #4821 · python-telegram-bot/python-telegram-bot

Description: Issue I am facing with open(file_path, 'rb') as f: input_file = InputFile(f, read_file_handle=False) msg = await update.message.reply_document(input_file, caption='本地文件直传', write_timeout=300, connect_timeout=30) #msg = await update.messa...

Open Graph Description: Issue I am facing with open(file_path, 'rb') as f: input_file = InputFile(f, read_file_handle=False) msg = await update.message.reply_document(input_file, caption='本地文件直传', write_timeout=300, conne...

X Description: Issue I am facing with open(file_path, 'rb') as f: input_file = InputFile(f, read_file_handle=False) msg = await update.message.reply_document(input_file, caption='本地文件直传', write_ti...

Opengraph URL: https://github.com/python-telegram-bot/python-telegram-bot/issues/4821

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"input_file = InputFile(f, read_file_handle=False)","articleBody":"### Issue I am facing\n\n\n```\n                    with open(file_path, 'rb') as f:\n                        input_file = InputFile(f, read_file_handle=False)\n                        msg = await update.message.reply_document(input_file, caption='本地文件直传', write_timeout=300, connect_timeout=30)\n                        #msg = await update.message.reply_document(f, caption='本地文件直传')\n                        new_file_id = msg.document.file_id\n```\n```\n    request = HTTPXRequest(\n        connect_timeout=60.0,   # Connection timeout\n        read_timeout=1810.0,    # Should be \u003e TDLIB_UPLOAD_FILE_TIMEOUT\n        write_timeout=1810.0,   # Should be \u003e TDLIB_UPLOAD_FILE_TIMEOUT\n        pool_timeout=60.0,       # Pool timeout\n        media_write_timeout=1810.0\n    )\n    builder = ApplicationBuilder().token(TOKEN).request(request)\n```\nCan someone help me? If I add .request(request), it will report this error\n\nBut  file can be sent successfully.\n\n.request(request) If there is no such thing, it will prompt a timeout, but the file can still be sent successfully\n\nI have used my own API, (https://github.com/aiogram/telegram-bot-api) and there is no problem sending small files, but there is a problem with large files\n\n### Traceback to the issue\n\n```python\nCan not load invalid JSON data: \"\"\nTraceback (most recent call last):\n  File \"C:\\Users\\123\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python39\\site-packages\\telegram\\request\\_baserequest.py\", \nline 380, in parse_json_payload\n    return json.loads(decoded_s)\n  File \"C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\\lib\\json\\__init__.py\", line 346, in loads\n    return _default_decoder.decode(s)\n  File \"C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\\lib\\json\\decoder.py\", line 337, in decode\n    obj, end = self.raw_decode(s, idx=_w(s, 0).end())\n  File \"C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\\lib\\json\\decoder.py\", line 355, in raw_decode\n    raise JSONDecodeError(\"Expecting value\", s, err.value) from None\njson.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)\nTraceback (most recent call last):\n  File \"c:\\Users\\123\\Desktop\\1\\mytgbot\\docker_txttg\\new_tg_bot.py\", line 536, in \u003cmodule\u003e\n    main()\n  File \"c:\\Users\\123\\Desktop\\1\\mytgbot\\docker_txttg\\new_tg_bot.py\", line 533, in main\n    app.run_polling()\n  File \"C:\\Users\\123\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python39\\site-packages\\telegram\\ext\\_application.py\", line 832, in run_polling\n    return self.__run(\n  File \"C:\\Users\\123\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python39\\site-packages\\telegram\\ext\\_application.py\", line 1061, in __run\n    loop.run_until_complete(self.updater.stop())  # type: ignore[union-attr]\n  File \"C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\\lib\\asyncio\\base_events.py\", line 634, in run_until_complete\n    self.run_forever()\n  File \"C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\\lib\\asyncio\\windows_events.py\", line 321, in run_forever\n  File \"C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\\lib\\asyncio\\base_events.py\", line 601, in run_forever\n    self._run_once()\n  File \"C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\\lib\\asyncio\\base_events.py\", line 1869, in _run_once\n    event_list = self._selector.select(timeout)\n  File \"C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\\lib\\asyncio\\windows_events.py\", line 439, in select\n    self._poll(timeout)\n  File \"C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\\lib\\asyncio\\windows_events.py\", line 788, in _poll\n    status = _overlapped.GetQueuedCompletionStatus(self._iocp, ms)\nKeyboardInterrupt\n```\n\n### Related part of your code\n\n```python\nasync def on_start(update: Update, context: ContextTypes.DEFAULT_TYPE):\n    args = context.args\n    if not args and update.message:\n        # 兼容 /start 无参数\n        await update.message.reply_text('欢迎使用本bot!')\n        return\n    # 支持 deep link\n    if update.message:\n        start_param = update.message.text.split(' ', 1)[1] if ' ' in update.message.text else ''\n    elif update.callback_query:\n        start_param = update.callback_query.data.split(' ', 1)[1] if ' ' in update.callback_query.data else ''\n    else:\n        start_param = ''\n    \n    if start_param.startswith('book_'):\n        # 检查用户权限\n        user_id = update.effective_user.id\n            \n        # 只解析 file_id\n        try:\n            parts = start_param.split('_')\n            file_id = int(parts[1])\n        except Exception:\n            await update.message.reply_text('参数错误。')\n            return\n        with SessionLocal() as session:\n            file = session.query(File).filter_by(file_id=file_id).first()\n        if not file:\n            await update.message.reply_text('文件不存在。')\n            return\n        tg_file_id, file_path = file.tg_file_id, file.file_path\n        try:\n            if tg_file_id and (tg_file_id.startswith('BQAC') or tg_file_id.startswith('CAAC') or tg_file_id.startswith('HDAA')):\n                await update.message.reply_document(tg_file_id, caption=f'文件tg_file_id: {tg_file_id}')\n            elif tg_file_id and tg_file_id.startswith('BAAC'):\n                await update.message.reply_video(tg_file_id, caption=f'文件tg_file_id: {tg_file_id}')\n            elif tg_file_id and tg_file_id.startswith('AgAC'):\n                await update.message.reply_photo(tg_file_id, caption=f'文件tg_file_id: {tg_file_id}')\n            elif tg_file_id is None or tg_file_id == '':\n                ext = os.path.splitext(file_path)[1].lower()\n                if ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']:\n                    with open(file_path, 'rb') as f:\n                        msg = await update.message.reply_photo(f, caption='本地图片直传')\n                        new_file_id = msg.photo[-1].file_id if msg.photo else None\n                elif ext in ['.mp4', '.mov', '.avi', '.mkv', '.webm']:\n                    with open(file_path, 'rb') as f:\n        \n                        msg = await update.message.reply_video(f, caption='本地视频直传')\n                        new_file_id = msg.video.file_id\n                elif os.path.exists(file_path):\n                    with open(file_path, 'rb') as f:\n                        input_file = InputFile(f, read_file_handle=False)\n                        msg = await update.message.reply_document(input_file, caption='本地文件直传', write_timeout=300, connect_timeout=30)\n                        #msg = await update.message.reply_document(f, caption='本地文件直传')\n                        new_file_id = msg.document.file_id\n                else:\n                    await update.message.reply_text('文件丢失。')\n                    return\n                # 关键:本地直传后写入tg_file_id\n                if new_file_id:\n                    with SessionLocal() as session:\n                        file = session.query(File).filter_by(file_id=file_id).first()\n                        if file:\n                            file.tg_file_id = new_file_id\n                            session.commit()\n            elif os.path.exists(file_path):\n                ext = os.path.splitext(file_path)[1].lower()\n                if ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']:\n                    with open(file_path, 'rb') as f:\n                        await update.message.reply_photo(f, caption=f'文件tg_file_id: {tg_file_id}')\n                elif ext in ['.mp4', '.mov', '.avi', '.mkv', '.webm']:\n                    with open(file_path, 'rb') as f:\n                        await update.message.reply_video(f, caption=f'文件tg_file_id: {tg_file_id}')\n                else:\n                    with open(file_path, 'rb') as f:\n                        await update.message.reply_document(f, caption=f'文件tg_file_id: {tg_file_id}')\n            else:\n                await update.message.reply_text('文件丢失。')\n        except Exception as e:\n            await update.message.reply_text(f'发送失败: {e}')\n\ndef main():\n    upgrade_users_table()  # 启动时自动升级users表结构\n    base_url = os.getenv('TELEGRAM_API_URL')\n    request = HTTPXRequest(\n        connect_timeout=60.0,   # Connection timeout\n        read_timeout=1810.0,    # Should be \u003e TDLIB_UPLOAD_FILE_TIMEOUT\n        write_timeout=1810.0,   # Should be \u003e TDLIB_UPLOAD_FILE_TIMEOUT\n        pool_timeout=60.0,       # Pool timeout\n        media_write_timeout=1810.0\n    )\n    builder = ApplicationBuilder().token(TOKEN).request(request)\n    if base_url:\n        builder = builder.base_url(f\"{base_url}/bot\").base_file_url(f\"{base_url}/file/bot\")\n    app = builder.build()\n\n    # 用 post_init 钩子自动注入 bot 用户名\n    async def set_username(app):\n        me = await app.bot.get_me()\n        set_bot_username(me.username)\n    app.post_init = set_username\n    app.add_handler(CommandHandler('start', on_start))\n\n\n    app.run_polling()\n\nif __name__ == '__main__':\n    main()\n```\n\n### Operating System\n\nwin10\n\n### Version of Python, python-telegram-bot \u0026 dependencies\n\n```shell\npython-telegram-bot 22.1\nBot API 9.0\nPython 3.9.13 (tags/v3.9.13:6de2ca5, May 17 2022, 16:36:42) [MSC v.1929 64 bit (AMD64)]\n```","author":{"url":"https://github.com/aiastia","@type":"Person","name":"aiastia"},"datePublished":"2025-06-09T06:19:36.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":10},"url":"https://github.com/4821/python-telegram-bot/issues/4821"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:790af697-fc74-65a0-e123-a4f94c8bb947
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idD83A:3FD786:2504E2:317A95:6A5CB972
html-safe-nonce75b7be869e74d645c6120871573387625d9558d7704f9f893920c072925b75cb
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEODNBOjNGRDc4NjoyNTA0RTI6MzE3QTk1OjZBNUNCOTcyIiwidmlzaXRvcl9pZCI6IjU3NjkxNDkzNzU0MjQ4MDUyMzQiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ==
visitor-hmacaac3d3b5a0ebeefad8a49d98ffb1a6a81c51aee02be6f5b35ffc09a7cdc60541
hovercard-subject-tagissue:3129279717
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python-telegram-bot/python-telegram-bot/4821/issue_layout
twitter:imagehttps://opengraph.githubassets.com/33965fbf5de63c53d6f00d88daeef01a3446f043e27f01e7d1f885a1887abf51/python-telegram-bot/python-telegram-bot/issues/4821
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/33965fbf5de63c53d6f00d88daeef01a3446f043e27f01e7d1f885a1887abf51/python-telegram-bot/python-telegram-bot/issues/4821
og:image:altIssue I am facing with open(file_path, 'rb') as f: input_file = InputFile(f, read_file_handle=False) msg = await update.message.reply_document(input_file, caption='本地文件直传', write_timeout=300, conne...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernameaiastia
hostnamegithub.com
expected-hostnamegithub.com
None5290d7e14309ad1e76106a9c4237bd1041517e83ea182c8ab756752cb0c6940b
turbo-cache-controlno-preview
go-importgithub.com/python-telegram-bot/python-telegram-bot git https://github.com/python-telegram-bot/python-telegram-bot.git
octolytics-dimension-user_id16178365
octolytics-dimension-user_loginpython-telegram-bot
octolytics-dimension-repository_id38696925
octolytics-dimension-repository_nwopython-telegram-bot/python-telegram-bot
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id38696925
octolytics-dimension-repository_network_root_nwopython-telegram-bot/python-telegram-bot
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release9c975978430e9ad293956f2bbdaf153b1bd84a99
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/python-telegram-bot/python-telegram-bot/issues/4821#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython-telegram-bot%2Fpython-telegram-bot%2Fissues%2F4821
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub Copilot appDirect agents from issue to mergehttps://github.com/features/ai/github-app
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
View all resourceshttps://github.com/resources
GitHub SponsorsFund open source developershttps://github.com/open-source/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/open-source/accelerator
GitHub Starshttps://stars.github.com
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython-telegram-bot%2Fpython-telegram-bot%2Fissues%2F4821
Sign up https://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=python-telegram-bot%2Fpython-telegram-bot
Reloadhttps://github.com/python-telegram-bot/python-telegram-bot/issues/4821
Reloadhttps://github.com/python-telegram-bot/python-telegram-bot/issues/4821
Reloadhttps://github.com/python-telegram-bot/python-telegram-bot/issues/4821
Please reload this pagehttps://github.com/python-telegram-bot/python-telegram-bot/issues/4821
python-telegram-bot https://github.com/python-telegram-bot
python-telegram-bothttps://github.com/python-telegram-bot/python-telegram-bot
Notifications https://github.com/login?return_to=%2Fpython-telegram-bot%2Fpython-telegram-bot
Fork 6.1k https://github.com/login?return_to=%2Fpython-telegram-bot%2Fpython-telegram-bot
Star 29.3k https://github.com/login?return_to=%2Fpython-telegram-bot%2Fpython-telegram-bot
Code https://github.com/python-telegram-bot/python-telegram-bot
Issues 24 https://github.com/python-telegram-bot/python-telegram-bot/issues
Pull requests 9 https://github.com/python-telegram-bot/python-telegram-bot/pulls
Discussions https://github.com/python-telegram-bot/python-telegram-bot/discussions
Actions https://github.com/python-telegram-bot/python-telegram-bot/actions
Projects https://github.com/python-telegram-bot/python-telegram-bot/projects
Wiki https://github.com/python-telegram-bot/python-telegram-bot/wiki
Security and quality 0 https://github.com/python-telegram-bot/python-telegram-bot/security
Insights https://github.com/python-telegram-bot/python-telegram-bot/pulse
Code https://github.com/python-telegram-bot/python-telegram-bot
Issues https://github.com/python-telegram-bot/python-telegram-bot/issues
Pull requests https://github.com/python-telegram-bot/python-telegram-bot/pulls
Discussions https://github.com/python-telegram-bot/python-telegram-bot/discussions
Actions https://github.com/python-telegram-bot/python-telegram-bot/actions
Projects https://github.com/python-telegram-bot/python-telegram-bot/projects
Wiki https://github.com/python-telegram-bot/python-telegram-bot/wiki
Security and quality https://github.com/python-telegram-bot/python-telegram-bot/security
Insights https://github.com/python-telegram-bot/python-telegram-bot/pulse
❔ questionhttps://github.com/python-telegram-bot/python-telegram-bot/issues?q=type:"❔ question"
input_file = InputFile(f, read_file_handle=False)https://github.com/python-telegram-bot/python-telegram-bot/issues/4821#top
https://github.com/aiastia
aiastiahttps://github.com/aiastia
on Jun 9, 2025https://github.com/python-telegram-bot/python-telegram-bot/issues/4821#issue-3129279717
https://github.com/aiogram/telegram-bot-apihttps://github.com/aiogram/telegram-bot-api
❔ questionhttps://github.com/python-telegram-bot/python-telegram-bot/issues?q=type:"❔ question"
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.