[PYTHON] [Discode Bot] I created a bot that tells me the race value of Pokemon

Background of creation

Race value is an important factor in determining stats in Pokemon. In fact, when you play Pokemon, you may not be able to play a decent game unless you know the race value. At present, if you don't know the race value of Pokemon, you have to do a Google search every time, which I found to be troublesome. So I started to think that it would be convenient to have a chat bot that interactively tells me the race value.

Purpose

There are three main purposes.

--Reduced search effort --Activation of Discord server -Get parts and knowledge that can be used for future development

Specifically, the parts and knowledge that can be used for development include "Pokemon race value database" and "Common Pokemon name mistakes". (I want to correct it to the correct Pokemon name by knowing how to make a mistake in a common Pokemon name)

Completion drawing

[Pokemon name] pictorial book When you chat with, it will tell you the race value of Pokemon. IMG_0468.jpg For the time being, I installed it only on the discord server I run. Introduction of Discord server "Gatserver" for Pokemon Gachi About 200 people participated, including several people who have experienced first place in the season.

[github](https://github.com/ryoYAMAZAKI11/Pokemonbot )

environment

【local】 MacOS Catalina Ver. 10.15.4 Python Ver. 3.7.7 【server】 I made the bot resident on xserver by following the procedure on the following site. https://ogapsan.com/archives/1077

Implementation

I looked it up on a Discord Bot and found Python to be fun. I saved the Pokemon race value data in a json file as a database in advance, and made it "take out the race value data and make it react to Discord Bot" in Python.

Database of race values

Created with reference to National Encyclopedia of Pokemon Thorough Strategy.

Part of the database


{
...

"Charmander":{"No":"4","Pokemon name":"Charmander","HP":"39","attack":"52","defense":"43","Special attack":"60","Special defense":"50","Agility":"65","total":"309"},
"Lizard":{"No":"5","Pokemon name":"Lizard","HP":"58","attack":"64","defense":"58","Special attack":"80","Special defense":"65","Agility":"80","total":"405"},
"Charizard":{"No":"6","Pokemon name":"Charizard","HP":"78","attack":"84","defense":"78","Special attack":"109","Special defense":"85","Agility":"100","total":"534"},

...
}

Body of Pokédex bot

https://qiita.com/1ntegrale9/items/9d570ef8175cf178468f I installed discord.py from the acquisition of the bot token with reference to.

The source code is below

main.py


import sys
import discord
import json
from collections import OrderedDict
import pprint
import re
import bot_token

client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as', file=sys.stderr)
    print(client.user.name, file=sys.stderr)
    print(client.user.id, file=sys.stderr)
    print('------', file=sys.stderr)
    
@client.event



async def on_message(message):
    #I don't want to react if the sender is a bot
    if message.author.bot:
        return
    #Find out if it starts with "picture book"
    if message.content == 'Zakoyama's illustrated book':
        message_send = "The creator of this bot, Lotto!" + "\n" + "Lotto to contact us on twitter for any problems!"+ "\n" + "https://twitter.com/zakoyama_com"
        
    elif re.match('.+Picture book$', message.content):
        json_open = open('pokedex_zen.json', 'r')
        json_load = json.load(json_open)    
        #Get the Pokemon name from the message (remove the "picture book" part)
        m = message.content[0:len(message.content)-3]
        
        #Send a message to the channel to which the message was sent
        if m in json_load:
            message_send = "```"
            for key, value in json_load[m].items():
                if key == 'No':
                    message_send = message_send + '%s.%s'%(key, value) + ' '
 elif key =='Pokemon name':
 message_send = message_send +'% s'% (value) + "\ n" +'HP Attack Defense Special Attack Special Defense Quick Total \ n'
                elif key == 'HP' :    
                    message_send = message_send + '%3d'%(int(value))
                else:    
                    message_send = message_send + '%4d'%(int(value))
                    
            message_send = message_send + "```"
            print('0 ' + m)#To log
        else:
            message_send = "Lotto where no Pokemon can be found!"
            print('1 ' + m)#To log
            
    await message.channel.send(message_send)
    
client.run(bot_token.TOKEN)

bot_token.py


TOKEN = "Tokens obtained here"

Point 1: Trigger the picture book of [Pokemon name]

Most of the users are Japanese, and it is said that they are inputting from a smartphone, so commands like `! P``` that are common in Discord bots are not good? I thought. Therefore, the bot responds with the [Pokemon name] picture book `` which is easy to input even from a smartphone.

main.Excerpt from py


    elif re.match('.+Picture book$', message.content):

In this way, it is extracted using the regular expression module `` `re```.

main.Excerpt from py


    #Get the Pokemon name from the message (remove the "picture book" part)
    m = message.content[0:len(message.content)-3]

The Pokemon name was stored in the variable `` `m``` by removing the three-letter" picture book "part from the end.

Point 2: Make the race value as easy to see as possible

In Discord, the character width of alphabets and spaces differs depending on the type. Therefore, just arranging them will cause a large deviation like this. IMG_0594.jpg So I used the Discord code block. "```If you enclose it in ", it becomes a code block. The size of the alphabet and half-width space is unified, and the Japanese character size is also smaller, making it easier to see. IMG_0595.jpg However, the size of full-width Japanese and alphabets and half-width spaces is 2:Since it is not 1, it seems that it will shift a little when trying to translate it into Japanese. It is implemented as follows in the source code.

main.Excerpt from py


 #Send a message to the channel to which the message was sent
        if m in json_load:
            message_send = "```"#Start the code block here
            for key, value in json_load[m].items():
                if key == 'No':
                    message_send = message_send + '%s.%s'%(key, value) + ' '
                elif key == 'Pokemon name':
                    message_send = message_send + '%s'%(value) + " \n"  + 'HP Attack Defense Special Attack Special Defense Quick Total\n'
                elif key == 'HP' :    
                    message_send = message_send + '%3d'%(int(value))
                else:    
                    message_send = message_send + '%4d'%(int(value))
                    
 message_send = message_send + "` `` "# Close the code block here

###Point 3: Log is standard output If it is true, I wanted to record a log and make it like "Pokemon ranking that is searched a lot", but I do not feel like I can make it immediately, and the purpose of logging is "I want to know how to make a mistake in a common Pokemon name" Therefore, I decided to make the standard output log and record it. It is spit out by the print function as follows.

main.Excerpt from py


 print ('0' + m) # To log
...

 print ('1' + m) # To log

If a Pokemon is found0, If not found1You can check "common mistakes in Pokemon names". (If you perform text processing, you can also find out which Pokemon are often searched)

Part of the log


 0 Heat Rotom
 0 Gyarados
 0 Cinccino
 0 Froslass
 1 Alola Ninetales
 0 Ninetales
 0 Togekiss

When executing on the server to take this log, execute with the following command.

nohup python3 main.py 1>> out.log 2> /dev/null &

with thisout.logIs logged. #Achievement of purpose I introduced this bot for about 2 months. Check the achievement level for each of the three objectives.

-Reduced search effort -Discord server activation -Acquire parts and knowledge that can be used for future development

###Reduced search effort It's pretty easy. You don't have to do a google search, so it's easy. However, since the race value alone is not enough as information and I want to know the technique and characteristics, I may end up doing a google search. This is a future issue.

###Discord server activation At the beginning of the introduction of the bot, there were about 20 participants, but the number has exceeded 200. It has become quite active. It is thought that one of the reasons is that the tweets in the process of being created received a lot of RT. Extended tweets

###Acquire parts and knowledge that can be used for future development I was able to create a list of Pokemon race values.

Regarding the log, when I checked it and found no Pokemon, it was filled with 80% off-color humor and was useless. Probably a triggerPicture book ofBecauseIt seems that there are people who are playing with obscene words in the part of.

#Summary It was created in one week and adjusted while being introduced for about two months. I've made something with a decent function, but honestly, it's not working very well (about once a day). I will continue to improve it without fail.

What impressed me was that when the tweet was RT, many people said that they wanted to use it, but few actually used it. I keenly realized that the needs that people say and the true needs that are actually needed may be different.

Recommended Posts

[Discode Bot] I created a bot that tells me the race value of Pokemon
I made a slack bot that notifies me of the temperature
I made a LINE bot that tells me the type and strength of Pokemon in the Galar region with Heroku + Flask + PostgreSQL (Heroku Postgres)
I want a Slack bot that calculates and tells me the salary of a part-time job from the schedule of Google Calendar!
I started to work at different times, so I made a bot that tells me the time to leave
[Python] I made a bot that tells me the current temperature when I enter a place name on LINE
The story of making a Line Bot that tells us the schedule of competitive programming
Make a BOT that shortens the URL of Discord
I created a Slack bot that confirms and notifies AWS Lambda of the expiration date of an SSL certificate
[Go] Create a tool that returns the Pokemon race value received from the standard input
[Python & SQLite] I analyzed the expected value of a race with horses with a win of 1x ②
I created a Discord bot on Docker that reports the number of corona infected people in Tokyo at a specified time.
When incrementing the value of a key that does not exist
I made a Twitter bot that mutters Pokemon caught by #PokemonGO
I made a Line bot that guesses the gender and age of a person from an image
I made a calendar that automatically updates the distribution schedule of Vtuber
I wrote a corpus reader that reads the results of MeCab analysis
I tried to display the altitude value of DTM in a graph
[Python & SQLite] I tried to analyze the expected value of a race with horses in the 1x win range ①
I made a LINE BOT that returns a terrorist image using the Flickr API
The story of IPv6 address that I want to keep at a minimum
I made a SlackBot that notifies me of AtCoder contest information every week
With LINEBot, I made an app that informs me of the "bus time"
I made a Linebot that notifies me of nearby evacuation sites on AWS
Create a BOT that displays the number of infected people in the new corona
I created a function that splits a clumsy copy of a PDF text reasonably well.
I made a github action that notifies Slack of the visual regression test
I made a twitter app that decodes the characters of Pricone with heroku (failure)
The story of Linux that I want to teach myself half a year ago
[Python / C] I made a device that wirelessly scrolls the screen of a PC remotely.
I made a calendar that automatically updates the distribution schedule of Vtuber (Google Calendar edition)
A story that reduces the effort of operation / maintenance
[Python] A program that counts the number of valleys
# Function that returns the character code of a string
LINE Bot that notifies you of the stocks of interest
Generate that shape of the bottom of a PET bottle
A memo that I touched the Datastore with python
The story that the return value of tape.gradient () was None
A story that analyzed the delivery of Nico Nama.
[Python] A program that compares the positions of kangaroos.
When I created an ECR scan from a CDK, I could see the back side of the scan
I made an API with Docker that returns the predicted value of the machine learning model
I tried to create a Python script to get the value of a cell in Microsoft Excel
A tool that automatically turns the gacha of a social game
Code that sets the default value in case of AttributeError
I made a LINE BOT that returns parrots with Go
A network diagram was created with the data of COVID-19.
I just changed the sample source of Python a little.
Find the index of the maximum value (minimum value) of a multidimensional array
I made a function to check the model of DCGAN
I made a dot picture of the image of Irasutoya. (part1)
I tried a little bit of the behavior of the zip function
I made a dot picture of the image of Irasutoya. (part2)
Extract the value of dict or list as a string
The story of making a question box bot with discord.py
A Python script that compares the contents of two directories
I wrote a script that splits the image in two
I tried to make a site that makes it easy to see the update information of Azure
I wrote AWS Lambda, and I was a little addicted to the default value of Python arguments
I will publish a shell script created to reduce the trouble of creating LiveUSB on Linux
I analyzed the image of the Kyudo scoring book (a booklet that records the results of the hits). (Google Colaboratory)