uniCloud基础练习---使用云开发每天定时向女朋友发送短信

代码哈士奇
• 阅读 1119

上次我们使用云函数定时向女朋友推送邮件 使用云函数每天定时向女朋友发送邮件推送天气

代码已放置github https://github.com/dmhsq/uniCloud-demo 开发工具 Hbuilder X 使用uni-app uniCloud 云开发 如果你对Hbuilder X uni-app uniCloud 云开发不是很熟悉可以先看这几篇文章 云开发系列

这次我们使用短信,每天早上六点向女朋友发送天气和情话短信 晚上十点 发送晚安短信 爱她 就每天早上六点告诉他今天的天气,再来句情话或者小故事 当然你也可以定时晚上发送 睡前小故事

参考文档 https://uniapp.dcloud.io/uniCloud/README

这是测试的短信 uniCloud基础练习---使用云开发每天定时向女朋友发送短信

短信服务

进入 Dcloud 开发者中心 https://dev.dcloud.net.cn/ 如果没有账号 注册即可

开通短信服务

uniCloud基础练习---使用云开发每天定时向女朋友发送短信 开通 后可以充值一块钱当作测试

添加签名

uniCloud基础练习---使用云开发每天定时向女朋友发送短信根据要求填写即可 我这里只用云函数 且只用于给女朋友推送短信 等待审核完成即可 同时可以去配置模板

添加模板

uniCloud基础练习---使用云开发每天定时向女朋友发送短信 我是这样填写的 uniCloud基础练习---使用云开发每天定时向女朋友发送短信

注意这里的 weekday weather story 你可以自己定义 比如 name 等等 等会要用到 等待审核完成即可

创建项目

uniCloud基础练习---使用云开发每天定时向女朋友发送短信 uniCloud基础练习---使用云开发每天定时向女朋友发送短信)uniCloud基础练习---使用云开发每天定时向女朋友发送短信 右键点击uniCloud关联服务空间 如果没有 请登陆控制台https://unicloud.dcloud.net.cn 新建一个服务空间 uniCloud基础练习---使用云开发每天定时向女朋友发送短信选择腾讯云的免费版本即可

绑定服务空间后 创建cloudfunctions目录 右键点击cloudfunctions目录 选择创建云函数 我们下面的代码除了页面代码都写在云函数里面

uniCloud基础练习---使用云开发每天定时向女朋友发送短信

发送短信

发送代码

文档地址 https://uniapp.dcloud.io/uniCloud/send-sms

smsKey和 smsSecret 在基础配置里 templateId是模板id审核过了会有 data

try {
    const res = await uniCloud.sendSms({
      smsKey: '****************',
      smsSecret: '****************',
      phone: '***********',
      templateId: '模板id',
      data: {
        weekday: 'DCloud',
        weather: '123456',
        story: '注册'
      }
    })
    // 调用成功,请注意这时不代表发送成功
    return res
  } catch(err) {
    // 调用失败
    console.log(err.errCode)
    console.log(err.errMsg)
    return {
      code: err.errCode,
      msg: err.errMsg
    }
  }

情话获取

可以使用云数据库 自己添加 uniCloud基础练习---使用云开发每天定时向女朋友发送短信

也可以从网上获取 土味情话 比如 这个api http://shiyan666.cn/api/twqh.php

function getQH(city) {
    let res = uniCloud.httpclient.request('http://shiyan666.cn/api/twqh.php')
    return new Promise(function(resolve) {
        res.then(ress => {
            let arrayBuffer = ress.res.data
            let unit8Arr = new Uint8Array(arrayBuffer)
            let encodedString = String.fromCharCode.apply(null, unit8Arr)
            let decodedString = decodeURIComponent(escape(encodedString))
            let data = JSON.parse(JSON.stringify(decodedString))
            resolve(data)
        })
    })
}

如果是从数据库获取 就获取后根据当天为周几 就返回xid为几的情话 数据库可以存放经过自己筛选的 可以一次放一个月的 或者七天的 当情话发过一遍后 给自己的手机发短信提醒 情话已经用过一遍

当然如果你有时间 还可以自定义 写个小后台 向数据库存入数据 云函数读取后 第二天发送 发送完自动删除 如果数据库没存 就默认调用情话数据库/网上获取

天气获取

appid和appsecret的获取 参考网站 https://tianqiapi.com/

