[PYTHON] I tried to make a translation BOT that works on Discord using googletrans

Preface

I suddenly wanted to translate English sentences, but I found it troublesome to add chrome on my PC, open google translate, and type. However, Discord is always on for some reason, so I thought I would use Discord's translation BOT, but I felt that downloading it as it was was something different, so I decided to make it and came here. This is the second BOT in my life.

Thing you want to do

――Translates Japanese into English ――Translates English into Japanese --Translates to Japanese without specifying a language other than Japanese --If you specify the language, it will translate from any word to any word.

What was made

--Translate to Japanese with ! Trans [character string other than Japanese] --Translate Japanese to English with ! Trans [Japanese string] --! Trans [Language name A]-[Language name B]-[Character string of A word] to translate A word to B word --Get the language code of that string with ! detect [arbitrary string]

environment

Advance preparation

--Environment where Python can be used --Basic knowledge of Python --Easy way to make a bot

This is easy to understand. How to make a simple Discord Bot with Python Discord Bot fastest tutorial [Python & Heroku & GitHub]

What is googletrans

A free library that allows you to translate and detect languages using the Google Translate API. However, it is not very stable and can be blocked by Google at any time, so if you want stability, we recommend using the official API of Google Cloud.

Installation

pip install googletrans You can install it with.

Successfully installed googletrans- (arbitrary version) Is completed.

Code example

As an example, let's create a program that converts Japanese to English.

trans_test.py


from googletrans import Translator

translator = Translator()

japanese = translator.translate('Good morning.')
print(japanese.text)
#>> Good morning.

In addition to text, the value returned by translete () includes the language of the conversion source and the language after conversion.

trans_test.py


from googletrans import Translator

translator = Translator()

japanese = translator.translate('Good morning.')
print(japanese)
#>> Translated(src=ja, dest=en, text=Good morning., pronunciation=None, extra_data="{'translat...")

To detect the language, put the sentence or word you want to detect in the parentheses of detect ().

trans_test.py


from googletrans import Translator

translator = Translator()

detect = translator.detect('Good morning.')
print(detect)
#>> Detected(lang=ja, confidence=1.0)

The two letters in English after lang are the language name, and confidence is the accuracy.

What a useful library! !! This time, we will make a translation BOT using this library.

Creating a BOT

First, put the finished product down.

main.py


import discord
from googletrans import Translator

TOKEN = 'Tokens face down'

client = discord.Client()
translator = Translator()

@client.event
async def on_ready():
    print('--------------')
    print('You are now logged')
    print(client.user.name)
    print(client.user.id)
    print('--------------')

@client.event
async def on_message(message):
    if message.author.bot:
        return

    if message.content.startswith('!trans'):
        say = message.content
        say = say[7:]
        if say.find('-') == -1:
            str = say
            detact = translator.detect(str)
            befor_lang = detact.lang
            if befor_lang == 'ja':
                convert_string = translator.translate(str, src=befor_lang, dest='en')
                embed = discord.Embed(title='Conversion result', color=0xff0000)
                embed.add_field(name='Befor', value=str)
                embed.add_field(name='After', value=convert_string.text, inline=False)
                await message.channel.send(embed=embed)
            else:
                convert_string = translator.translate(str, src=befor_lang, dest='ja')
                embed = discord.Embed(title='Conversion result', color=0xff0000)
                embed.add_field(name='Befor', value=str)
                embed.add_field(name='After', value=convert_string.text, inline=False)
                await message.channel.send(embed=embed)
        else:
            trans, str = list(say.split('='))
            befor_lang, after_lang = list(trans.split('-'))
            convert_string = translator.translate(str, src=befor_lang, dest=after_lang)
            embed = discord.Embed(title='Conversion result', color=0xff0000)
            embed.add_field(name='Befor', value=str)
            embed.add_field(name='After', value=convert_string.text, inline=False)
            await message.channel.send(embed=embed)

    if message.content.startswith('!detect'):
        say = message.content
        s = say[8:]
        detect = translator.detect(s)
        m = 'The language of this string is probably' + detect.lang + 'is.'
        await message.channel.send(m)

client.run(TOKEN)

I don't know if it looks complicated, but it's very simple to do.

!trans ~ When the instruction starts with, remove the instruction ! Trans and one half-width character from the instruction. ↓ detect the language of the sentence with detect (). ↓ If the language is Japanese, translate it into English, otherwise translate it into Japanese.

② (Assuming that! Trans has already been removed) !trans [A]-[B]-[C] At the time of the instruction, A is the language name before conversion, B is the language name after conversion, and C is a character string. ↓ Translate C from A, B, C to B language.

