티스토리 뷰

[다국어 번역 챗봇]



슬랙 채널에서 각기 다른 언어를 사용하는 유저들이 하나의 언어로 대화할 수 있도록


폰트 사이즈 12 고딕


폰트 사이즈 12 고딕


폰트 사이즈 12 고딕


폰트 사이즈 12 고딕


폰트 사이즈 12 고딕



import requests
from slacker import Slacker
import time
from slackclient import SlackClient


def translate(content, target_lang):
encoding = "utf-8"
url = 'https://translate.googleapis.com/translate_a/single'
params = {'client': 'gtx', 'sl': 'auto', 'tl': target_lang, 'dt': 't', 'q': content, 'ie': encoding}
res = requests.get(url=url, params=params)
res.raise_for_status()
text = ""
for caption in list(res.json())[0]:
text += caption[0]
return text


def notification(chanel, massage, token, bot):
slack = Slacker(token)
slack.chat.post_message('#'+chanel, massage, bot)


def is_head(msg):
if len(msg) > 0 and msg[0] == '#':
return True
return False


def is_lang(msg):
langs = ['en', 'ko', 'ja', 'zh-TW', 'pt', 'fr', 'vi', 'es', 'ar', 'de']
if msg[1:] in langs:
return True
return False


def change_tl(cmd):
return cmd[1:]


def set_params(msg, tl):
body = translate(msg + " [{}]".format(tl), tl)
if is_head(msg):
tl = change_tl(msg) if is_lang(msg) else tl
body = 'changed [{}]'.format(tl) if is_lang(msg) else '[{}] is not found!'.format(msg[1:])
return body, tl


def response(token, chanel, bot):
sc = SlackClient(token)
if sc.rtm_connect():
tl = 'en'
while True:
recive_data = sc.rtm_read()
if len(recive_data):
keys = list(recive_data[0].keys())
if 'type' in keys and 'text' in keys and 'user' in keys:
print(recive_data[0])
body, tl = set_params(recive_data[0]['text'], tl)
notification(chanel, body, token, bot)
time.sleep(1)
else:
print("connection failed")


slack_token = '토큰'
response(slack_token, "dev", 'translate bot')


댓글