Write an automatic reminder program for your girlfriend in python

Posted by ManInBlack on Thu, 07 Oct 2021 21:23:48 +0200

The background of the event is that there are often many trivial things that need to be done at a certain time point. Relying on manpower alone is prone to deviation, especially for players who are easy to get confused.

So I started to write a set of code, which can send messages through wechat as needed. Whether it is a memo to serve as an automatic reminder or a timed message to others, it can be realized on the basis of this set of code.

First put an example of the final result:

The text in the figure can be modified according to their own needs, so the code attached in the article is just a brick to attract jade, and readers can adjust it according to their own needs. This article will be divided into three parts to introduce the implementation methods in turn, which are

  1. Determination of text content
  2. Implementation of sending message on wechat end
  3. Setting of scheduled tasks

Step 1: Determination of text content

The "text content" here actually refers to the information you want to send, so its content is very different and needs to be adjusted according to your own needs. The author will briefly introduce the code corresponding to the content in the screenshot. The first line of the screenshot "good morning every day" is set when wechat sends a message, and the second line is a simple greeting, just plain text, The following table is not here.
The third line is "it's now 11:25, Thursday, 2021-10-07". The date and number of weeks when sending the message. The corresponding python script is as follows:

# Send content today date and week
import datetime
import calendar
import time
sysdate = datetime.date.today()  # Get date only
now_time = datetime.datetime.now()  # Get date plus time
week_day = sysdate.isoweekday()  # Get day of week
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
text_date = 'Now it is' + str(now_time)[0:16] + ',' + week[week_day -1 ]
print(text_date)

In the fourth line, "the weather is sunny and the temperature is 8 ~ 19 degrees Celsius", a simple crawler will be involved. We need to climb the current weather on the weather website. The script is as follows:

#Sending content: weather conditions
import requests
from bs4 import BeautifulSoup
import datetime

url = 'http://www.weather.com.cn/weather/101010300.shtml'
sysdate=datetime.date.today()
r = requests.get(url, timeout=30)  # Grab web page information with requests
r.raise_for_status()  # You can stop the program when the program generates an exception
r.encoding = r.apparent_encoding #Coding format
html=r.text

final_list = []
soup = BeautifulSoup(html, 'html.parser')  # use BeautifulSoup Library parsing web page #There are suggestions for the current weather in the soup
body = soup.body #Intercept a part of the body from the soup
data = body.find('div', {'id': '7d'})
ul = data.find('ul')
lis = ul.find_all('li')

for day in lis:
    temp_list = []

    date = day.find('h1').string  # Date found
    if date.string.split('day')[0]==str(sysdate.day):
        temp_list = []

        date = day.find('h1').string  # Date found
        temp_list.append(date)

        info = day.find_all('p')  # Find all p Tags
        temp_list.append(info[0].string)

        if info[1].find('span') is None:  # Find the second value 'span' tag in the p tag - maximum temperature
            temperature_highest = ' '  # Use a to determine whether there is a maximum temperature
        else:
            temperature_highest = info[1].find('span').string
            temperature_highest = temperature_highest.replace('℃', ' ')

        if info[1].find('i') is None:  # Find the second value 'i' tag in the p tag - maximum temperature
            temperature_lowest = ' '  # Use a to determine whether there is a minimum temperature
        else:
            temperature_lowest = info[1].find('i').string
            temperature_lowest = temperature_lowest.replace('℃', ' ')

        temp_list.append(temperature_highest)  # Add maximum temperature to temp_list
        temp_list.append(temperature_lowest)  # Add minimum temperature to temp_list

        final_list.append(temp_list)  # Set temp_ Add list to final_list
        text_weather = 'The weather is' + final_list[0][1] + ',The temperature is' + final_list[0][3].strip() + '~' + final_list[0][2].strip() + 'centigrade'

The fifth line is "just paid salary, please be nice to it". Here is to calculate the number of days from the salary date. After all, there is nothing more that migrant workers care about most.

import datetime
import calendar
import time
import emoji
# Gets the last day of the current month
next_month = sysdate.replace(day=28) + datetime.timedelta(days=4)  # Get to next month
minus = datetime.timedelta(days=next_month.day)  # Get next_ Days of month
salary_date=next_month - minus  # next_month minus its own days, you can get the last day of the month at the end of the month

# Judging the actual pay date, only weekends are considered, and holidays are not considered
if salary_date.isoweekday() == 6:
    salary_date_actual = salary_date - datetime.timedelta(days=1)  # If the salary is paid on Saturday, it will be paid on Friday, one day in advance
elif salary_date.isoweekday() == 7:
    salary_date_actual = salary_date - datetime.timedelta(days=2)  # If the salary is paid on Sunday, it will be paid on Friday, 2 days in advance
