開発経緯
twitterで毎日英語の文章を投稿しようと思った時に、英単語が思いつかないことがあり、twitterから日本語→英語変換できれば、Webサイトや別アプリを立ち上げずに済むと思ったので開発しました。
仕様
@cometoprob #tr 変換したい文字列
で「変換したい文字列」に日本語を入力すると英語の変換結果がリプライで返ってきます。
使用したもの
・Twitter API
・Amazon AWS EC2(クラウド上の仮想サーバー)
→Amazon EC2にssh接続し、そこに下記作成のプログラムを移動させ、それを実行することでtwitter bot動かしてます。
メインコード
import config import tweepy import datetime from googletrans import Translator # 先ほど取得した各種キーを代入する CK= config.TW_CONSUMER_KEY CS= config.TW_CONSUMER_SECRET AT= config.TW_TOKEN AS= config.TW_TOKEN_SECRET Twitter_ID = config.TWITTER_ID track_sentence = "@"+Twitter_ID+" #tr" translator = Translator() # Twitterオブジェクトの生成 auth = tweepy.OAuthHandler(CK, CS) auth.set_access_token(AT, AS) api = tweepy.API(auth) #override tweepy.StreamListener to add logic to on_status class MyStreamListener(tweepy.StreamListener): # def on_status(self, status): # print(status.text) def on_status(self, status): status.created_at += datetime.timedelta(hours=9) print("on_status") # example_manから誰かにリプライが送られたら反応 if status.in_reply_to_screen_name is not None: print("reply") reply_format = "@" + str(status.user.screen_name) formatting_input_text = status.text.replace(track_sentence," ",1) trans_en = translator.translate(formatting_input_text) tweet = reply_format + " " + "result:\n" \ + trans_en.text api.update_status(status=tweet) return True def on_error(self, status_code): if status_code == 420: #returning False in on_error disconnects the stream return False else: print('Got an error with status_code:' + str(status_code)) myStreamListener = MyStreamListener() myStream = tweepy.Stream(auth = auth, listener=myStreamListener) myStream.filter(track=[track_sentence])
よろしければ使用してみてください。
now, the function of translation is not working. tomorrow morning, the bot will work. please wait for our mentenance.
— 日本語→英語訳bot (@cometoprob) August 18, 2019