利用腾讯云云函数自动提交表单

利用腾讯云云函数自动提交表单

前情提要:利用python urllib3自动提交表单 (基于Q学校的学工系统 健康信息提交)

上回说到用python写了个自动提交今日健康信息的脚本,苦于没有服务器托管仍然是手动执行。无意中听说腾讯云函数能免费实现定期执行脚本,遂尝试一下,果然好用!

0x04 适配为腾讯云函数识别的执行方法

利用python urllib3自动提交表单 (基于Q学校的学工系统 健康信息提交)的基础上又增加了邮件通知

import urllib3
import json
import platform
import smtplib
import datetime
from email.mime.text import MIMEText
from email.header import Header

######################################
#            仅使用QQ邮箱             #
#  此处更改邮箱账号密码(不加@qq.com)   #
#         密码使用SMTP的授权码        #
######################################

mail_user = "username"
mail_pass = "smtp_password"

mailText = ""


def sendText(string):
    global mailText
    mailText += string + "\n"
    print(string)


def checkRequest(urllib3Request):  # 检查request请求
    global mailText

    sendText("HTTP " + str(urllib3Request.status))
    if urllib3Request.status == 200:
        return True
    else:
        return False


def makeDiction(urllib3Request):  # 将返回的request整理为字典
    urllib3RequesDict = urllib3Request.data.decode(encoding="utf-8")
    return json.loads(urllib3RequesDict)


def getCookies(urllib3Pool, postBody):
    # 获取登录cookies
    sendText("STEP 1: Getting login cookies...")
    try:
        login_req = urllib3Pool.request(
            "POST",
            "http://xuegon********du.cn:8080/authentication/login",
            headers={
                "user-agent": "Dart/2.10 (dart:io)",
                "content-type": "application/json",
                "accept-encoding": "gzip",
                "content-length": str(len(postBody)),
                "host": "xuegon********du.cn:8080"
            },
            body=postBody
        )
    except:
        sendText("ERROR at getCookies.")
        return False
    if checkRequest(login_req):
        cookies = makeDiction(login_req)["data"]  # 读取得到的cookies
        sendText("Login cookies:" + cookies)
        return cookies
    sendText("ERROR: Get cookies failed.")
    return False


def tryLogin(urllib3Pool, postCookies):
    # 尝试模拟登录
    sendText("\nSTEP 2: Trying to log in...")
    try:
        req = urllib3Pool.request(
            "POST",
            "http://xuegon********du.cn:8080/info/current",
            headers={
                "user-agent": "Dart/2.10 (dart:io)",
                "cookie": "syt.sessionId="+postCookies,
                "accept-encoding": "gzip",
                "content-length": "0",
                "authorization": postCookies,
                "host": "xuegon********du.cn:8080"
            }
        )
    except:
        sendText("ERROR at tryLogin.")
        return False
    if checkRequest(req):
        username = makeDiction(req)["data"]["name"]  # 输出登录信息(姓名)
        sendText("Login username:" + username)
        return True
    sendText("ERROR: Login failed, using cookies:" + postCookies)
    return False


def requestHealth(urllib3Pool, postCookies, postBody):
    # 提交健康信息
    sendText("\nSTEP 3: Submitting health information...")
    try:
        health_req = urllib3Pool.request(
            "POST",
            "http://xuegon********du.cn:8080/student/healthInfo/save",
            headers={
                "user-agent": "Dart/2.10 (dart:io)",
                "content-type": "application/json",
                "cookie": "syt.sessionId=" + postCookies,
                "accept-encoding": "gzip",
                "content-length": str(len(postBody)),
                "host": "xuegon********du.cn:8080"
            },
            body=postBody
        )
    except:
        sendText("ERROR at requestHealth.")
        return False
    state = checkRequest(health_req)
    message = makeDiction(health_req)["message"]
    sendText("message:" + message)
    if message == "请在上午20:00前提交!" or message == "每日最多提交5次!" or state:
        return True
    return False


def sendMail(mailText, state):
    global mail_user, mail_pass

    todayTime = datetime.date.today()

    # 第三方 SMTP 服务
    mail_host = "smtp.qq.com"  # 设置服务器

    sender = mail_user+'@qq.com'
    receivers = [mail_user+'@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

    message = MIMEText("以下为今日的健康信息:\n" + mailText, 'plain', 'utf-8')
    message['From'] = Header(mail_user+'@qq.com', 'utf-8')
    message['To'] = Header(mail_user+'@qq.com', 'utf-8')

    subject = str(todayTime) + " autohealth 提交报告:" + state
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print("Mail send successful.")
    except smtplib.SMTPException:
        print("Error: Cannot send mail.")


def main_handler(event, context):
    global mailText
    http = urllib3.PoolManager()
    try:
        if platform.architecture()[1] == "WindowsPE":
            # 登录信息
            with open(r".\userdata.json", "rb") as file:
                userdata = file.read()
                file.close()
            # 读取今日健康信息
            with open(r".\healthinfo.json", "rb") as file:
                healthdata = file.read()
                file.close()
        else:
            with open(r"./userdata.json", "rb") as file:
                userdata = file.read()
                file.close()
            with open(r"./healthinfo.json", "rb") as file:
                healthdata = file.read()
                file.close()
    except:
        sendText("file open aborted.")
        return

    cookies = getCookies(urllib3Pool=http, postBody=userdata)
    state = False
    if cookies:
        if tryLogin(urllib3Pool=http, postCookies=cookies):
            state = requestHealth(
                urllib3Pool=http, postCookies=cookies, postBody=healthdata)
    if state:
        state = "成功"
    else:
        state = "失败"
    sendMail(mailText, state)

先开通QQ邮箱的SMTP服务。

0x05 开通QQ邮箱的SMTP服务

那么现在部署到腾讯云的云函数服务上。

0x06部署到腾讯云 云函数

上传项目(一共三个文件)


执行结果:

创建一个触发器让其每天7:15提交

完结撒花,可以摸鱼了

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值