[PYTHON] Create a TalkBot easily using Discord.py and A3RT's Talk API (pya3rt).

In the afternoon, I tried various things using a certain Discord.py, There was a person saying this on Discord's server. ** "I want Talking !!" ** Talking-kun is a TalkBot on Discord that is kind to me and has no conversation partner that I often saw for a while ... By the way, there was a free API called A3RT. Alright, let's make it.

Precautions for the time being.

The person who writes this is a Python beginner, so there may be some points that cannot be reached. At that time, please be kind .... Also, this is Qiita's first post. I look forward to working with you. ~~ This is a cat. ~~

environment

Regarding the environment, it is considerably outlaw compared to the bot like the article in Qiita, so if you refer to this, please adjust it to your own environment.

Thing you want to do

If you speak on a specific channel, it will react unconditionally → Return it with Talk API of A3RT.

Then do it.

A3RT API KEY issuance

You can easily issue an API KEY by sending an email from the TalkAPI page. I will use it later.

Write the contents of the bot.

run.py like this.

run.py


import discord
from discord.ext import commands
import asyncio
import os
import sys
import traceback

loop = asyncio.get_event_loop()

airlinia_token = os.environ['AIRLINIA_DISCORD_TOKEN'] #Environment variables ~~.
technetium_token = os.environ['TECHNETIUM_DISCORD_TOKEN']

class DISCORDBOT(commands.Bot):
    #constructor.
    def __init__(self, command_prefix, cogs, **options):
        #Execute by passing a value to the constructor of the superclass.
        super().__init__(command_prefix, **options)
        #In the cog folder.Read the py file.
        for cog in os.listdir(f'./{cogs}'):
            if cog.endswith('.py'):
                try:
                    self.load_extension(f'{cogs}.{cog[:-3]}')
                except Exception:
                    traceback.print_exc()

    async def on_ready(self): #Call when ready.
        print(f"""You are now logged.
        ------\nBot account overview\n Username:{self.user.name}\n User ID:{self.user.id}
        ------\nDiscord.version of py\n{discord.__version__}
        ------\Python version\n{sys.version}
        ――――――――――――――――――――――――――――――""")
        await self.change_presence(activity=discord.Game(name=f'{self.command_prefix}¦{self.user.name} - by.amazakura0804'))

if __name__ == '__main__':
    airlinia = DISCORDBOT(command_prefix='al!', cogs='airlinia_cogs', loop=loop)
    airlinia_task = loop.create_task(airlinia.start(airlinia_token))

    technetium = DISCORDBOT(command_prefix='te!', cogs='technetium_cogs', loop=loop)
    technetium_task = loop.create_task(technetium.start(technetium_token))

    loop.run_until_complete(technetium_task)
    loop.run_until_complete(airlinia_task)
    loop.close()

While referring to Bot development using Bot Commands Framework of discord.py. TOKEN is an environment variable. Please change here depending on the environment. I won't move more than one. I think that this kind of feeling is enough.

run.py


import discord
from discord.ext import commands
import asyncio
import os
import sys
import traceback

token = os.environ['DISCORD_TOKEN']

class HogeBot(commands.Bot):
    #constructor.
    def __init__(self, command_prefix, cogs, **options):
        #Execute by passing a value to the constructor of the superclass.
        super().__init__(command_prefix, **options)
        #In the cog folder.Read the py file.
        for cog in os.listdir(f'./{cogs}'):
            if cog.endswith('.py'):
                try:
                    self.load_extension(f'{cogs}.{cog[:-3]}')
                except Exception:
                    traceback.print_exc()

    async def on_ready(self): #Call when ready.
        print(f"""You are now logged.
        ------\nBot account overview\n Username:{self.user.name}\n User ID:{self.user.id}
        ------\nDiscord.version of py\n{discord.__version__}
        ------\Python version\n{sys.version}
        ――――――――――――――――――――――――――――――""")
        await self.change_presence(activity=discord.Game(name=f'{self.command_prefix}¦{self.user.name} - by.amazakura0804'))

if __name__ == '__main__':
    hogebot = HogeBot(command_prefix='!', cogs='hogebot_cogs')
    hogebot.run(token) #Bot token

Talk.py

Talk.py


import discord
from discord.ext import commands
import asyncio
import os
import pya3rt

class Talk_Bot(commands.Cog):
    def __init__(self, airlinia):
        self.bot = airlinia #Receive a bot.

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot:  #Fly the bot's message
            return
        if message.channel.id == TALK_CHANNEL_ID: #Replace with CHANNEL ID that you want to speak as appropriate.
            client = pya3rt.TalkClient(os.environ['TALK_API_KEY']) #This is also an environment variable, so it is omitted below.
            content = client.talk(message.content)['results'][0]['reply']
            await message.channel.send(content) #Send a reply message

def setup(airlinia):
    airlinia.add_cog(Talk_Bot(airlinia))

Yes. A3RT is odd. Try applying the A3RT API KEY to an environment variable or inserting it directly. With just this code ...

image.png

Yay. God. Thank you Recruit.

Finally

By using various APIs including A3RT, the range of things that can be done will expand considerably. There are many other things that seem interesting, so I would like to take advantage of them.

Recommended Posts

Create a TalkBot easily using Discord.py and A3RT's Talk API (pya3rt).
Create a CRUD API using FastAPI
Let's create a REST API using SpringBoot + MongoDB
Create a web map using Python and GDAL
Create a Mac app using py2app and Python3! !!
Create a REST API using the model learned in Lobe and TensorFlow Serving.
Create a pseudo REST API server using GitHub Pages
Create a real-time auto-reply bot using the Twitter Streaming API
Tornado-Let's create a Web API that easily returns JSON with JSON
I made a Chatbot using LINE Messaging API and Python
Create an API that returns data from a model using turicreate
Create a simple scheduled batch using Docker's Python Image and parse-crontab
[Python] Conversation using OpenJTalk and Talk API (up to voice output)
[Python] I wrote a REST API using AWS API Gateway and Lambda.
I made a Chatbot using LINE Messaging API and Python (2) ~ Server ~
I made a music bot using discord.py and Google Drive API (tested with Docker → deployed to Heroku)
Create a nested dictionary using defaultdict
Create API using hug with mod_wsgi
Easily create homemade RPA using Python
Create a C wrapper using Boost.Python
Create a stack with a queue and a queue with a stack (from LetCode / Implement Stack using Queues, Implement Queue using Stacks)
I tried to create a sample to access Salesforce using Python and Bottle