!detect ~ When the command starts with, remove the command ! Detect and one half-width character from the command. ↓ detect () to detect the language of the sentence and output it

That's all for the overall movement. There are places where ʻembed ~ `is written in various places, but this is necessary for embedding when speaking on Discord. Embedding seems to be easier to see.

result

There is nothing wrong with the content to be translated. I choose it appropriately.

--From Japanese to English 翻訳1.PNG

--From English to Japanese 翻訳2.PNG

--From German to Japanese 翻訳3.PNG

--From Japanese to German 翻訳4.PNG

--Language detection Japanese 翻訳5.PNG

French 翻訳6.PNG

I've implemented everything I was trying to do!

Conclusion ・ Impression

I think the translation is inferior to google translate, but I am satisfied because I was able to do what I was trying to do. I'm still doing something elementary, so I have a lot of things I want to do, such as voice chat, acquiring members, and combining it with web scraping.

Let's make it because everyone is happy to make BOT! !!

If you make a mistake or have any improvements, feel free to tell me anything on Twitter.

Recommended Posts

I tried to make a translation BOT that works on Discord using googletrans
[Python] I tried to make a simple program that works on the command line using argparse.
I tried to make a ○ ✕ game using TensorFlow
I tried to make a stopwatch using tkinter in python
I tried to make a simple text editor using PyQt
I tried to create a server environment that runs on Windows 10
I tried to make a system that fetches only deleted tweets
I tried to make a regular expression of "time" using Python
I tried to make a regular expression of "date" using Python
I tried to make a todo application using bottle with python
I tried to make a bot that randomly acquires Wikipedia articles and tweets once a day
I tried to make a Web API
I tried to implement a blockchain that actually works with about 170 lines
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
I tried to make a skill that Alexa will return as cold
I tried to operate Linux with Discord Bot
[Python] I tried to make a Shiritori AI that enhances vocabulary through battles
I tried to make a dictionary function that does not distinguish between cases
I tried to make a suspicious person MAP quickly using Geolonia address data
I tried to make a "fucking big literary converter"
Make a BOT that shortens the URL of Discord
I tried to draw a configuration diagram using Diagrams
[LPIC 101] I tried to summarize the command options that are easy to make a mistake
I tried to make a memo app that can be pomodoro, but a reflection record
A Python beginner made a chat bot, so I tried to summarize how to make it.
I made a discord bot
I tried to make it on / off by setting "Create a plug-in that highlights double-byte space with Sublime Text 2".
I tried to combine Discord Bot and face recognition-for LT-
I tried using "Syncthing" to synchronize files on multiple PCs
I tried to automate [a certain task] using Raspberry Pi
I tried to create a bot for PES event notification
I tried using a library (common thread) that makes Python's threading package easier to use
[Git] I tried to make it easier to understand how to use git stash using a concrete example
I tried to make a document search slack command using Kendra announced at re: Invent 2019.
I tried to make a generator that generates a C # container class from CSV with Python
I tried to make a motion detection surveillance camera with OpenCV using a WEB camera with Raspberry Pi
How to make a Japanese-English translation
I tried to get a database of horse racing using Pandas
[Python] I tried to implement stable sorting, so make a note
I tried to implement anomaly detection using a hidden Markov model
[3rd] I tried to make a certain authenticator-like tool with python
[Python] A memo that I tried to get started with asyncio
I tried to digitize the stamp stamped on paper using OpenCV
I tried to make a periodical process with Selenium and Python
I tried to get a list of AMI Names using Boto3
I tried to register a station on the IoT platform "Rimotte"
I tried to make a 2channel post notification application with Python
I tried to visualize BigQuery data using Jupyter Lab on GCP
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
[4th] I tried to make a certain authenticator-like tool with python
[Python] Simple Japanese ⇒ I tried to make an English translation tool
[1st] I tried to make a certain authenticator-like tool with python
I tried to make a strange quote for Jojo with LSTM
I tried to make a mechanism of exclusive control with Go
I tried to make a site that makes it easy to see the update information of Azure
I tried to build a SATA software RAID configuration that boots the OS on Ubuntu Server
I tried to make a script that traces the tweets of a specific user on Twitter and saves the posted image at once
Tweet in Chama Slack Bot ~ How to make a Slack Bot using AWS Lambda ~
Python: I tried to make a flat / flat_map just right with a generator
I tried using Azure Speech to Text.
I tried using jpholidayp over proxy to execute cron only on weekdays