function getTQ(city) {
    let res = uniCloud.httpclient.request("https://tianqiapi.com/api?version=v6&appidxxxx&appsecret=sxxx&city=" +
        city)
    return new Promise(function(resolve) {
        res.then(ress => {
            let arrayBuffer = ress.res.data
            let unit8Arr = new Uint8Array(arrayBuffer)
            let encodedString = String.fromCharCode.apply(null, unit8Arr)
            let decodedString = decodeURIComponent(escape(encodedString))
            let data = JSON.parse(decodedString)
            resolve(data)
        })
    })
}

嵌入数据

let datas = await getTQ('城市名 不要加县市 比如天津');
let qh = await getQH();

这是我的发送短信的data

data: {
    weekday: datas.week + ',亲爱的',
    weather: `当前温度${datas.tem}℃,最高温度${datas.tem1}℃,最低温度${datas.tem2}℃,出行建议:${datas.air_tips}\n`,
    story: '土味情话:' + qh
}

api获取情话发送短信完整代码

'use strict';

function getTQ(city) {
    let res = uniCloud.httpclient.request("https://tianqiapi.com/api?version=v6&appid=xxxx&appsecret=xxxx&city=" +
        city)
    return new Promise(function(resolve) {
        res.then(ress => {
            let arrayBuffer = ress.res.data
            let unit8Arr = new Uint8Array(arrayBuffer)
            let encodedString = String.fromCharCode.apply(null, unit8Arr)
            let decodedString = decodeURIComponent(escape(encodedString))
            let data = JSON.parse(decodedString)
            resolve(data)
        })
    })
}

function getQH(city) {
    let res = uniCloud.httpclient.request('http://shiyan666.cn/api/twqh.php')
    return new Promise(function(resolve) {
        res.then(ress => {
            let arrayBuffer = ress.res.data
            let unit8Arr = new Uint8Array(arrayBuffer)
            let encodedString = String.fromCharCode.apply(null, unit8Arr)
            let decodedString = decodeURIComponent(escape(encodedString))
            let data = JSON.parse(JSON.stringify(decodedString))
            resolve(data)
        })
    })
}
exports.main = async (event, context) => {
    let datas = await getTQ('xxxx');
    let qh = await getQH();
    try {
        const res = await uniCloud.sendSms({
            smsKey: 'fee5c97e6aeaaae9d0d8923e62229797',
            smsSecret: 'xxxxxxx',
            phone: 'xxxxxxx',
            templateId: 'xxxxx',
            data: {
                weekday: datas.week + ',亲爱的',
                weather: `当前温度${datas.tem}℃,最高温度${datas.tem1}℃,最低温度${datas.tem2}℃,出行建议:${datas.air_tips}\n`,
                story: ':土味情话:' + qh
            }
        })
        // 调用成功,请注意这时不代表发送成功
        return "成功"
    } catch (err) {
        // 调用失败
        console.log(err.errCode)
        console.log(err.errMsg)
        return {
            code: err.errCode,
            msg: err.errMsg
        }
    }
};

如果情话来源为数据库

根据周几查询情话

这里我的云数据库 uniCloud基础练习---使用云开发每天定时向女朋友发送短信 查询代码

const dbs = uniCloud.database();
    let db = dbs.collection('story')
    let now = new Date();
    let day = now.getDay();
    let res = await db.where({xid: day}).get()
    console.log(res.data[0].story)

情话用完警告

比如今天是周三 那么情话是周四早上6点发第一个 下周四发完 所以我们新建一个数据表 uniCloud基础练习---使用云开发每天定时向女朋友发送短信 只需要一个数据 uniCloud基础练习---使用云开发每天定时向女朋友发送短信这里的_id拿到

每次发送后都会获取下tx 如果不是7就加1 如果为7说明用完 将tx重置为0防止你忘了设置新的 从第一条开始发送 并且向你发送告警短信

