forked from jotslo/discord-auto-translate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
69 lines (52 loc) · 2.28 KB
/
main.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
# discord-auto-translate by JoshSCF (joshl.io)
import config, discord, re
from modules import google, microsoft, yandex
from discord import Webhook, RequestsWebhookAdapter
client = discord.Client()
apis = {
"google": google,
"yandex": yandex,
"microsoft": microsoft
}
async def get_webhook(bot, channel, webhook_list):
# if webhook exists, return
for webhook in webhook_list:
if webhook.user == bot and webhook.channel_id == channel.id:
return webhook
# otherwise, create new webhook and return
new_webhook = await channel.create_webhook(
name = "discord-auto-translate",
reason = "This webhook is used to post translations on behalf of a user."
)
return new_webhook
async def replace_message(message, translation):
user = message.author
# prepare webhook, delete message and send message with the same name & pic as user
webhook_info = await get_webhook(client.user, message.channel, await message.guild.webhooks())
webhook = Webhook.partial(webhook_info.id, webhook_info.token, adapter=RequestsWebhookAdapter())
await message.delete()
webhook.send(translation, username = user.nick or user.name, avatar_url = user.avatar_url)
@client.event
async def on_message(message):
channel_id = message.channel.id
# ignore message if channel blacklisted or not whitelisted
if config.channel_whitelisting_enabled:
if channel_id not in config.whitelisted_channels:
return
else:
if channel_id in config.blacklisted_channels:
return
# translate message via relevant translation module
api_service = apis[config.translation_service]
translation = api_service.translate(message.content, config.api_key)
# compare translation with original, replace if different
alnum_translation = re.sub(r"\W+", "", translation)
alnum_message = re.sub(r"\W+", "", message.content)
if alnum_translation != alnum_message:
await replace_message(message, translation)
if not config.i_have_read_config:
# user has not read config file, don't start code
print("You must modify config.py before running!")
input("Press enter to continue...")
exit()
client.run(config.bot_token)