You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python开发Telegram图片翻译机器人:接收图片及API适配问题求助

问题分析

你当前的代码存在两个核心问题:

  1. 混用Telegram Bot开发库:同时导入了telebot(pyTelegramBotAPI)和telegram.ext(python-telegram-bot)两个完全独立的库,二者API不兼容,导致代码逻辑混乱。
  2. 同步/异步方法误用:用telebot.TeleBot创建的是同步Bot实例,其所有方法都是同步的,不能用await调用,这是你await语句失效的直接原因。
  3. 旧版API依赖:python-telegram-bot v20+确实移除了Updater和Dispatcher,改用Application作为核心入口。
解决方案

下面提供两种适配你需求的修正方案,选择其一即可:


方案一:基于pyTelegramBotAPI(适配你现有代码)

保留你当前使用的pyTelegramBotAPI,用同步方法处理图片,无需asyncio:

修正后完整代码

try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract
import os
import telebot
from dotenv import load_dotenv, find_dotenv
import io
from googletrans import Translator

load_dotenv(find_dotenv())

BOT_TOKEN = os.environ.get('BOT_TOKEN')
bot = telebot.TeleBot(BOT_TOKEN)
pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\tesseract\\tesseract.exe'

@bot.message_handler(commands=['start', 'hello'])
def send_welcome(message):
    bot.reply_to(message, "Welcome")

@bot.message_handler(commands=['translate'])
def prompt_for_photo(message):
    sent_msg = bot.send_message(message.chat.id, "Send a picture you want to translate")
    bot.register_next_step_handler(sent_msg, process_translation_photo)

def process_translation_photo(message):
    # 校验是否为图片消息
    if not message.photo:
        bot.send_message(message.chat.id, "请发送图片!")
        return
    
    chat_id = message.chat.id
    # 获取最高分辨率的图片file_id
    photo = message.photo[-1].file_id
    # 同步获取文件信息并下载字节流
    file_info = bot.get_file(photo)
    file_bytes = bot.download_file(file_info.file_path)
    
    # OCR识别日文
    image = Image.open(io.BytesIO(file_bytes))
    text = pytesseract.image_to_string(image, config='-l jpn')
    
    # 翻译文本
    translator = Translator()
    translated_text = translator.translate(text, dest='uk').text
    
    # 返回结果
    bot.send_message(chat_id, f"识别结果:\n{text}\n\n翻译结果:\n{translated_text}")

# 直接处理用户主动发送的图片
@bot.message_handler(content_types=['photo'])
def handle_direct_photo(message):
    process_translation_photo(message)

bot.infinity_polling()

方案二:基于python-telegram-bot v20+(推荐,原生支持异步)

改用最新版python-telegram-bot,适配其API变更:

步骤1:安装/升级库

pip install python-telegram-bot --upgrade

修正后完整代码

try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract
import os
from dotenv import load_dotenv, find_dotenv
import io
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
from googletrans import Translator

load_dotenv(find_dotenv())

BOT_TOKEN = os.environ.get('BOT_TOKEN')
pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\tesseract\\tesseract.exe'

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Welcome")

async def prompt_translate(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Send a picture you want to translate")
    # 标记用户状态,等待接收图片
    context.user_data['awaiting_photo'] = True

async def process_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 仅处理处于翻译请求状态的用户
    if not context.user_data.get('awaiting_photo', False):
        return
    
    chat_id = update.effective_chat.id
    # 获取最高分辨率图片
    photo = update.message.photo[-1]
    # 异步下载图片字节流
    file = await context.bot.get_file(photo.file_id)
    file_bytes = await file.download_as_bytearray()
    
    # OCR识别与翻译
    image = Image.open(io.BytesIO(file_bytes))
    text = pytesseract.image_to_string(image, config='-l jpn')
    translator = Translator()
    translated_text = translator.translate(text, dest='uk').text
    
    # 返回结果并重置状态
    await update.message.reply_text(f"识别结果:\n{text}\n\n翻译结果:\n{translated_text}")
    context.user_data['awaiting_photo'] = False

def main():
    # 创建Application实例替代旧的Updater/Dispatcher
    application = ApplicationBuilder().token(BOT_TOKEN).build()
    
    # 注册命令与消息处理器
    application.add_handler(CommandHandler(["start", "hello"], start))
    application.add_handler(CommandHandler("translate", prompt_translate))
    application.add_handler(MessageHandler(filters.PHOTO, process_photo))
    
    application.run_polling()

if __name__ == '__main__':
    main()

内容的提问来源于stack exchange,提问作者Oleksa24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 00:45:01