else:
    salary_date_actual=salary_date  # Actual payroll date

# Gets the number of days difference between the current date and the payday
day_between = salary_date_actual.day - sysdate.day
if day_between == 0:
    text_salary = 'Pay today!go for it!!!'
elif day_between < 0 or day_between > 20:
    text_salary = 'Please treat the newly paid salary better' + emoji.emojize(':wink:', use_aliases=True)
else:
    text_salary = 'It's still a long way from salary' + str(day_between) + 'day'

So far, the text content in the screenshot has been realized. You can see that the code of this step is closely related to the actual needs, so readers can complete this step according to their own needs.

Step 2: implementation of sending messages at wechat end

After we have determined the text content, we need to send the information through wechat. In previous years, third-party libraries such as itchat were used, but these libraries seem to be unavailable recently, so we can only find other ideas. WeChat official account has official permission to send messages to users, so the function of WeChat official account is considered to achieve this function. So the author tried to use his personal WeChat public number, but found that the main body is not authorized by the official account, and if he wants to apply for the type of enterprise, he has to pay his own money. So we can only abandon the use of its own official account of WeChat.

Instead, turn to the existing WeChat official account that can provide the initiative to send messages: meow reminder.
You can search this name directly. After paying attention, find "add reminder" and complete it in order. Note that in the first step, we don't press the four words "good morning every day" in the first line of the table. In fact, it is set in the meow reminder, that is, the name of this reminder. The "reminder" option is chosen to remind the public official account. After all, only this is free.

When you complete the reminder settings in meow reminder, the system will return a "meow code" to you. This meow code must be saved. Only when you visit the corresponding address of the meow code, will the official account send you the message.

When you complete this step, you only need to access the corresponding address of the meow code through the python script, and pass the content you need to send. The official account will send the content to WeChat again. The code is as follows:

from urllib import request, parse
import json
#Visit meow reminder and send wechat message
class Message(object):
    def __init__(self,text):
        self.text = text
    def push(self):
        # Important, fill in your own bound id in id
        page = request.urlopen("http://miaotixing.com/trigger? "+ parse.urlencode ({" Id ":" fill in meow code here "," text ": self.text," type ":" JSON "}))
        result = page.read()
        jsonObj = json.loads(result)
        if (jsonObj["code"] == 0):
            print("\nReminder message was sent successfully")
        else:
            print("\nReminder message failed to be sent,wrong code: " + str(jsonObj["code"]) + ",describe: " + jsonObj["msg"])

text = f"""
Good morning❤❤❤❤❤❤❤❤
{text_date}
{text_weather}
{text_salary}
"""
message = Message(text)
message.push() # Complete push

The text in this code is what you need to send. In the code, "fill in the meow code here" needs to copy the meow code mentioned above. The greeting content of "good morning" is written manually here, and {text_date}, {text_weather}, {text_salary} is what we prepared in the first step.
However, official account official mail is required to send any message to WeChat official account every 48 hours. Otherwise, the official account will lose the authority to send messages to you. However, in practical use, this malpractice can still be received, because when the public number sends you a message, you can return a message at random, of course. If there is a better way, please give advice to readers.

Step 3: setting of scheduled tasks

When the first two steps are completed, when you call the python script, you can get the WeChat official account to send messages to you, but in the actual scenario, it is definitely hoped that the script can be invoked automatically instead of manually. In order to achieve this goal, it was originally considered to operate regularly through the schedule library, but later it was found that the script needed to run in the background when using the library. Moreover, other operations cannot be carried out, so we choose the "planning program" function of WIN10 system, and the corresponding path is: control panel - system and security - management tools - task planning program.
Before setting the plan, there is another preparatory work to be done, because WIN10 system cannot directly call python script, so we need to prepare a txt file first, which contains
python xxx.py
xxx corresponds to the name of the written Python script. After completing the content, modify the suffix of the txt file to. Bat, and make the bat file and the python script in the same folder, so as to form a bat file that can be called by the WIN10 system, and the content of the bat file is to call the python script you specify.
After completing this preparation, we select "create basic task" in the "scheduler" panel

Fill in the plan name and description, and click next to select the scheduling frequency according to your own needs

If you choose every day, you also need to choose the specific time according to your own needs.
You can only select "start program" for "operation" in the next step

In the next step, "start the program", we need to prepare the bat file in advance. Select the bat file under "program or script" and fill in the file path of the bat file in the box after "start from".

Things are still a little short here.
After completing the above operations, the plan you just named will appear in the planning program panel. After selecting it, right-click to enter "properties" and select "run regardless of whether the user logs in or not", so as to avoid that the program is not executed due to different users.

Go to "conditions" to modify the power configuration. It is recommended to cancel the restriction. If it is a laptop, check the box in the red box, and the script will not be executed without connecting the power supply.

