I made a Discord chat reading bot by imitating the appearance

Introduction

The chat reading bot used in Discord has temporarily become unusable, so I made it on a temporary basis. I made it by rewriting a part of the code referring to Creating a bot that reads out Discord chat.

Advance preparation

I did the bot creation and environment construction while looking at the following.

-[Discord bot creation tutorial](https://ikayome.hateblo.jp/entry/2019/07/03/Discord_bot%E4%BD%9C%E6%88%90%E3%83%81%E3%83% A5% E3% 83% BC% E3% 83% 88% E3% 83% AA% E3% 82% A2% E3% 83% AB) -Speech synthesis on Windows Open JTalk -Install ffmpeg on windows

ffmpeg puts the unzipped files in C: \ open_jtalk \ bin. Don't forget the Path setting ...

bot source code

Please rewrite the token of each bot in the part of the bottom line, which is the token copied when the bot was created.

read_bot.py


import discord
from discord.ext import commands
import asyncio
import os
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):
    print('#Get voicechannel')
    vc = ctx.author.voice.channel
    print('#Connect to voice channel')
    await vc.connect()

@client.command()
async def bye(ctx):
    print('#Disconnect')
    await ctx.voice_client.disconnect()

@client.event
async def on_message(message):
    msgclient = message.guild.voice_client
    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
    await client.process_commands(message)


client.run("Token copied when creating the bot")

Audio file source code

There are various comments out in the voice file path, but if you download the Source code of Sample Script in MMD Agent You can change it to a female voice. (Since there is a htsvoice file in the Voice / mei directory of the unzipped file, place the mei directory in the same hierarchy as the source code.)

voice_generator.py


import subprocess
import re

# remove_custom_emoji
#Emoji ID is not read aloud
def remove_custom_emoji(text):
    pattern = r'<:[a-zA-Z0-9_]+:[0-9]+>'    #Custom emoji pattern
    return re.sub(pattern,'',text)   #Replacement process

# urlAbb
#Omitted for URL
def urlAbb(text):
    pattern = "https?://[\w/:%#\$&\?\(\)~\.=\+\-]+"
    return re.sub(pattern,'The URL is omitted!',text)   #Replacement process

# creat_WAV
# message.Write content to a text file
def creat_WAV(inputText):
        # message.Write content to a text file

    inputText = remove_custom_emoji(inputText)   #Emoji ID is not read aloud
    inputText = urlAbb(inputText)   #Omitted for URL
    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}'

    #Dictionary Path
    x = 'C:/open_jtalk/bin/dic'

    #Voice file Path
    m = 'C:/open_jtalk/bin/nitech_jp_atr503_m001.htsvoice'
    #m = 'C:/open_jtalk/bin/mei/mei_sad.htsvoice'
    #m = 'C:/open_jtalk/bin/mei/mei_angry.htsvoice'
    #m = 'C:/open_jtalk/bin/mei/mei_bashful.htsvoice'
    #m = 'C:/open_jtalk/bin/mei/mei_happy.htsvoice'
    #m = 'C:/open_jtalk/bin/mei/mei_normal.htsvoice'

    #Vocalization speed
    r = '1.0'

    #Output file name 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('test')

Directory structure

The composition is like this.

image.png

How to use

There was a description up to the point of inviting the bot, but it was not written about how to use it, so I will write it appropriately.

Command prompt start

タイトルなし.png

Drag and drop "read_bot.py" from C: \ open_jtalk \ bin to the command prompt and Enter

タイトルなし2.png

Then the bot will log in

タイトルなし3.png

Call to voice channel

First of all, I enter the voicing. (This bot basically comes in at the person who called the voicing.) The command to call is .join

タイトルなし4.png

Let me talk

If you chat appropriately, it will be read. It doesn't read emojis or custom emojis ... Also, I try to omit the URL.

Evacuate

The command to leave the bot from the voice channel is .bye

タイトルなし5.png

Clean up

At the command prompt, use Ctrl + C or close the window.

end

I feel that even simple English can be read in alphabets, so I'd like to add a dictionary registration function.

Well it will be done soon. maybe

Recommended Posts

I made a Discord chat reading bot by imitating the appearance
I made a discord bot
When I made a Discord Bot, my classmates destroyed my computer
I made a wikipedia gacha bot
I made a Twitter bot that mutters Pokemon caught by #PokemonGO
I made a slack bot that notifies me of the temperature
I made a Discord bot in Python that translates when it reacts
I made a LINE Bot with Serverless Framework!
I made a Mattermost bot with Python (+ Flask)
I made a LINE BOT that returns a terrorist image using the Flickr API
[AWS] I made a reminder BOT with LINE WORKS
I made a household account book bot with LINE Bot
〇✕ I made a game
I made a user management tool for Let's Chat
Make a BOT that shortens the URL of Discord
A Python beginner made a chat bot, so I tried to summarize how to make it.
I made a command to markdown the table clipboard
Add a function to tell the weather of today to slack bot (made by python)
I made a LINE BOT that returns parrots with Go
I scraped the Organization member team and made a ranking
I made a function to check the model of DCGAN
I made a dot picture of the image of Irasutoya. (part1)
I made a VGG16 model using TensorFlow (on the way)
I made a dot picture of the image of Irasutoya. (part2)
[AWS] I made a reminder BOT with LINE WORKS (implementation)
Let's make a Discord Bot.
Make a LINE BOT (chat)
I made a python text
I made a Line bot that guesses the gender and age of a person from an image
[Python] I made a Line bot that randomly asks English words.
I made a program to solve (hint) Saizeriya's spot the difference
I made a simple network camera by combining ESP32-CAM and RTSP.
I made a program that solves the spot the difference in seconds
I made a Twitter Bot with Go x Qiita API x Lambda
I made a scaffolding tool for the Python web framework Bottle
I made a command to display a colorful calendar in the terminal
I made a program that automatically calculates the zodiac with tkinter
[Kaggle] I made a collection of questions using the Titanic tutorial
I found out by making a python script to record radiko while reading the code of the predecessors
I started to work at different times, so I made a bot that tells me the time to leave
I made a bot to post on twitter by web scraping a dynamic site with AWS Lambda (continued)
[Python] I made a bot that tells me the current temperature when I enter a place name on LINE
I made a C ++ learning site
I made a Line-bot using Python!
I made a CUI-based translation script (2)
I made a fortune with Python.
I made a CUI-based translation script
I made a daemon with Python
I made a calendar that automatically updates the distribution schedule of Vtuber
[Django] I made a field to enter the date with 4 digit numbers
I made a kitchen timer to be displayed on the status bar!
I made a program to notify you by LINE when switches arrive
I made a simple timer that can be started from the terminal
I made a GAN with Keras, so I made a video of the learning process.
I made a library konoha that switches the tokenizer to a nice feeling
I made a program to check the size of a file in Python
I made a mistake in fetching the hierarchy with MultiIndex of pandas
I tried to verify the result of A / B test by chi-square test
I made a function to see the movement of a two-dimensional array (Python)