tx为你本次修改数据库发送的天数 从0~7 为7时置0并发送警告消息 数据库使用 参考文档 https://uniapp.dcloud.io/uniCloud/cf-database?id=%e6%b7%bb%e5%8a%a0%e6%9f%a5%e8%af%a2%e6%9d%a1%e4%bb%b6

    const dbs = uniCloud.database();
    let db = dbs.collection('story')
    let now = new Date();
    let day = now.getDay();
    let qh = await db.where({xid: day}).get()
    let dbtx = dbs.collection('tx')
    let res = await dbtx.get()
    let tx = res.data[0].tx
    if(tx==7){
        tx = 0;
        let updb = await dbtx.doc('b00064a7602d226805806e0e2eb8b529').update({
          tx: tx
        });
        try {
            const res = await uniCloud.sendSms({
                smsKey: 'xxxxxxxx',
                smsSecret: 'xxxxxxxxxx',
                phone: 'yourphone',
                templateId: 'xxxxx',
                data: {
                    weekday: '用完啦',
                    weather: '用完啦',
                    story: '用完啦'
                }
            })
            // 调用成功,请注意这时不代表发送成功
            return "成功"
        } catch (err) {
            // 调用失败
            console.log(err.errCode)
            console.log(err.errMsg)
            return {
                code: err.errCode,
                msg: err.errMsg
            }
        }
    }
    else{
        tx = tx+1;
        let updb = await dbtx.doc('b00064a7602d226805806e0e2eb8b529').update({
          tx: tx
        });
    }

数据库获取情话发送短信完整代码

'use strict';
function getTQ(city) {
    let res = uniCloud.httpclient.request("https://tianqiapi.com/api?version=v6&appid=xxxx&appsecret=xxxxx&city=" +
        city)
    return new Promise(function(resolve) {
        res.then(ress => {
            let arrayBuffer = ress.res.data
            let unit8Arr = new Uint8Array(arrayBuffer)
            let encodedString = String.fromCharCode.apply(null, unit8Arr)
            let decodedString = decodeURIComponent(escape(encodedString))
            let data = JSON.parse(decodedString)
            resolve(data)
        })
    })
}
exports.main = async (event, context) => {
    //event为客户端上传的参数
    const dbs = uniCloud.database();
    let db = dbs.collection('story')
    let now = new Date();
    let day = now.getDay();
    let qha = await db.where({xid: day}).get()
    let qh = qha.data[0].story
    let datas = await getTQ('xxx')
    try {
        const res = await uniCloud.sendSms({
            smsKey: 'xxxxx',
            smsSecret: 'xxxxx',
            phone: 'xxxxx',
            templateId: 'xxxx',
            data: {
                weekday: datas.week + ',亲爱的',
                weather: `当前温度${datas.tem}℃,最高温度${datas.tem1}℃,最低温度${datas.tem2}℃,出行建议:${datas.air_tips}\n`,
                story: ':土味情话:' + qh
            }
        })
        let dbtx = dbs.collection('tx')
        let res = await dbtx.get()
        let tx = res.data[0].tx
        let id = res.data[0]._id
        if(tx==7){
            tx = 0;
            let ipdb = await dbtx.doc(id).update({
              tx: tx
            });
            try {
                const res = await uniCloud.sendSms({
                    smsKey: 'xxxxxxxx',
                    smsSecret: 'xxxxxxxxxx',
                    phone: 'yourphone',
                    templateId: 'xxxxx',
                    data: {
                        weekday: '用完啦',
                        weather: '用完啦',
                        story: '用完啦'
                    }
                })
                // 调用成功,请注意这时不代表发送成功
                return "成功"
            } catch (err) {
                // 调用失败
                console.log(err.errCode)
                console.log(err.errMsg)
                return {
                    code: err.errCode,
                    msg: err.errMsg
                }
            }
        }
        else{
            tx = tx+1;
            let ipdb = await dbtx.doc(id).update({
              tx: tx
            });
        }

    } catch (err) {
        // 调用失败
        console.log(err.errCode)
        console.log(err.errMsg)
        return {
            code: err.errCode,
            msg: err.errMsg
        }
    }

};

编写页面自定义修改情话(以七条为例一周嘛)

以上面那个数据库为例子

效果

uniCloud基础练习---使用云开发每天定时向女朋友发送短信

云函数

uniCloud基础练习---使用云开发每天定时向女朋友发送短信

'use strict';
exports.main = async (event, context) => {
    //event为客户端上传的参数
    let type = event.type
    const dbs = uniCloud.database();
    let db = dbs.collection('story')
    if(type==1){
        let res = await db.get()
        return res
    }else if(type==2){
        let qh = await db.where({xid: event.xid}).get()
        let id = qh.data[0]._id
        let updb = await db.doc(id).update({
          story: event.story
        });
        return updb
    }else{
        return "error"
    }
};

页面代码

