Closed as not planned
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.message.reply_document(f, caption='本地文件直传')
new_file_id = msg.document.file_id
request = HTTPXRequest(
connect_timeout=60.0, # Connection timeout
read_timeout=1810.0, # Should be > TDLIB_UPLOAD_FILE_TIMEOUT
write_timeout=1810.0, # Should be > TDLIB_UPLOAD_FILE_TIMEOUT
pool_timeout=60.0, # Pool timeout
media_write_timeout=1810.0
)
builder = ApplicationBuilder().token(TOKEN).request(request)
Can someone help me? If I add .request(request), it will report this error
But file can be sent successfully.
.request(request) If there is no such thing, it will prompt a timeout, but the file can still be sent successfully
I 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
Traceback to the issue
Can not load invalid JSON data: ""
Traceback (most recent call last):
File "C:\Users\123\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\telegram\request\_baserequest.py",
line 380, in parse_json_payload
return json.loads(decoded_s)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Traceback (most recent call last):
File "c:\Users\123\Desktop\1\mytgbot\docker_txttg\new_tg_bot.py", line 536, in <module>
main()
File "c:\Users\123\Desktop\1\mytgbot\docker_txttg\new_tg_bot.py", line 533, in main
app.run_polling()
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
return self.__run(
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
loop.run_until_complete(self.updater.stop()) # type: ignore[union-attr]
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
self.run_forever()
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
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
self._run_once()
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
event_list = self._selector.select(timeout)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\windows_events.py", line 439, in select
self._poll(timeout)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\windows_events.py", line 788, in _poll
status = _overlapped.GetQueuedCompletionStatus(self._iocp, ms)
KeyboardInterrupt
Related part of your code
async def on_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
args = context.args
if not args and update.message:
# 兼容 /start 无参数
await update.message.reply_text('欢迎使用本bot!')
return
# 支持 deep link
if update.message:
start_param = update.message.text.split(' ', 1)[1] if ' ' in update.message.text else ''
elif update.callback_query:
start_param = update.callback_query.data.split(' ', 1)[1] if ' ' in update.callback_query.data else ''
else:
start_param = ''
if start_param.startswith('book_'):
# 检查用户权限
user_id = update.effective_user.id
# 只解析 file_id
try:
parts = start_param.split('_')
file_id = int(parts[1])
except Exception:
await update.message.reply_text('参数错误。')
return
with SessionLocal() as session:
file = session.query(File).filter_by(file_id=file_id).first()
if not file:
await update.message.reply_text('文件不存在。')
return
tg_file_id, file_path = file.tg_file_id, file.file_path
try:
if tg_file_id and (tg_file_id.startswith('BQAC') or tg_file_id.startswith('CAAC') or tg_file_id.startswith('HDAA')):
await update.message.reply_document(tg_file_id, caption=f'文件tg_file_id: {tg_file_id}')
elif tg_file_id and tg_file_id.startswith('BAAC'):
await update.message.reply_video(tg_file_id, caption=f'文件tg_file_id: {tg_file_id}')
elif tg_file_id and tg_file_id.startswith('AgAC'):
await update.message.reply_photo(tg_file_id, caption=f'文件tg_file_id: {tg_file_id}')
elif tg_file_id is None or tg_file_id == '':
ext = os.path.splitext(file_path)[1].lower()
if ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']:
with open(file_path, 'rb') as f:
msg = await update.message.reply_photo(f, caption='本地图片直传')
new_file_id = msg.photo[-1].file_id if msg.photo else None
elif ext in ['.mp4', '.mov', '.avi', '.mkv', '.webm']:
with open(file_path, 'rb') as f:
msg = await update.message.reply_video(f, caption='本地视频直传')
new_file_id = msg.video.file_id
elif os.path.exists(file_path):
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.message.reply_document(f, caption='本地文件直传')
new_file_id = msg.document.file_id
else:
await update.message.reply_text('文件丢失。')
return
# 关键:本地直传后写入tg_file_id
if new_file_id:
with SessionLocal() as session:
file = session.query(File).filter_by(file_id=file_id).first()
if file:
file.tg_file_id = new_file_id
session.commit()
elif os.path.exists(file_path):
ext = os.path.splitext(file_path)[1].lower()
if ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']:
with open(file_path, 'rb') as f:
await update.message.reply_photo(f, caption=f'文件tg_file_id: {tg_file_id}')
elif ext in ['.mp4', '.mov', '.avi', '.mkv', '.webm']:
with open(file_path, 'rb') as f:
await update.message.reply_video(f, caption=f'文件tg_file_id: {tg_file_id}')
else:
with open(file_path, 'rb') as f:
await update.message.reply_document(f, caption=f'文件tg_file_id: {tg_file_id}')
else:
await update.message.reply_text('文件丢失。')
except Exception as e:
await update.message.reply_text(f'发送失败: {e}')
def main():
upgrade_users_table() # 启动时自动升级users表结构
base_url = os.getenv('TELEGRAM_API_URL')
request = HTTPXRequest(
connect_timeout=60.0, # Connection timeout
read_timeout=1810.0, # Should be > TDLIB_UPLOAD_FILE_TIMEOUT
write_timeout=1810.0, # Should be > TDLIB_UPLOAD_FILE_TIMEOUT
pool_timeout=60.0, # Pool timeout
media_write_timeout=1810.0
)
builder = ApplicationBuilder().token(TOKEN).request(request)
if base_url:
builder = builder.base_url(f"{base_url}/bot").base_file_url(f"{base_url}/file/bot")
app = builder.build()
# 用 post_init 钩子自动注入 bot 用户名
async def set_username(app):
me = await app.bot.get_me()
set_bot_username(me.username)
app.post_init = set_username
app.add_handler(CommandHandler('start', on_start))
app.run_polling()
if __name__ == '__main__':
main()
Operating System
win10
Version of Python, python-telegram-bot & dependencies
python-telegram-bot 22.1
Bot API 9.0
Python 3.9.13 (tags/v3.9.13:6de2ca5, May 17 2022, 16:36:42) [MSC v.1929 64 bit (AMD64)]