This is the first post. This time, I had to enter my body temperature on Google Forms every day at school, which was annoying. No, I don't have time to enter it, so let's make a program that randomly sends it between 6:00 and 8:30 every day, and also sends any body temperature between 36.4 and 36.6. It was.
--Python3 series
In creating it, I made it while referring to the article here. Also, I will omit the acquisition of the identification number of the Google Form question this time.
In form_url
, put the URL of the submitted Form, and in ʻentry, put the identification number of the obtained question. Please increase it like ʻans_7
according to the number of questions.
In ʻoutput, write the answer to the question. The values of ʻans_1
and ʻans_4change every day, so enter the appropriate values. Here,
None` is entered as appropriate.
cfg.json
{
"form_url": "https://docs.google.com/forms/d/e/1FAIpQLSc93lIQ3Aob93cwjx6HSRbuC8V7NT59UfUPhlw6AlkGtZ6CXQ/",
"entry": {
"ans_1": 964244932,
"ans_2": 888214820,
"ans_3": 23055831,
"ans_4": 10832147,
"ans_5": 1720496078,
"ans_6": 2017707777
},
"output":{
"ans_1": "None",
"ans_2": "2A",
"ans_3": "8",
"ans_4": "None",
"ans_5": "I'm fine",
"ans_6": "Not in"
}
}
Creating a json file looks like this.
This time, in cooperation with Discord, we will send logs such as whether it was sent properly to a specific Discord channel. The completed program looks like this.
bot.py
# -*- coding: utf-8 -*-
import discord
from discord import Embed
from discord.ext import tasks
from datetime import datetime
import os
import requests
import random
import json
TOKEN = os.environ["TOKEN"]
client = discord.Client(intents=discord.Intents.all())
#The next scheduled transmission time is 06:00-8:Randomly set up to 30
def setting_time_set():
setting_time_h = random.randint(6, 8)
if setting_time_h == 8:
setting_time_m = random.randint(0, 30)
else:
setting_time_m = random.randint(0, 59)
setting_time = f"{setting_time_h:02}:{setting_time_m:02}"
return setting_time
def set_tem():
choice_list = ["36.4", "36.5", "36.6"]
choice_ans = random.choice(choice_list) # 36.4-36.Randomly select up to 6
return choice_ans
time_set = setting_time_set() #Set the first next transmission time at startup
tem_set = set_tem()
#Embed function
async def template_embed(message, title, name_1, name_2, value_1, color, description=None):
ch = client.get_channel(message)
embed_time = datetime.now().strftime("%Y year%m month%d day-%H:%M")
embed = Embed(title=title, description=description, color=color)
embed.add_field(name=name_1, value=f"{value_1}", inline=True)
embed.add_field(name=name_2, value=f"{tem_set}", inline=True)
embed.set_footer(text=f"{embed_time}")
await ch.send("<@User ID>")
await ch.send(embed=embed)
@client.event
async def on_ready():
await template_embed(message=768274673984208926, title="Startup log", name_1="Next scheduled transmission time", value_1=time_set,
name_2="Body temperature to be sent", color=discord.Color.orange())
@client.event
async def on_message(message):
if message.content == "/reset":
await reset(message)
if message.content == "/now":
await now(message)
async def reset(message):
global time_set
global tem_set
time_set = setting_time_set()
tem_set = set_tem()
await template_embed(message=768274673984208926, title="Reset", name_1="Next scheduled transmission time", name_2="Body temperature to be sent",
value_1=time_set, color=discord.Color.purple())
await template_embed(message=message.channel.id, title="Reset", name_1="Next scheduled transmission time", name_2="Body temperature to be sent",
value_1=time_set, color=discord.Color.purple())
async def now(message):
await template_embed(message=message.channel.id, title="current situation", name_1="Next scheduled transmission time", name_2="Body temperature to be sent",
value_1=time_set, color=discord.Color.greyple())
@tasks.loop(seconds=60)
async def loop():
global time_set
global tem_set
now_t = datetime.now().strftime('%H:%M')
print(f"Current time:{now_t}/ Scheduled transmission time:{time_set}/ Scheduled body temperature to be transmitted:{tem_set}")
if now_t == time_set: #Is it the scheduled transmission time?
dt_now = datetime.now().strftime("%Y-%m-%d") #Current time 2020-01-Obtained in the form of 01, dt_Store in now
file_name = "cfg.json"
with open(file_name, "r", encoding="utf-8")as f:
cfg = json.load(f)
cfg["output"]["ans_1"] = f"{dt_now}"
cfg["output"]["ans_4"] = f"{tem_set}"
params = {"entry.{}".format(cfg["entry"][k]): cfg["output"][k] for k in cfg["entry"].keys()}
res = requests.get(cfg["form_url"] + "formResponse", params=params)
if res.status_code == 200:
await template_embed(message=768274673984208926, title="Log information", description=f"[URL]({res.url})",
name_1="Completion status", name_2="Sent body temperature", value_1="Succeeded", color=discord.Color.green())
else:
res.raise_for_status()
await template_embed(message=768274673984208926, title="Log information", name_1="Completion status", name_2="Body temperature to be sent",
value_1="An error has occurred.", color=discord.Color.red())
else:
if now_t == "21:00":
time_set = setting_time_set()
tem_set = set_tem()
await template_embed(message=768274673984208926, title="Notification of transmission time update", name_1="Next scheduled transmission time", name_2="Body temperature to be sent",
value_1=time_set, color=discord.Color.blue())
loop.start()
client.run(TOKEN)
I will explain step by step.
First of all, regarding this part, the transmission time is randomly issued between 6:00 and 8:30 and returned to setting_time
, and then the body temperature is randomly selected and returned to choice_ans
.
In the process below that, the transmission time and body temperature are set at the first startup. Furthermore, the processing below it is the generation processing of Embed.
#The next scheduled transmission time is 06:00-8:Randomly set up to 30
def setting_time_set():
setting_time_h = random.randint(6, 8)
if setting_time_h == 8:
setting_time_m = random.randint(0, 30)
else:
setting_time_m = random.randint(0, 59)
setting_time = f"{setting_time_h:02}:{setting_time_m:02}"
return setting_time
def set_tem():
choice_list = ["36.4", "36.5", "36.6"]
choice_ans = random.choice(choice_list) # 36.4-36.Randomly select up to 6
return choice_ans
time_set = setting_time_set() #Set the first next transmission time at startup
tem_set = set_tem()
#Embed function
async def template_embed(message, title, name_1, name_2, value_1, color, description=None):
ch = client.get_channel(message)
embed_time = datetime.now().strftime("%Y year%m month%d day-%H:%M")
embed = Embed(title=title, description=description, color=color)
embed.add_field(name=name_1, value=f"{value_1}", inline=True)
embed.add_field(name=name_2, value=f"{tem_set}", inline=True)
embed.set_footer(text=f"{embed_time}")
await ch.send("<@User ID>")
await ch.send(embed=embed)
I will explain the main processing.
@client.event
async def on_ready():
await template_embed(message=768274673984208926, title="Startup log", name_1="Next scheduled transmission time", value_1=time_set,
name_2="Body temperature to be sent", color=discord.Color.orange())
At startup, the startup log will be sent to a specific channel.
@client.event
async def on_message(message):
if message.content == "/reset":
await reset(message)
if message.content == "/now":
await now(message)
async def reset(message):
global time_set
global tem_set
time_set = setting_time_set()
tem_set = set_tem()
await template_embed(message=768274673984208926, title="Reset", name_1="Next scheduled transmission time", name_2="Body temperature to be sent",
value_1=time_set, color=discord.Color.purple())
await template_embed(message=message.channel.id, title="Reset", name_1="Next scheduled transmission time", name_2="Body temperature to be sent",
value_1=time_set, color=discord.Color.purple())
async def now(message):
await template_embed(message=message.channel.id, title="current situation", name_1="Next scheduled transmission time", name_2="Body temperature to be sent",
value_1=time_set, color=discord.Color.greyple())
Here, the processing of the reset command that can reset the transmission time and body temperature and the command that can check the current status.
@tasks.loop(seconds=60)
async def loop():
global time_set
global tem_set
now_t = datetime.now().strftime('%H:%M') #Get the current time
print(f"Current time:{now_t}/ Scheduled transmission time:{time_set}/ Scheduled body temperature to be transmitted:{tem_set}")
if now_t == time_set: #Is it the scheduled transmission time?
dt_now = datetime.now().strftime("%Y-%m-%d") #Current time 2020-01-Obtained in the form of 01, dt_Store in now
file_name = "cfg.json"
with open(file_name, "r", encoding="utf-8")as f:
cfg = json.load(f)
cfg["output"]["ans_1"] = f"{dt_now}" #Ans today's year, month, day_Overwrite 1
cfg["output"]["ans_4"] = f"{tem_set}" #Body temperature ans_Overwrite 4
params = {"entry.{}".format(cfg["entry"][k]): cfg["output"][k] for k in cfg["entry"].keys()}
res = requests.get(cfg["form_url"] + "formResponse", params=params)
if res.status_code == 200: #When sent normally
await template_embed(message=768274673984208926, title="Log information", description=f"[URL]({res.url})",
name_1="Completion status", name_2="Sent body temperature", value_1="Succeeded", color=discord.Color.green())
else: #If you could not send
res.raise_for_status()
await template_embed(message=768274673984208926, title="Log information", name_1="Completion status", name_2="Body temperature to be sent",
value_1="An error has occurred.", color=discord.Color.red())
else:
if now_t == "21:00":
time_set = setting_time_set()
tem_set = set_tem()
await template_embed(message=768274673984208926, title="Notification of transmission time update", name_1="Next scheduled transmission time", name_2="Body temperature to be sent",
value_1=time_set, color=discord.Color.blue())
Here, tasks.loop ()
is used to check the current time and the scheduled transmission time at 60-second intervals, and if they match, the transmission process is performed.
If they do not match, the current time and reset time are checked to see if they match, and if it is the reset time, the reset process is performed.
Please note that it is quite a mess because it is the first post. The completed code is posted on Github, so feel free to use it .... Towards the end, I omitted the explanation considerably, but I hope it will be helpful.
Win the fucking survey with Google Form auto-answer bot (Python3)
Recommended Posts