In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
In this issue, the editor will bring you about how to use Serverless to achieve intelligent life. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
Through the timing trigger, a WeCom robot can be easily and quickly customized. We can use it to achieve small functions such as drinking water and eating reminders, as well as the small functions of regularly pushing news, weather, and even monitoring alarms.
Use WeCom robot
In WeCom, choose to add a robot:
After that, we can customize the basic functions of WeCom robot according to the documentation:
The following is an example of using the curl tool to push a text message to a group (note that to replace url with the robot's webhook address, content must be utf8 encoded):
Curl 'WeCom robot address'-H 'Content-Type: application/json'-d' {"msgtype": "text", "text": {"content": "hello world"}}'
Through the Python language:
Url = "" data = {"msgtype": "markdown", "markdown": {"content": "hello world",}} data = json.dumps (data) .encode ("utf-8") req_attr = urllib.request.Request (url, data) resp_attr = urllib.request.urlopen (req_attr) return_msg = resp_attr.read (). Decode ("utf-8")
At this point, we can deploy the basic functions of a robot through Serverless Framework and set the API gateway trigger:
The index.py file is as follows:
Import osimport jsonimport urllib.requestdef main_handler (event, context): url = os.environ.get ("url") data = {"msgtype": "markdown", "markdown": {"content": "hello world",}} data = json.dumps (data) .encode ("utf-8") req_attr = urllib.request.Request (url Data) resp_attr = urllib.request.urlopen (req_attr) return resp_attr.read () .decode ("utf-8")
The serverless.yaml file is as follows:
MyRobot_Base: component:'@ serverless/tencent-scf' inputs: name: MyRobot_Base runtime: Python3.6 timeout: 3 codeUri:. / base_robot description: robot push interface region: ap-guangzhou environment: variables: url: webhook address handler: index.main_handler memorySize: 64 tags: app: myrobot events:-apigw: name: MyRobot Parameters: protocols:-http-https description: robot push interface environment: release endpoints:-path: / push method: ANY
After the deployment is successful, you can see the address output on the command line:
Open it in the browser and you can see that WeCom's robot has been triggered:
This is a simple hello world function. Next, the fun begins!
We further modify this basic function:
Import osimport jsonimport urllib.requestdef main_handler (event, context): url = os.environ.get ("url") data = {"msgtype": "markdown", "markdown": {"content": event ['body'],}} data = json.dumps (data) .encode ("utf-8") req_attr = urllib.request.Request (url) Data) resp_attr = urllib.request.urlopen (req_attr) return resp_attr.read () .decode ("utf-8")
By changing the content field in data to event ['body'], you can allow other modules to request this API to achieve robot push function. Of course, this basic function can also be improved, not only in markdown format, but also in more supported formats:
Robot function extension reminder function of drinking water / eating
This function can be realized through timing triggers and accessing cloud functions.
For example, index.py code:
Import osimport jsonimport urllib.requestdef main_handler (event, context): url = os.environ.get ("url") data = "drink plenty of water every day, don't forget to replenish it" .encode ("utf-8") req_attr = urllib.request.Request (url, data) resp_attr = urllib.request.urlopen (req_attr) return resp_attr.read (). Decode ("utf-8")
Serverless.yaml file:
MyRobot_Water: component:'@ serverless/tencent-scf' inputs: name: MyRobot_Water runtime: Python3.6 timeout: 3 codeUri:. / water description: remind the drinking robot region: ap-guangzhou environment: variables: url: https://service-lf3ug84s-1256773370.gz.apigw.tencentcs.com/release/push handler: index.main_handler memorySize: 64 tags: app: myrobot events :-timer: name: timer parameters: cronExpression:'0 * / 309-17 * 'enable: true
This function is to remind you to drink water every 30 minutes from 9 a.m. to 5 p.m.
Weather forecast / local news function
To achieve the function of weather forecast / news broadcast, we can implement it through the existing news APIs. Take Tencent Cloud's cloud market as an example, look for a news API interface:
According to the API document, you can see that the request address is: https://service-aqvnjmiq-1257101137.gz.apigw.tencentcs.com/release/news/search
The Get method can take one parameter: keyword, as the target keyword, write code:
Import ssl, hmac, base64, hashlib, os, jsonfrom datetime import datetime as pydatetimefrom urllib.parse import urlencodefrom urllib.request import Request, urlopendef main_handler (event, context): source = "market" datetime = pydatetime.utcnow () .strftime ('a,% d% b% Y% H:%M:%S GMT') signStr = "x-date:% snx-source:% s"% (datetime Source) sign = base64.b64encode (hmac.new (os.environ.get ('secretKey'). Encode (' utf-8'), signStr.encode ('utf-8'), hashlib.sha1). Digest () auth =' hmac id= "% s", algorithm= "hmac-sha1", headers= "x-date x-source", signature= "% s"'% (os.environ.get ("secretId"), sign.decode ('utf-8') headers= {' Xrel Sourcekeeper: source QueryParams = {'keyword':' Science News'} url = 'https://service-aqvnjmiq-1257101137.gz.apigw.tencentcs.com/release/news/search' if len (queryParams.keys ()) > 0: url = url +'? + urlencode (queryParams) content = "" for eve in json.loads (urlopen (url)) Headers=headers) .read () .decode ("utf-8") ["result"] ["list"] [0:5]: content = content + "* [% s] (% s) n"% (eve ['title'], eve [' url']) if content: urlopen (os.environ.get ('url'), content.encode ("utf-8"))
Serverless.yaml file:
MyRobot_News: component:'@ serverless/tencent-scf' inputs: name: MyRobot_News runtime: Python3.6 timeout: 3 codeUri:. / news description: news push region: ap-guangzhou environment: variables: url: https://service-lf3ug84s-1256773370.gz.apigw.tencentcs.com/release/push secretId: cloud market key information secretKey: cloud market key information Handler: index.main_handler memorySize: 64 tags: app: myrobot events:-timer: name: timer parameters: cronExpression:'00 * / 8 * 'enable: true
The operation effect is as follows: push the science and technology news of the day for us at 8 o'clock every morning:
Monitoring and alarm function
We can also give WeCom robot the ability to monitor alarms:
Index.py file:
Import osimport urllib.requestdef getStatusCode (url): return urllib.request.urlopen (url). Getcode () def main_handler (event, context): url = "http://www.anycodes.cn" if getStatusCode (url) = = 200: print (" your website% s is accessible! " % (url)) else: urllib.request.urlopen (urllib.request.Request (os.environ.get ('url'), ("your website% s is not accessible!" % (url)) .encode ("utf-8")) return None
Serverless.yaml file:
MyRobot_Monitor: component:'@ serverless/tencent-scf' inputs: name: MyRobot_Monitor runtime: Python3.6 timeout: 3 codeUri:. / monitor description: website Monitoring region: ap-guangzhou environment: variables: url: https://service-lf3ug84s-1256773370.gz.apigw.tencentcs.com/release/push handler: index.main_handler memorySize: 64 tags: app: myrobot events: -timer: name: timer parameters: cronExpression:'0 * / 30 * 'enable: true
After the deployment is complete, the monitoring script for the site has been started, checking the availability of the site every 30 minutes. If it is not available, an alert is sent:
Train of thought divergence
WeCom robot can be given more and more interesting functions through the Serverless architecture, so what other products can be combined with the Serverless architecture to become more interesting?
With the continuous development of network technology, IoT technology has gradually entered thousands of households, whether it is floor-sweeping robots, intelligent curtains and other intelligent home, or intelligent speakers and other entertainment facilities, IoT technology has become visible.
Xiao Ai can also quickly develop special new functions through the Serverless architecture.
First of all, let's go to Xiao Ai's open platform to register an account and submit authentication:
Then the customization function of Xiao Ai is studied. As shown in the figure, in the development document, we can see the capability information provided by Xiao Ai developer platform, as well as the details of request and response:
Continue with the project design. The goal of this article is to provide users with the title and brief introduction of the latest popular articles in Tencent Cloud + community by saying keywords such as "enter Cloud + Community" to Xiao Ai.
The whole process is shown in the figure:
The function code is written:
#-*-coding: utf8-*-import jsonimport loggingimport urllib.requestimport urllib.parselogging.basicConfig (level=logging.NOTSET) def main_handler (event, context): host = "https://cloud.tencent.com/" path =" developer/services/ajax/column/article?action=FetchColumnHomeArticleList "json_data = {" action ":" FetchColumnHomeArticleList "," payload ": {" pageNumber ": 1," pageSize ": 20 "version": 1} data= json.dumps (json_data) .encode ("utf-8") request_attr = urllib.request.Request (url=host + path, data=data) response_attr = urllib.request.urlopen (request_attr). Read (). Decode ("utf-8") json_resp = json.loads (response_attr) logging.debug (json_resp) temp_str = "the title is% s" The main content is% s "list_data = json_resp [" data "] [" list "] [0:5] art_list = [temp_str% (eve [" title "] Eve ["abstract"]) for eve in list_data] news_str = 'today's popular articles in Tencent Cloud plus community are as follows:% swarming'% ("," .join (art_list)) logging.debug (news_str) xiaoai_response = {"version": "1.0"," response ": {" open_mic ": False "to_speak": {"type": 0, "text": news_str}} "is_session_end": False} return xiaoai_response
After the deployment using Serverless Framework, bind the API gateway trigger, and you can see the test result through the request address:
As you can see, we have obtained the target data. At this point, we create a skill development on Xiao Ai's official website. After filling in and saving the basic information, select the configuration service and enter the testing address in HTTPS:
After the configuration is complete, start the test, as shown in the following figure. You can see that when we enter the predetermined command "Open Yunjia Community", the system will correctly retrieve the result information and return it to us:
We have successfully developed a new feature for "Xiao Ai" through the Serverless architecture, and we can also release and launch this new feature!
The above is the editor for you to share how to use Serverless to achieve intelligent life, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.