Make an easy Python bot to automatically translate Discord messages
in , , ,

Make An Easy Python Bot To Automatically Translate Discord Messages

Make an easy Python bot to automatically translate Discord messages: It’s no secret that Discord is one of the best messaging applications around, connecting people from all around the world, helping friends become closer. However, occasionally we find someone speaking in a language we’re unfamiliar with. 

how about you use that dormant brain of yours and create an automated translation bot that can handle the situation for you!  

Getting started with the basics

The fact that you’ve come here implies you’re familiar with the basics like making a command and getting a token. Alternatively, you can view Lucas’s tutorial, which is the one I used when I started out, or you can join Ctk’s server, where passionate people will be happy to assist you.

Therefore, let’s begin with the normal boilerplate.

import discord
from discord.ext import commands
import json
import os 

def get(element:str):
  path = os.path.abspath("./conf.json")
  with open(path, "r") as read_file:
    content = json.load(read_file)
  return content[element]

intents = discord.Intents().all()
client = commands.Bot(command_prefix=get("prefix"),intents = intents)

@client.event
async def on_ready():
    print(f"Logged in as {client.user}")
    print(f"{client.user}: Online")

@client.command()
async def ping(ctx):
  await ctx.send("pong!")


client.run(get("token"))

{
  "prefix":"your prefix",
  "token":"your token"
}

We can start programming now that we have completed the boilerplate. To start the translation, either an API or module is needed. I will stick to modules as the API might be slow and it is just much easier to implement modules!

GoogleTrans is going to be used for this project, so make sure you’re installing GoogleTrans 3.1.0a0, as any other version will fail to work correctly even when implemented correctly.  

pip3 install googletrans==3.1.0a0

Moving Toward Translation System

Our first step will be to write a translation function that will be used in our main command. Let’s initialize the translator and translate the message that was given to us.  

def translate(message,lang="en"):
    translator = Translator()
    translation = translator.translate(message)
    return (translation.text)

Translating each message that is not in English into English is the main function. First, we’ll install textblob, a module that lets us identify the language of the message.

pip3 install textblob

We will now import textblob and begin writing the function. You should now have a file called main.py that looks something like this  

import discord
from discord.ext import commands
from googletrans import Translator, constants
import json
import os 
from textblob import TextBlob

def get(element:str):
  path = os.path.abspath("./conf.json")
  with open(path, "r") as read_file:
    content = json.load(read_file)
  return content[element]

intents = discord.Intents().all()
client = commands.Bot(command_prefix=get("prefix"),intents = intents)

def translate(message,lang="en"):
    translator = Translator()
    translation = translator.translate(message)
    return (translation.text)

@client.event
async def on_ready():
    print(f"Logged in as {client.user}")
    print(f"{client.user}: Online")

@client.command()
async def ping(ctx):
  await ctx.send("pong!")

client.run(get("token"))

To begin, we must create a command header and define it as an asynchronous function on_message. As a parameter, we should input the message and check if it is in English, if not, we will translate the word in English. Moreover, we will check if it has at least three characters in order to avoid spam. The module doesn’t support this, so we’ve provided drop-down suggestions in comments on how to work around this. In this case, we will first check whether the message begins with the prefix, but only if it doesn’t, will we translate it. 

We will also check to see if the message is sent by the bot itself, and if it is, we will not translate it. This is optional, but I like to have it. Then we will call our translate function to translate the message and send it. Here is what the final product should look like. Of course, there is still room for improvement.

@client.event
async def on_message(message):
  print("working!")
  m = TextBlob(message.content)
  print(message.content)
  if len(message.content) < 3:
    await message.reply("you need to provide at least 3 characters!")
    return
  elif message.content.startswith(get("prefix")) == True:
    return
  elif m.detect_language() == "en":
    return
  elif message.author == client.user:
    return
  t=translate(message.content,"en")
  await message.reply(t)

In the end, it should look like this!

import discord
from discord.ext import commands
from googletrans import Translator, constants
import json
import os 
from textblob import TextBlob

def get(element:str):
  path = os.path.abspath("./conf.json")
  with open(path, "r") as read_file:
    content = json.load(read_file)
  return content[element]

intents = discord.Intents().all()
client = commands.Bot(command_prefix=get("prefix"),intents = intents)


def translate(message,lang="en"):
    translator = Translator()
    translation = translator.translate(message)
    return (translation.text)

@client.event
async def on_ready():
    print(f"Logged in as {client.user}")
    print(f"{client.user}: Online")


@client.command()
async def ping(ctx):
  await ctx.send("pong!")

"""@client.command()
async def stlang(ctx,lang):
  path = os.path.abspath("./conf.json")
  with open(path, "w") as write_file:
    write_file.write(lang)
  await ctx.send("Done")"""

  
@client.event
async def on_message(message):
  print("working!")
  m = TextBlob(message.content)
  print(message.content)
  if len(message.content) < 3:
    await message.reply("you need to provide at least 3 characters!")
    return
  elif message.content.startswith(get("prefix")) == True:
    return
  elif m.detect_language() == "en":
    return
  elif message.author == client.user:
      return
  t=translate(message.content,"en")
  await message.reply(t)

client.run(get("token"))

Voila! There you have it!

And in case you couldn’t follow just clone/fork this repo.

Related Posts

Written by Pain444

Leave a Reply

5 Comments