Telegram 机器人无法接收用于图像保存功能的图像

问题描述 投票:0回答:1

我需要一些帮助......

这次我正在为我的 Instagram 销售构建一个小电报机器人......

我想添加一个将图像从机器人保存到Python的功能。

短信可以正常使用,但是...

当我尝试从手机或网络浏览器发送图像时,我的 python 服务器无法接收该图像...

# if photo taken
if awaiting_photo and photo:
    if photo:
        photo_file = await context.bot.get_file(update.message.photo[-1].file_id)
    elif update.message.document:
        photo_file = await context.bot.get_file(update.message.document.file_id)
    else:
        await update.message.reply_text("Please send photo.")

    # Save photo
    photo_path = f"{temp_model_info['model_no']}.jpg"
    await photo_file.download_to_drive(custom_path=photo_path)

    # MODEL_DATA to json
    MODEL_DATA[temp_model_info['model_no']] = {
        "price": temp_model_info['price'],
        "info": "In stocks!!!",
        "image": photo_path
    }
    with open('model_data.json', 'w') as json_file:
        json.dump(MODEL_DATA, json_file, indent=4)

    awaiting_photo = False
    await update.message.reply_text(f"Model {temp_model_info['model_no']} succesfully added..")

    return

我尝试了多种方法,但还是不行。

你们能帮我吗?

谢谢...

python async-await bots telegram python-telegram-bot
1个回答
0
投票

在我向这里的朋友询问后,我通过添加更多功能来修复它。谢谢大家...

async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    global awaiting_photo, temp_model_info
    if awaiting_photo:
        photo = update.message.photo
        if photo:
            # Fotoğraf olarak gönderildi
            photo_file = await context.bot.get_file(update.message.photo[-1].file_id)
        elif update.message.document:
            # Dosya olarak gönderildi
            photo_file = await context.bot.get_file(update.message.document.file_id)
        else:
            # Fotoğraf ya da dosya gönderilmedi
            await update.message.reply_text("Lütfen bir fotoğraf gönderin.")

        # Fotoğrafı kaydet
        photo_path = os.path.join(data_directory, f"{temp_model_info['model_no']}.jpg")
        await photo_file.download_to_drive(custom_path=photo_path)

        # MODEL_DATA güncelle ve JSON'a yaz
        MODEL_DATA[temp_model_info['model_no']] = {
            "price": temp_model_info['price']+"TL",
            "info": "Stoklarda mevcut.",
            "image": photo_path
        }
        with open(model_data_path, 'w') as json_file:
            json.dump(MODEL_DATA, json_file, indent=4)

        awaiting_photo = False
        await update.message.reply_text(f"Model {temp_model_info['model_no']} başarıyla eklendi.")

并将其添加到主函数中...

application.add_handler(MessageHandler(filters.PHOTO, handle_photo))
© www.soinside.com 2019 - 2024. All rights reserved.