Skip to content

Instantly share code, notes, and snippets.

@elliottcordo
Last active January 27, 2020 20:01
Show Gist options
  • Save elliottcordo/3e342da1535a3614c8ee4b3646e70169 to your computer and use it in GitHub Desktop.
Save elliottcordo/3e342da1535a3614c8ee4b3646e70169 to your computer and use it in GitHub Desktop.
Translate-a-tron.py
import boto3
import os
import slack
from pprint import pprint
SLACK_API_TOKEN = os.environ["SLACK_API_TOKEN"]
BOT_ID = '<@UT4N8STGX>'
FLAG_MAP = {
':flag-mx:': 'es',
':flag-cn:': 'zh',
':flag-ae:': 'ar',
':flag-fr:': 'fr',
':flag-it:': 'it',
':flag-ge:': 'de',
':flag-jp:': 'ja',
':flag-ru:': 'ru',
':flag-br:': 'pt',
':flag-ar:': 'es',
':flag-pt:': 'pt',
':flag-us:': 'en'
}
def parse_flags(text):
language = 'es' # default
for flag in FLAG_MAP.keys():
if flag in text:
language = FLAG_MAP[flag]
text = text.replace(flag, '')
return text, language
def translate(text, language):
translate = boto3.client(service_name='translate', use_ssl=True)
result = translate.translate_text(Text=text, SourceLanguageCode = 'auto',
TargetLanguageCode=language)
translate_text = (result.get('TranslatedText'))
print('SourceLanguageCode: ' + result.get('SourceLanguageCode'))
print('TargetLanguageCode: ' + result.get('TargetLanguageCode'))
print(f'TranslatedText: {translate_text}')
return translate_text
def send_message(message):
client = slack.WebClient(token=SLACK_API_TOKEN)
response = client.chat_postMessage(
channel='#minihack-aws-translate',
text=message,
as_user='translate-a-tron'
)
assert response["ok"]
assert response["message"]["text"] == message
@slack.RTMClient.run_on(event='message')
def say_hello(**payload):
data = payload['data']
pprint(data)
web_client = payload['web_client']
text = str(data.get('text', ''))
print(f'message text: {text}')
if BOT_ID in text:
channel_id = data['channel']
parsed_text, language = parse_flags(text)
# thread_ts = data['ts']
# user = data['user']
web_client.chat_postMessage(
channel=channel_id,
text=translate(parsed_text.replace('<@UT4N8STGX>', ''),language),
as_user='translate-a-tron')
rtm_client = slack.RTMClient(token=SLACK_API_TOKEN)
rtm_client.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment