LoginSignup
8
13

More than 3 years have passed since last update.

リアクションしたら翻訳してくれるDiscordのbotをPythonで作った

Last updated at Posted at 2020-03-11

こんな感じのbot
image.png

Discordでbotを作る方法は割愛。この辺りを読んで下さい。
Pythonで実用Discord Bot(discordpy解説)

ソースコード

# インストールした discord.py を読み込む
import discord
from googletrans import Translator

# 自分のBotのアクセストークンに置き換えてください
TOKEN = '[bot-token]'

# 接続に必要なオブジェクトを生成
client = discord.Client()

# 起動時に動作する処理
@client.event
async def on_ready():
    # 起動したらターミナルにログイン通知が表示される
    print('ログインしました')

@client.event
async def on_reaction_add(reaction, user):
    print("emoji-id")
    print(reaction.emoji.id)
    if reaction.count == 1:
        # 日本語訳
        if reaction.emoji.id == 687336060556017758:
            translator = Translator()
            trans_en = translator.translate(reaction.message.content, src='en', dest='ja')
            await reaction.message.channel.send(trans_en.text)


        # 英語訳
        if reaction.emoji.id == 687336087408214062:
            translator = Translator()
            trans_en = translator.translate(reaction.message.content, src='ja', dest='en')
            await reaction.message.channel.send(trans_en.text)



# Botの起動とDiscordサーバーへの接続
client.run(TOKEN)

[bot-token]はそれぞれのbotのトークンを。
[emoji-id]は反応させたい絵文字のIDを設定してあげてください(Integerです)

Google翻訳「googletrans 」

翻訳はGoogle翻訳に投げて、その結果をメッセージで返してるだけです。
emoji.idについては登録された絵文字だと、絵文字のIDが振られているので、サーバーに絵文字をセットしたら、リアクションをして、printに吐き出された絵文字IDをベタ打ちで書きましょう。
私の場合は、日本の国旗を日本語訳、アメリカの国旗を英語訳にしました。

srcが翻訳前の文章、destが翻訳後の文章なので、英訳、日本語訳以外にすることも出来ます。

完成したら、heroku辺りにデプロイして動かせば24時間体制で翻訳してくれます、便利!
ちなみに、リアクションの回数を取得する方法が分からなかったので、2リアクションすると2回翻訳します。

やり方誰か教えてください。

追記:リアクション1回にする方法教えて貰いました

if reaction.count == 1:
こちらになります、@rareshanaさんありがとうございます!

参考

Pythonで実用Discord Bot(discordpy解説)
Discord.pyでリアクションを検知する方法&バラメータ一覧
【Python】googletransを使って日本語のデータを英語に変換(翻訳)してみる

8
13
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
13