I created a Discord bot on Docker that reports the number of corona infected people in Tokyo at a specified time.

I am a new graduate in 2020 and am working in IT. Since this is my first post on Qiita, I think there are some points that cannot be reached, but thank you.

Purpose

I was addicted to making bots using discordApi, so I tried to make a bot like a title for scraping practice.

Execution environment

Windows

VPS

procedure

Build on Windows and check the operation of the bot

I will omit the token acquisition of bot because it is written a lot in other articles. Install the library used by the following command pip install beautifulsoup4 pip install requests pip install discord The site targeted for scraping this time is Tokyo Metropolitan Government's new coronavirus infection control site. First of all, let's verify whether you can get the data you want with Beautiful Soup. The source code is as follows.

soup.py



import requests
from bs4 import BeautifulSoup

#Get data by connecting to URL with get
res= requests.get("https://stopcovid19.metro.tokyo.lg.jp/cards/number-of-confirmed-cases/")

#Store object
soup = BeautifulSoup(res.text,"html.parser")

#Filter by the tag and class of the part you want, remove the part that does not use extract
con = soup.find("span",class_="DataView-DataInfo-summary")
con=soup.find("small",class_="DataView-DataInfo-summary-unit").extract()

text=con.get_text()

text= text.strip()


print(text+"Is a person")

When I try to do this image.png I was able to get it firmly, and I was able to erase the blanks.

Next, we will incorporate this into the discord bot program. Using the loop function included in discord.py, I created a program that loops once every 60 seconds and scrapes and posts to the text channel at the specified time. The source is as follows.

bot.py


#coding:UTF-8
import discord
from discord.ext import tasks
from datetime import datetime
import requests
from bs4 import BeautifulSoup

TOKEN = "hoge" #token
CHANNEL_ID = hoge #Channel ID

#Generate the objects needed for the connection
client = discord.Client()

#Loop once every 60 seconds
@tasks.loop(seconds=60)
async def loop():    
    now = datetime.now().strftime('%H:%M')
    
    if now == '20:05':
        await client.wait_until_ready()
        channel = client.get_channel(CHANNEL_ID)
        #The previous code(soup.py)
        res= requests.get("https://stopcovid19.metro.tokyo.lg.jp/cards/number-of-confirmed-cases/")
        soup = BeautifulSoup(res.text,"html.parser")
        con = soup.find("span",class_="DataView-DataInfo-summary")
        con=soup.find("small",class_="DataView-DataInfo-summary-unit").extract()
        text=con.get_text()
        text= text.strip() 

        await channel.send("The number of infected people in Tokyo today is"+text+"Is a person") 

 #Bonus part. Ability to return comments in response to a specified word
@client.event
async def on_message(message):
    #Ignore if the message sender is a bot
    if message.author.bot:
        return
    #If you say "Shinjuku", "Dense" will be returned
    if message.content == 'Shinjuku':
        await message.channel.send('Dense')
    
    if message.content == 'Edogawa Ward':
        await message.channel.send('Dense')

#Loop processing execution
loop.start()
#Bot launch
client.run(TOKEN)

The time is set to 20:05 because it is estimated that the number of infected people on the site used this time will be updated at 20:00. Execution result image.png

Transport to Docker

docker run -it --name hoge python /bin/bash Build a python environment with docker exec -it hoge bash I went inside and started work. First, install the required libraries with pip. pip install beautifulsoup4 pip install requests pip install discord I can't edit without vim apt-get update apt-get install vim I will put it in. Because the default timezone is UTC ln -sf /usr/share/zoneinfo/Asia/Tokyo /etc/localtime Use this command to change the time zone. After that, create an appropriate folder, create bot.py in it, and copy and paste the source. This completes. If you start it with python bot.py, a bot will start up on discord and report the number of people infected with corona today in Tokyo at the specified time!

Improvement points

This time, we assume that the site will be updated at 20:00 and make a definite decision, but the ideal form is that the site will be updated and scraped at the same time and the bot will report it. In the loop, I thought that it would be possible to write a program that compares the data acquired in that loop with the data acquired last time, updates it if it matches, and the bot reports it, so if it improves, another article I will post it all together.

Recommended Posts

I created a Discord bot on Docker that reports the number of corona infected people in Tokyo at a specified time.
Create a BOT that displays the number of infected people in the new corona
Create a bot that posts the number of people positive for the new coronavirus in Tokyo to Slack
[Concept] bot that posts the start notification of Nico Nico Live Broadcasting to Discord on discord.py
Make a BOT that shortens the URL of Discord
Create a bot that only returns the result of morphological analysis with MeCab on Discord
Let's execute the command on time with the bot of discord
Get comments on Nico Nico Live Broadcasting
Create a bot that posts the number of people positive for the new coronavirus in Tokyo to Slack
I tried to make a translation BOT that works on Discord using googletrans
Looking back on the history of expressions that return sum of square to Pythonic
I created a Discord bot on Docker that reports the number of corona infected people in Tokyo at a specified time.
I tried to predict the number of domestically infected people of the new corona with a mathematical model
[Discode Bot] I created a bot that tells me the race value of Pokemon
Make a BOT that shortens the URL of Discord
Posted the number of new corona positives in Tokyo to Slack (deployed on Heroku)
A server that returns the number of people in front of the camera with bottle.py and OpenCV
Create a bot that only returns the result of morphological analysis with MeCab on Discord
Let's execute the command on time with the bot of discord
Analyzing data on the number of corona patients in Japan
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
A function that measures the processing time of a method in python
I made a slack bot that notifies me of the temperature
Get the number of readers of a treatise on Mendeley in Python
I started to work at different times, so I made a bot that tells me the time to leave
Count the number of times two values appear in a Python 3 iterator type element at the same time
I made a Discord bot in Python that translates when it reacts
I measured the run queue wait time of a process on Linux
Get a datetime instance at any time of the day in Python
I created a script to check if English is entered in the specified position of the JSON file in Python.
I tried to predict the number of people infected with coronavirus in Japan by the method of the latest paper in China
I tried to predict the number of people infected with coronavirus in consideration of the effect of refraining from going out
I created a Slack bot that confirms and notifies AWS Lambda of the expiration date of an SSL certificate
The story of IPv6 address that I want to keep at a minimum
I made a LINE Bot that sends recommended images every day on time
I tried to make a translation BOT that works on Discord using googletrans
A program that sends a fixed amount of mail at a specified time by Python
At the time of python update on ubuntu
A python script that gets the number of jobs for a specified condition from indeed.com
[Example of Python improvement] I learned the basics of Python on a free site in 2 weeks.
A template that I often use when making Discord BOT in Python (memorial note)
[Python] A program that finds the shortest number of steps in a game that crosses clouds
I want to take a screenshot of the site on Docker using any font
I made a program in Python that changes the 1-minute data of FX to an arbitrary time frame (1 hour frame, etc.)
I drew a Python graph using public data on the number of patients positive for the new coronavirus (COVID-19) in Tokyo + with a link to the national version of practice data
Execute packet capture at the specified time on CentOS7
[Python] A program that counts the number of valleys
I tried to find the trend of the number of ships in Tokyo Bay from satellite images.
[Concept] bot that posts the start notification of Nico Nico Live Broadcasting to Discord on discord.py
I tried to make a script that traces the tweets of a specific user on Twitter and saves the posted image at once