嘿Stackoverflow社区,
我是Ruby的新手,正在做一个小项目来安排课程。我必须创建一个使用Google Translate API并返回翻译后文本的移动机器人。
我一直在努力弄清楚如何为机器人编写代码以获取输入的文本并输出翻译。
有人可以看看吗?真的会很感激
def transl8 (input,lang) #method to translate incoming text
# Translates some text into Russian
# Instantiates a client
translate = Google::Cloud::Translate.new project: project-217401
puts input + "Looks like you're speak in #{detection.language}"
puts "Confidence: #{detection.confidence}"
translation = translate.translate input, to: lang
return "In #{lang} that's" + translation
end
def transl8 (input,lang) #method to translate incoming text
detection = $translate.detect input
puts input + "Looks like you're speak in #{detection.language}"
puts "Confidence: #{detection.confidence}"
translation = $translate.translate input, to: lang
return "In #{lang} that's" + translation
end
def listlang #method to show language code
language_code = "en"
languages = $translate.languages
puts "Supported languages:"
languages.each do |language|
puts "#{language.code} #{language.name}"
end
end
configure :development do
require 'dotenv'
Dotenv.load
end
#Translate End-point
https://translation.googleapis.com/language/translate/v2 endpoint
get "/incoming/sms/" do
"Hey! I'm AllSpeak, a translator bot. The list of supported languages are
below. Just ask by typing (TEXT) (space) (Language Code)"
incoming_text = params['Body']
text_to_translate = incoming_text.split(' ')[0]
lang_requested = incoming_text.split(' ')[1]
twiml_body = transl8(text_to_translate, lang_requested)
#return twiml here with twiml_body
end
#Look into Including method to set default language for commonly used
phrases
puts listlang
transl8 (text)
# Build a twilio response object
twiml = Twilio::TwiML::MessagingResponse.new do |r|
r.message do |m|
end
end
答案 0 :(得分:0)
关于Translation API代码:
对于listlang
:
end
循环中缺少do
,并且没有设置project_id变量对于transl8
:
detection
变量示例代码:
#!/usr/bin/ruby
require "google/cloud/translate"
$translate = Google::Cloud::Translate.new project: "slatebot-217401"
def transl8 (input,lang) #method to translate incoming text
detection = $translate.detect input
puts input + "Looks like you're speak in #{detection.language}"
puts "Confidence: #{detection.confidence}"
translation = $translate.translate input, to: lang
return "In #{lang} that's" + translation
end
def listlang #method to show language code
language_code = "en"
languages = $translate.languages
puts "Supported languages:"
languages.each do |language|
puts "#{language.code} #{language.name}"
end
end
答案 1 :(得分:0)
特威里奥的贾罗德。我注意到了您的问题,并建议您解析将发送到您的“传入/短信”的用户SMS。将电话号码配置为向“传入/短信”发出GET请求后,Twilio将开始向该URL发送传入的SMS。当Twilio执行此操作时,它还将在http请求中向您传递一堆信息。传入的SMS正文在请求中作为Body
传递。所以你可以做这样的事情
get '/incoming/sms' do
incoming_text = params['Body']
text_to_translate = incoming_text.split(' ')[0]
lang_requested = incoming_text.split(' ')[1]
twiml_body = transl8(text_to_translate, lang_requested)
#return twiml here with twiml_body
end
这有意义吗?看来您的twiml方法几乎可以使用了,因此只需在响应末尾插入即可,您应该一切顺利!有趣的应用程序。兴奋地看到它完成了!