This repository has been archived by the owner on Dec 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
app.py
129 lines (109 loc) · 4.11 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#
# A Python implementation of https://github.com/slackapi/reacjilator
#
# Author: Kazuhiro Sera @seratch
# MIT License as with the original code
#
import re
import os
import json
# Google
from google.cloud import translate
import six
import html
# Slack
import slack
from slackeventsapi import SlackEventAdapter
# --------------------
# Slack API
# Slack Web API Client with sufficient permissions
slack_web_api_client = slack.WebClient(token=os.environ['SLACK_API_TOKEN'])
# In order for our application to verify the authenticity
# of requests from Slack, we'll compare the request signature
slack_signing_secret = os.environ["SLACK_SIGNING_SECRET"]
# Create an instance of SlackEventAdapter, passing in our Flask server so it can bind the
# Slack specific routes. The `endpoint` param specifies where to listen for Slack event traffic.
slack_events_adapter = SlackEventAdapter(
slack_signing_secret,
endpoint="/slack/events"
)
# --------------------
# Google Translate API
# https://console.cloud.google.com/apis/credentials?project={project id}
# export GOOGLE_APPLICATION_CREDENTIALS=/path/to/{service-account-key}.json
translate_client = translate.Client()
# --------------------
# Load language mapping data
langcode: dict = {}
with open('./langcode.json') as langcode_file:
langcode = json.load(langcode_file)
# --------------------
# reaction_added event handler
@slack_events_adapter.on("reaction_added")
def reaction_added(event_data):
event = event_data["event"]
# Get the reactji name from the event payload
emoji_name = event["reaction"]
country: str = None
# Check the reaction name if it is a country flag
if re.match(r"flag-", emoji_name): # when the name has flag- prefix
country = re.search(r"flag-(\w{2})$", emoji_name).group(1)
else: # jp, fr, etc.
if emoji_name in langcode.keys():
country = emoji_name
else:
return
# Finding a lang based on a country is not the best way but oh well
# Matching ISO 639-1 language code
lang: str = langcode[country]
if lang is None:
return
print(u'country: {}, lang: {}'.format(country, lang))
channel = event["item"]["channel"]
thread_ts = event['item']['ts']
# Fetch all the messages in the thread
replies_response = slack_web_api_client.conversations_replies(
channel=channel,
ts=thread_ts
)
if replies_response["ok"]:
messages = replies_response["messages"]
first_message = messages[0]
if first_message["text"]:
text: str = first_message["text"]
# Call Google Translate API
if isinstance(text, six.binary_type):
text = text.decode('utf-8')
translation_result = translate_client.translate(
text,
target_language=lang,
model='nmt')
translated_text = html.unescape(
translation_result["translatedText"])
# Make sure if the translated text is not posted yet
for msg in messages:
if msg["text"] and msg["text"] == translated_text:
print("The translation seems to be already posted")
return
# Post the translation as a new message in the thread
post_response = slack_web_api_client.chat_postMessage(
channel=channel,
thread_ts=thread_ts,
username="Reacjilator Bot",
text=translated_text)
if post_response["ok"]:
print(u'The translated text for {} has been successfully posted: {}'
.format(lang, post_response["ts"]))
else:
print(u'Failed to post a translated text: {}'
.format(post_response["error"]))
else:
print(u'Skipped because the message doesn\'t contain text: {}'
.format(first_message))
return
else:
print(u'Failed to fetch message replies: {}'
.format(replies_response["error"]))
# --------------------
# python app.py
slack_events_adapter.start(port=3000)