<template>
    <view class="content">
        <view v-for="item in tableList" style="border: #DD524D solid 1px;">
            <view class="text-area">{{item.xid}}</view>
            <textarea v-model="item.story"></textarea>
            <button type="primary" @click="upstory(item.xid,item.story)">修改</button>
        </view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                tableList: [],
                butable: []
            }
        },
        onLoad() {
            this.getDB();
        },
        methods: {
            getDB() {
                let vm = this;
                uniCloud.callFunction({
                    name: 'getdbs',
                    data: {
                        type: 1
                    },
                    success: function(res) {
                        console.log(res.result.data)
                        vm.tableList = res.result.data
                        vm.butable = JSON.parse(JSON.stringify(vm.tableList))
                    }
                })
            },
            upstory(xid, story) {
                let vm = this;
                if(this.butable[xid-1].story==story){
                    uni.showToast({
                        icon: 'none',
                        title: '没有任何变化'
                    })
                    return 
                }
                uniCloud.callFunction({
                    name: 'getdbs',
                    data: {
                        type: 2,
                        xid: xid,
                        story: story
                    },
                    success: function(res) {
                        if (res.result.updated == 0) {
                            uni.showToast({
                                icon: 'none',
                                title: '更新失败'
                            })
                        }
                        if(res.result.updated == 1) {
                            uni.showToast({
                                icon: 'none',
                                title: '更新成功'
                            })
                            vm.butable = JSON.parse(JSON.stringify(vm.tableList))
                        }
                    }
                })
            }
        }
    }
</script>

<style>
    .content {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .text-area {
        display: flex;
        justify-content: center;
    }
</style>

uniCloud基础练习---使用云开发每天定时向女朋友发送短信

这样就可以自定义情话了哈哈 然后短信会发送以这个数据库里面的情话

自定义情话发送代码

代码和数据库的一样 因为本身就是修改数据库的情话

定时每天早上六点发送

当你开发完云函数(右键点击云函数选择上传部署) 后上传部署 打开控制台 https://unicloud.dcloud.net.cn 找到部署的云函数 uniCloud基础练习---使用云开发每天定时向女朋友发送短信点击详情 找到定时器触发 编辑 uniCloud基础练习---使用云开发每天定时向女朋友发送短信输入以下代码 即可定时早上六点发送

[
  {
    "name": "myTrigger",
    "type": "timer",
    "config": "0 0 6 * * * *"
  }
]

晚安短信

当然你也可以发送晚安短信 代码大差不差

uniCloud基础练习---使用云开发每天定时向女朋友发送短信

代码

'use strict';

function getTQ(city) {
    let res = uniCloud.httpclient.request("https://tianqiapi.com/api?version=v6&appid=xxxxx&appsecret=xxxx&city=" +
        city)
    return new Promise(function(resolve) {
        res.then(ress => {
            let arrayBuffer = ress.res.data
            let unit8Arr = new Uint8Array(arrayBuffer)
            let encodedString = String.fromCharCode.apply(null, unit8Arr)
            let decodedString = decodeURIComponent(escape(encodedString))
            let data = JSON.parse(decodedString)
            resolve(data)
        })
    })
}

exports.main = async (event, context) => {
    let datas = await getTQ('xxxx');
    try {
        const res = await uniCloud.sendSms({
            smsKey: 'xxxxxxx',
            smsSecret: 'xxxxxx',
            phone: 'xxxxxx',
            templateId: 'xxxxx',
            data: {
                weekday: datas.week + ',晚安亲爱的\n',
                weather: `当前温度${datas.tem}℃,最高温度${datas.tem1}℃,最低温度${datas.tem2}℃,注意增减衣物哦\n`,
                story: ':晚安老婆之我爱你'
            }
        })
        // 调用成功,请注意这时不代表发送成功
        return "成功"
    } catch (err) {
        // 调用失败
        console.log(err.errCode)
        console.log(err.errMsg)
        return {
            code: err.errCode,
            msg: err.errMsg
        }
    }
};

定时每天晚上十点发送

[
  {
    "name": "myTrigger",
    "type": "timer",
    "config": "0 0 22 * * * *"
  }
]

爱她 就每天早上六点告诉他今天的天气,再来句情话或者小故事 当然你也可以定时晚上发送 睡前小故事

大学之道亦在自身,努力学习,热血青春 如果对编程感兴趣可以加入我们的qq群一起交流:535620886 974178910

有问题可以下方留言,看到了会回复哦

点赞
收藏
评论区
推荐文章

暂无数据