从0上线一个简单提醒功能的企业微信机器人bot(python3.6+腾讯云部署+cron触发)

1、右键群,点击添加机器人

640?wx_fmt=png

2、查看机器人资料,可以看到一个Webhook地址,这个地址之后有大用处

3、前往腾讯云,注册好账号,然后进入serverless服务中,地址:

https://console.cloud.tencent.com/scf/list-detail?rid=1&ns=default&id=helloworld-1625125268&menu=trigger&tab=codeTab

 新建一个函数,模板选择自定义创建

函数代码中复制如下代码:

# -*- coding: utf8 -*-
import logging
import datetime
import time
import requests
import json
import pytz



robot_url = "https://qyapi.weixin.qq。。。。。。。。。。。。。。。。。。。"
# 向机器人推送消息,默认是 text(机器人支持 markdown)
metioned_userid = ["xxxxx"] 
def post_to_robot(req: str, url=robot_url, msgtypePara="text"):
    logging.info("Post to robot", req)
    dictPush = {"msgtype": msgtypePara, msgtypePara: {"content": req}
    ,"text": { "content": "已经"+str(GetNowTimeHumanable())[0:19]+"了,头哥该上班啦!!!"
    ,"mentioned_list":metioned_userid}
    }
    response = requests.post(
        url=url,
        headers={'Content-Type': 'application/json'},
        data=json.dumps(dictPush), timeout=5
        )
    logging.info("PostToRobot:%s , %s", response, response.text)

def main_handler(event="", context=""):
    ' event context 是云函数要用的,里面没用到'
    
    # 初始化日志
    LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
    logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
    logging.info("Runing")
    
    time = str(GetNowTimeHumanable())
    ans = ""
    logging.info("ans: %s",ans)
    post_to_robot(ans)



# 时间函数

def changeTimeToTimeZone(timeUnix: int, timeZone="Asia/Shanghai"):
    "转换当前时间戳到 UTC + 8"
    timeUnix = datetime.datetime.utcfromtimestamp(timeUnix)
    timeUnix = timeUnix.replace(tzinfo=pytz.timezone('UTC'))
    return timeUnix.astimezone(pytz.timezone(timeZone))


def GetNowTimeHumanable():
    # 获取当前时间
    dt = datetime.datetime.now(datetime.timezone.utc)
    ans = int(dt.timestamp())
    logging.debug("GetNowIntegralMinute(Humanable): %s",
                  changeTimeToTimeZone(ans))
    return changeTimeToTimeZone(ans)

if __name__ == "__main__":
    main_handler()

其中红色部分为你的机器人webhook地址,mentioned_userid为你要@的人的userid,"text"是你想要让机器人说的话,str(GetNowTimeHumanable())[0:19]函数为获取当前时间字符穿的前19位,这三个部分均可以自行修改。

 点击部署后,进入触发管理

 

选择自定义触发周期,cron表达式规则,点击cron相关文档即可查看,我这里采用

0 0 8 * * 1-5 *

实现的功能为,每周1到周5的早上8点整进行消息推送,这个触发周期表达式你可以根据自己的需求进行修改。

 定义好触发周期,提交后即可,一个函数可以定义多个触发器,同样,一个机器人的webhook可以应用到多个函数中,最终实现效果如下:

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值