LoginSignup
12
10

More than 5 years have passed since last update.

Google Apps Scriptを使ってらくらくTypetalk BOT開発③ 応用編 メンションに反応する翻訳Botを作ってみた

Posted at

最近手脂がすごい大橋です。

一昨日から書いているTypetalk BOTの話ですが、今日で最後です。

一応昨日までに

の二つのエントリーを書きました。
今日はよくあるメンションに対して反応する翻訳Botを作ってみたいと思います。

ゴール

以下の感じになります。

スクリーンショット 2014-03-06 18.40.18.png

@translatebot transate 翻訳したい語句 to ja|en

という感じの書式で翻訳元言語は自由、翻訳後は日本語か英語という感じで組みたいと思います。

なお@translatebotを何かしらのトピックに招待すれば(試すならテストトピックとか)利用可能なのですが、
Bot自体のトピックへの参加許可は現状手動で実施する必要があり、
めんどく.... 忙しいためすぐに取り込めない可能性があります。

あとエラーハンドリングちゃんとしてないので、うまく動かなくても知りません。自己責任でご利用を!
また今回翻訳Bot用のNulabアカウントを取得していますが、規約的に良いか微妙なのでいつか消すと想います。

そのうちBot用のアカウントとか、アカウントとらなくてもBotが動かせるようになるのかしら。

フルコード

書いてみた全体のコードは以下です。
自身でコピペ動かす場合は最初の記事を参考に
TypetalkAppライブラリを動かせるようにして、
ScriptPropertyにclientId、clientSecretを設定し
Triggerを1分一回とか5分一回とかに設定して下さい。

TranslateBot.js
function handleMensions() {


  var lock = LockService.getPrivateLock();

  //1分に1回とかの頻度で動かすので動いている最中の場合はスキップ
  if(!lock.tryLock(1000)) {
    Logger.log("oops, right now working");
    return;
  }

  //設定はScriptPropertiesに
  var prop = PropertiesService.getScriptProperties().getProperties();

  var typetalkApp = TypetalkApp.create(prop.clientId,
                                       prop.clientSecret, 
                                       [TypetalkApp.SCOPE_MY, TypetalkApp.SCOPE_TOPIC_POST, TypetalkApp.SCOPE_TOPIC_READ],
                                       {name : "translateBot"});

  //未認可の場合は認可 、今回のケースではBot宛にメンションが送られてきて、Botがメンションを返すので、Client CredentialsでOK
  typetalkApp.isAuthorized() || typetalkApp.authorize();

  //未読のメンションを取得
  var mentions = typetalkApp.getMentions({unread:true});

  (mentions.mentions || []).forEach(function(mention){

    //もろもろ必要な物を取得
    var topicId = mention.post.topic.id;
    var message = mention.post.message;
    var postId = mention.post.id;
    var account = mention.post.account.name;

    var separated = message.split(" ");

    //フォーマットを一応軽くチェック
    if(separated.length <= 4 || separated[1] != "translate") {
      return;
    }

    //翻訳対象を取得
    var target = "";
    for(var i = 2; i < separated.length - 2; i++) {
      target += separated[i] + " ";
    }

    //「翻訳やるお」を通知
    typetalkApp.postMessage(topicId, "@" + account + " Please wait, right now translating '" + target +"'....", {replyTo : postId});


    //翻訳
    var result = LanguageApp.translate(target, "", separated[separated.length - 1] == "en" ? "en" : "ja");

    //翻訳結果のメッセージをreplyTo形式で投げて
    typetalkApp.postMessage(topicId, result, {replyTo : postId});

    //メンションを既読に
    typetalkApp.openMention(mention.id);

    Utilities.sleep(1000);

  });

  lock.releaseLock();


}

まとめ

3日連チャンで書きましたがいかがだったでしょうか?
TypetalkのようなAPIがしっかりしたサービスとGASはかなり相性がよく、
Googleのサービス郡と繋ぎやすくなります。

是非色々実装してみてください☆

12
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
10