记上一篇 搭建OCR 机器人
先决条件
在Azure开通计算机视觉服务,获取密钥和终结点
在Telegram@BotFather获取token
开始搭建
复制这里面的代码到你的小鸡
```
import time
import logging
import os
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
from azure.ai.translation.text import TextTranslationClient, TranslatorCredential
from azure.ai.translation.text.models import InputTextItem
from azure.core.exceptions import HttpResponseError
设置日志记录
logging.basicConfig(format=‘%(asctime)s - %(name)s - %(levelname)s - %(message)s’, level=logging.INFO)
Azure 订阅密钥和端点
endpoint = ‘xxx’
region = “eastasia”
key = “xxx”
创建客户端
credential = TranslatorCredential(key, region)
text_translator = TextTranslationClient(endpoint=endpoint, credential=credential)
async def start(update: Update, context: CallbackContext) -> None:
await update.message.reply_text(‘欢迎使用translation Bot,请输入文字。’)
async def handle_image(update: Update, context: CallbackContext) -> None:
await update.message.reply_text(‘这是一个翻译机器人,它只能文字。’)
async def translate_text(update: Update, context: CallbackContext) -> None:
user_message = update.message.text
message = await update.message.reply_text(‘正在翻译,请稍等…’)
location, also known as region.
required if you’re using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
try:
source_language = “en”
target_languages = [“zh-Hans”]
input_text_elements = [ InputTextItem(text = user_message) ]
response = text_translator.translate(content = input_text_elements, to = target_languages, from_parameter = source_language)
translation = response[0] if response else None
if translation:
for translated_text in translation.translations:
await update.message.reply_text('识别结果:\n'+ translated_text.text)
except HttpResponseError as exception:
print(f"Error Code: {exception.error.code}“)
print(f"Message: {exception.error.message}”)
def main() -> None:
用你的Bot Token替换’token’
application = Application.builder().token(‘token’).build()
application.add_handler(CommandHandler(‘start’, start))
application.add_handler(MessageHandler(filters.PHOTO, handle_image))
application.add_handler(MessageHandler(filters.TEXT, translate_text))
application.run_polling()
if name == ‘main’:
main()
```
替换密钥和终结点点,以及Bot Token为你自己前面获取的东西
安装依赖pip install azure-ai-translation-text==1.0.0b1
python3 app.py