ProHoster > Blog > internet news > How to delegate simple reports to a robot. We write a bot in Python and Google BigQuery
How to delegate simple reports to a robot. We write a bot in Python and Google BigQuery
Do you have tasks that repeat day after day, week after week? For example, writing reports. You request data, analyze, visualize (make graphs, charts), and then send it to your boss. But what if all this is automated?
In this tutorial, we will create a bot for Telegram that will help automate reporting. And the coolest thing is that the whole program will consist of only 50 lines of code! If you are creating a bot for Telegram for the first time, then you should also read this one post.
If we want to use the service, we need to connect the Google BigQuery API. For this we go to Google Developers Console and create a new project (or select an existing one).
In the control panel, select ENABLE APIS AND SERVICES and look for the BigQuery API.
Select Enable to connect the API.
Create an account key
Let's go again to Google Developers Console, select the tab Credentials, Create credentials and Service account key.
Then - New service account, and in the Service account name field, enter a name.
From the Role drop-down list, select Project > Owner, then Create.
The file that will automatically load is called creds.json.
We expose GOOGLE_APPLICATION_CREDENTIALS, specifying the path to creds.json in the terminal.
This function will return the query as a data frame.
Visualizing data
To solve this problem, choose matplotlib.
import matplotlib.pyplot as plt
We need five parameters, where x is the x-axis data, x_label is the title for the axis, y is the y-axis data, y_label is the title for the axis, and title is the title of the entire visualization.
def visualize_bar_chart(x, x_label, y, y_label, title):
plt.title(title)
plt.xlabel(x_label)
plt.ylabel(y_label)
index = np.arange(len(x))
plt.xticks(index, x, fontsize=5, rotation=30)
plt.bar(index, y)
return plt
Saving the image
Now let's use two functions to create a visualization and save it.
We will send the number of posts published daily. First, we write a request.
query = """
SELECT DATE(creation_date) date, COUNT(*) total_posts
FROM `bigquery-public-data.stackoverflow.post_history`
GROUP BY 1
HAVING date > DATE_SUB('2018-12-02', INTERVAL 14 DAY)
ORDER BY 1
"""
The query helps collect data for two weeks starting December 2, 2018.
We use this date because 2018-12-02 is the latest data recorded in bigquery-public-data.stackoverflow.post_history, otherwise you can use CURRENT_DATE() to get the newest data.
We call the query_to_bigquery function to get the data.
dataframe = query_to_bigquery(query)
We then use the date data column for the x-axis and the total_posts column for the y-axis.
x = dataframe['date'].tolist()
y = dataframe['total_posts'].tolist()
Visualize using the visualize_bar_chart function and save as an image.
We wrap this code in a function called get_and_save_image.
def get_and_save_image():
query = """
SELECT DATE(creation_date) date, COUNT(*) total_posts
FROM `bigquery-public-data.stackoverflow.post_history`
GROUP BY 1
HAVING date > DATE_SUB('2018-12-02', INTERVAL 14 DAY)
ORDER BY 1
"""
dataframe = query_to_bigquery(query)
x = dataframe['date'].tolist()
y = dataframe['total_posts'].tolist()
plt = visualize_bar_chart(x=x, x_label='Date', y=y, y_label='Total Posts', title='Daily Posts')
plt.savefig('viz.png')
Sending an image
In order to send a report to the addressee, you need to know the chat_id parameter.
Use userinfobot and type /start. The bot responds with the necessary information, the chat_id is contained in the id field.
Now we create the send_image function. It will use the get_and_save_image function to get and save the image. And then we send everything to the right contact.