/
fluent.py
230 lines (201 loc) · 8.39 KB
/
fluent.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import logging
import traceback
from typing import Optional
import discord
import googletrans
from aiocache import cached
from discord import app_commands
from redbot.core import Config, commands
from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import pagify
from .api import TranslateManager
translator = googletrans.Translator()
log = logging.getLogger("red.vrt.fluent")
fail_embed = discord.Embed(description="❌ API seems to be down at the moment.")
# Inspired by Obi-Wan3#0003's translation cog.
class Fluent(commands.Cog):
"""
Seamless translation between two languages in one channel.
"""
__author__ = "Vertyco"
__version__ = "1.3.0"
def format_help_for_context(self, ctx: commands.Context):
helpcmd = super().format_help_for_context(ctx)
return f"{helpcmd}\nCog Version: {self.__version__}\nAuthor: {self.__author__}"
async def red_delete_data_for_user(self, *, requester, user_id: int):
"""No data to delete"""
def __init__(self, bot: Red):
self.bot = bot
self.translator = TranslateManager(bot)
self.config = Config.get_conf(self, identifier=11701170)
default_guild = {"channels": {}}
self.config.register_guild(**default_guild)
# Gets language identifier from string
@staticmethod
async def converter(language: str):
for key, value in googletrans.LANGUAGES.items():
if language == "chinese":
language = "chinese (simplified)"
if language == value or language == key:
return key
# Cached for two days to minimize api use as much as possible
@cached(ttl=1800)
async def translate(self, msg: str, dest: str):
return await self.translator.translate(msg, dest)
@commands.hybrid_command(name="translate")
@app_commands.describe(to_language="Translate to this language")
async def translate_command(
self, ctx: commands.Context, to_language: str, *, message: Optional[str] = None
):
"""Translate a message"""
lang = await self.converter(to_language.lower())
if not lang:
return await ctx.send(f"The `{to_language}` was not found")
if not message and hasattr(ctx.message, "reference"):
try:
message = ctx.message.reference.resolved.content
except AttributeError:
pass
if not message:
return await ctx.send("Could not find any content to translate!")
try:
trans = await self.translate(message, lang)
except Exception as e:
await ctx.send(f"Translation failed: `{e}`")
log.error("Translation failed", exc_info=e)
return
if trans is None:
return await ctx.send(embed=fail_embed)
embed = discord.Embed(description=trans.text, color=ctx.author.color)
embed.set_footer(text=f"{trans.src} -> {lang}")
try:
await ctx.reply(embed=embed, mention_author=False)
except (discord.NotFound, AttributeError):
await ctx.send(embed=embed)
@translate_command.autocomplete("to_language")
async def translate_autocomplete(self, interaction: discord.Interaction, current: str):
return await self.get_langs(current)
@cached(ttl=60)
async def get_langs(self, current: str):
return [
app_commands.Choice(name=i, value=i)
for i in googletrans.LANGUAGES.values()
if current.lower() in i.lower()
][:45]
@commands.group()
@commands.mod()
async def fluent(self, ctx: commands.Context):
"""Base command"""
pass
@fluent.command()
async def add(
self,
ctx: commands.Context,
language1: str,
language2: str,
channel: Optional[discord.TextChannel],
):
"""
Add a channel and languages to translate between
Tip: Language 1 is the first to be converted. For example, if you expect most of the conversation to be
in english, then make english language 2 to use less api calls.
"""
if not channel:
channel = ctx.channel
language1 = await self.converter(language1.lower())
language2 = await self.converter(language2.lower())
if not language1 or not language2:
return await ctx.send(
f"One of the languages were not found: lang1-{language1} lang2-{language2}"
)
async with self.config.guild(ctx.guild).channels() as channels:
cid = str(channel.id)
if cid in channels.keys():
return await ctx.send(
embed=discord.Embed(
description=f"❌ {channel.mention} is already a fluent channel."
)
)
else:
channels[cid] = {"lang1": language1, "lang2": language2}
color = discord.Color.green()
return await ctx.send(
embed=discord.Embed(description="✅ Fluent channel has been set!", color=color)
)
@fluent.command(aliases=["delete", "del", "rem"])
async def remove(self, ctx: commands.Context, channel: Optional[discord.TextChannel]):
"""Remove a channel from Fluent"""
if not channel:
channel = ctx.channel
async with self.config.guild(ctx.guild).channels() as channels:
cid = str(channel.id)
if cid in channels:
del channels[cid]
color = discord.Color.green()
embed = discord.Embed(
description="✅ Fluent channel has been deleted!", color=color
)
await ctx.send(embed=embed)
else:
embed = discord.Embed(description=f"❌ {channel.mention} isn't a fluent channel.")
await ctx.send(embed=embed)
@fluent.command()
async def view(self, ctx: commands.Context):
"""View all fluent channels"""
channels = await self.config.guild(ctx.guild).channels()
msg = ""
for cid, langs in channels.items():
channel = ctx.guild.get_channel(int(cid))
if not channel:
continue
l1 = langs["lang1"]
l2 = langs["lang2"]
msg += f"{channel.mention} `({l1} <-> {l2})`\n"
if not msg:
return await ctx.send("There are no fluent channels at this time")
final = f"**Fluent Settings**\n{msg.strip()}"
for p in pagify(final, page_length=1000):
await ctx.send(p)
@commands.Cog.listener("on_message_without_command")
async def message_handler(self, message: discord.Message):
if message.author.bot:
return
if not message.guild:
return
if message.content is None:
return
if not message.content.strip():
return
channels = await self.config.guild(message.guild).channels()
channel_id = str(message.channel.id)
if channel_id not in channels:
return
lang1 = channels[channel_id]["lang1"]
lang2 = channels[channel_id]["lang2"]
channel = message.channel
# Attempts to translate message into language1.
try:
trans = await self.translate(message.content, lang1)
except Exception:
log.error(f"Initial translation failed: {traceback.format_exc()}")
return
if trans is None:
return await channel.send(embed=fail_embed)
# If the source language is also language1, translate into language2
# If source language was language2, this saves api calls because translating gets the source and translation
if trans.src == lang1:
try:
trans = await self.translate(message.content, lang2)
except Exception:
log.error(f"Secondary translation failed: {traceback.format_exc()}")
return
if trans is None:
return await channel.send(embed=fail_embed)
# If src is lang2 then a 2nd api call isn't needed
if trans.text.lower() == message.content.lower():
return
embed = discord.Embed(description=trans.text, color=message.author.color)
try:
await message.reply(embed=embed, mention_author=False)
except (discord.NotFound, AttributeError):
await channel.send(embed=embed)