-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
95 lines (70 loc) · 2.44 KB
/
Copy pathmain.py
File metadata and controls
95 lines (70 loc) · 2.44 KB
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
# bot.py
import requests
import discord
import os
import re
TOKEN = os.environ.get('DISCORD_TOKEN')
API_KEY = os.environ.get('API_KEY')
def get_translation(text, target):
url = "https://microsoft-translator-text.p.rapidapi.com/translate"
translated_text = ''
querystring = {"to": "{}".format(target), "api-version": "3.0", "profanityAction": "NoAction", "textType": "plain"}
payload = [{"Text": "{}".format(text)}]
headers = {
"content-type": "application/json",
"X-RapidAPI-Host": "microsoft-translator-text.p.rapidapi.com",
"X-RapidAPI-Key": "{}".format(API_KEY)
}
try:
response = requests.request("POST", url, json=payload, headers=headers, params=querystring)
except requests.exceptions.RequestException as e:
return e
except (requests.exceptions.InvalidJSONError, TypeError):
return "Invalid JSON"
try:
translated_text = response.json()[0]["translations"][0]["text"]
except (KeyError, IndexError, ValueError):
return "PARSING ERROR"
if translated_text == '':
return 'Failed to get Translation'
return translated_text
client = discord.Client()
def get_translation_log(guild):
for channel in guild.channels:
if str(channel.name) == 'translation-log':
return channel
return 0
def validate_message_text(text):
if len(str(text)) == 0 or "https:" in str(text) or "http:" in str(text):
return False
return True
def get_target_language(emoji):
if emoji == '🇪':
return 'en'
elif emoji == '🇨':
return 'zh-CN'
elif emoji == '🇯':
return 'ja'
else:
return ''
@client.event
async def on_reaction_add(reaction, user):
if user.bot:
return
channel = get_translation_log(reaction.message.guild)
if channel == 0:
return
if reaction.count > 1:
return
text = reaction.message.content
text = re.sub("[:<>].*[:<>]", "", text) ## remove emojis in text message
if not validate_message_text(text):
return
target = get_target_language(reaction.emoji)
if len(target) == 0:
return
embed = discord.Embed(title="Translation", description="Translation", color=0xffffff)
embed.add_field(name="Original Text", value=text, inline=False)
embed.add_field(name="Translated Test", value=get_translation(text, target=target), inline=False)
await channel.send(embed=embed)
client.run(TOKEN)