LoginSignup
16
18

More than 3 years have passed since last update.

Discordのチャットを読み上げるbotの作成

Last updated at Posted at 2019-05-17

はじめに

discordで通話つなぎながらゲームしている時にチャットの反応が遅れるため、反応しやすいように作りました。
(windowsはOpen-jtalkの導入が少し面倒かもしれません。)

環境

  • Windows10
  • discord.py == 1.0.1
  • Python 3.7.x

事前準備

Botを作ったことがないひとはまず「Discord bot作成チュートリアル」

環境準備

すでに導入方法の記事は腐るほど存在してると思うため他記事に丸投げさせてもらいます。

Windowsで音声合成Open JTalk
https://qiita.com/mkgask/items/0bf9c26dc96e7b0b45ac
ffmpegインストール
https://web.plus-idea.net/2015/11/windows-ffmpeg/

僕はここを見ながらやりました。

bot作成

read_bot.py
import discord
from discord.ext import commands
import subprocess
import ffmpeg
from voice_generator import creat_WAV

client = commands.Bot(command_prefix='.')
voice_client = None


@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')


@client.command()
async def join(ctx):
    #voicechannelを取得
    vc = ctx.author.voice.channel
    #voicechannelに接続
    await vc.connect()

@client.command()
async def bye(ctx):
    #切断
    await ctx.voice_client.disconnect()

@client.event
async def on_message(message):
    if message.content.startswith('.'):
        pass

    else:
        if message.guild.voice_client:
            print(message.content)
            creat_WAV(message.content)
            source = discord.FFmpegPCMAudio("output.wav")
            message.guild.voice_client.play(source)
        else:
            pass


client.run("あなたのTOKEN")

次にopen-jtalkで音声ファイルを作るコードを書きます

voice_generator.py
import subprocess

def creat_WAV(inputText):
        #message.contentをテキストファイルに書き込み
    input_file = 'input.txt'

    with open(input_file,'w',encoding='shift_jis') as file:
        file.write(inputText)

    command = 'C:/open_jtalk/bin/open_jtalk -x {x} -m {m} -r {r} -ow {ow} {input_file}'

    #辞書のPath
    x = 'C:/open_jtalk/bin/dic'

    #ボイスファイルのPath
    m = 'C:/open_jtalk/bin/nitech_jp_atr503_m001.htsvoice'

    #発声のスピード
    r = '1.0'

    #出力ファイル名 and Path
    ow = 'output.wav'

    args= {'x':x, 'm':m, 'r':r, 'ow':ow, 'input_file':input_file}

    cmd= command.format(**args)
    print(cmd)

    subprocess.run(cmd)
    return True

if __name__ == '__main__':
    creat_WAV('テスト')

read_bot.pyとvoice_generator.pyは同じ階層、openj-talkはCドライブ直下にあるものとしたコードです。

最後に

discord.pyをasync版からrewrite版変えてから初めてコマンドを使ってみましたがとても便利ですね!いろいろ用途があって面白そうです。

@maguro869 さんがカスタムEmojiの読み上げをしてしまう不具合の修正をしてくださいました。
よろしければ一緒にどうぞ。
message.content内のサーバーカスタム絵文字を取り除く方法

参考

OpenJTalk + python で日本語テキストを発話
https://qiita.com/kkoba84/items/b828229c374a249965a9

16
18
2

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
16
18