So far, the work has been completed. Readers can modify the corresponding content according to their own needs. If there are any errors in the article or other suggestions, please don't hesitate to comment.
The complete code of the full text is as follows:

from urllib import request, parse
import json
import emoji

# Send content today date and week
import datetime
import calendar
import time
sysdate = datetime.date.today()  # Get date only
now_time = datetime.datetime.now()  # Get date plus time
week_day = sysdate.isoweekday()  # Get day of week
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
text_date = 'Now it is' + str(now_time)[0:16] + ',' + week[week_day -1 ]

# Gets the last day of the current month
next_month = sysdate.replace(day=28) + datetime.timedelta(days=4)  # Get to next month
minus = datetime.timedelta(days=next_month.day)  # Get next_ Days of month
salary_date=next_month - minus  # next_month minus its own days, you can get the last day of the month at the end of the month

# Judging the actual pay date, only weekends are considered, and holidays are not considered
if salary_date.isoweekday() == 6:
    salary_date_actual = salary_date - datetime.timedelta(days=1)  # If the salary is paid on Saturday, it will be paid on Friday, one day in advance
elif salary_date.isoweekday() == 7:
    salary_date_actual = salary_date - datetime.timedelta(days=2)  # If the salary is paid on Sunday, it will be paid on Friday, 2 days in advance
else:
    salary_date_actual=salary_date  # Actual payroll date

# Gets the number of days difference between the current date and the payday
day_between = salary_date_actual.day - sysdate.day
if day_between == 0:
    text_salary = 'Pay today!go for it!!!'
elif day_between < 0 or day_between > 20:
    text_salary = 'Please treat the newly paid salary better' + emoji.emojize(':wink:', use_aliases=True)
else:
    text_salary = 'It's still a long way from salary' + str(day_between) + 'day'

#Sending content: weather conditions
import requests
from bs4 import BeautifulSoup
import datetime

url = 'http://www.weather.com.cn/weather/101010300.shtml'
sysdate=datetime.date.today()
r = requests.get(url, timeout=30)  # Grab web page information with requests
r.raise_for_status()  # You can stop the program when the program generates an exception
r.encoding = r.apparent_encoding #Coding format
html=r.text

final_list = []
soup = BeautifulSoup(html, 'html.parser')  # use BeautifulSoup Library parsing web page #There are suggestions for the current weather in the soup
body = soup.body #Intercept a part of the body from the soup
data = body.find('div', {'id': '7d'})
ul = data.find('ul')
lis = ul.find_all('li')

for day in lis:
    temp_list = []

    date = day.find('h1').string  # Date found
    if date.string.split('day')[0]==str(sysdate.day):
        temp_list = []

        date = day.find('h1').string  # Date found
        temp_list.append(date)

        info = day.find_all('p')  # Find all p Tags
        temp_list.append(info[0].string)

        if info[1].find('span') is None:  # Find the second value 'span' tag in the p tag - maximum temperature
            temperature_highest = ' '  # Use a to determine whether there is a maximum temperature
        else:
            temperature_highest = info[1].find('span').string
            temperature_highest = temperature_highest.replace('℃', ' ')

        if info[1].find('i') is None:  # Find the second value 'i' tag in the p tag - maximum temperature
            temperature_lowest = ' '  # Use a to determine whether there is a minimum temperature
        else:
            temperature_lowest = info[1].find('i').string
            temperature_lowest = temperature_lowest.replace('℃', ' ')

        temp_list.append(temperature_highest)  # Add maximum temperature to temp_list
        temp_list.append(temperature_lowest)  # Add minimum temperature to temp_list

        final_list.append(temp_list)  # Set temp_ Add list to final_list
        text_weather = 'The weather is' + final_list[0][1] + ',The temperature is' + final_list[0][3].strip() + '~' + final_list[0][2].strip() + 'centigrade'

#Visit meow reminder and send wechat message
class Message(object):
    def __init__(self,text):
        self.text = text
    def push(self):
        # Important, fill in your own bound id in id
        page = request.urlopen("http://miaotixing.com/trigger? "+ parse.urlencode ({" Id ":" fill in meow code here "," text ": self.text," type ":" JSON "}))
        result = page.read()
        jsonObj = json.loads(result)
        if (jsonObj["code"] == 0):
            print("\nReminder message was sent successfully")
        else:
            print("\nReminder message failed to be sent,wrong code: " + str(jsonObj["code"]) + ",describe: " + jsonObj["msg"])

text = f"""
Good morning❤❤❤❤❤❤❤❤
{text_date}
{text_weather}
{text_salary}
"""
message = Message(text)
message.push() # Complete push

This concludes the full text.

Topics: Python Windows crawler