- 來源 | 願碼(ChainDesk.CN)內容編輯
- 願碼Slogan | 鏈接每一個程序員的故事
- 網站 | http://chaindesk.cn
- 願碼願景 | 打造全學科IT系統免費課程,助力小白用戶、初級工程師0成本免費系統學習、低成本進階,幫助BAT一線資深工程師成長並利用自身優點創造睡後收入。
- 官方公衆號 | 願碼 | 願碼服務號 | 區塊鏈部落
- 免費加入願碼全思惟工程師社羣 | 任一公衆號回覆「願碼」兩個字獲取入羣二維碼
本文閱讀時長:11minpython
在本文中,咱們將瞭解如何利用聊天機器人來協助網絡操做。隨着咱們向智能化運營邁進,另外一個須要關注的領域是移動性。有一個腳本能夠執行配置,修復甚至故障排除,但它仍然須要存在來監視,啓動甚至執行這些程序或腳本。程序員
諾基亞的MIKA是操做人員能夠用來進行網絡故障排除和修復的聊天機器人的一個很好的例子。根據諾基亞的博客,MIKA根據此單個網絡的實際狀況響應警報優先級信息,並將當前狀況與此網絡及其餘網絡過去事件的整個服務歷史進行比較,以肯定當前網絡的最佳解決方案。json
讓咱們建立一個聊天機器人來協助網絡運營。對於這個用例,咱們將使用普遍使用的聊天應用程序Slack。參考Splunk的智能數據分析功能,咱們會看到一些用戶聊天與聊天機器人的交互,以得到對環境的一些瞭解。後端
當咱們部署了咱們的Web框架時,咱們將利用相同的框架與Slack聊天機器人進行交互,然後者又將與Splunk進行交互。它還能夠直接與網絡設備交互,所以咱們能夠啓動一些複雜的聊天,例如在須要時從Slack重啓路由器。這最終爲工程師提供了移動性,他能夠從任何地方(甚至是手機)處理任務,而沒必要綁定到某個位置或辦公室。api
要建立聊天機器人,如下是基本步驟:網絡
在這裏,關鍵的一步是,一旦咱們輸入接受聊天消息的URL,就須要從Slack驗證特定的URL。驗證涉及API端點將相同的響應做爲從Slack發送到該端點的字符串或JSON發回。若是咱們收到相同的響應,Slack確認端點是可信的並將其標記爲已驗證。這是一次性過程,API URL中的任何更改都將致使重複此步驟。app
如下是Ops API框架中的 Python代碼,它響應此特定查詢:框架
import falcon import json def on_get(self,req,resp): # Handles GET request resp.status=falcon.HTTP_200 # Default status resp.body=json.dumps({"Server is Up!"}) def on_post(self,req,resp): # Handles POST Request print("In post") data=req.bounded_stream.read() try: # Authenticating end point to Slack data=json.loads(data)["challenge"] # Default status resp.status=falcon.HTTP_200 # Send challenge string back as response resp.body=data except: # URL already verified resp.status=falcon.HTTP_200 resp.body=""
這將驗證,若是從Slack發送質詢,它將回復相同的質詢值,確認它是Slack通道發送聊天數據的正確端點。ide
響應特定聊天消息的核心API框架代碼執行如下操做:函數
· 確認發送給Slack的任何帖子都會200在三秒內響應。若是沒有這樣作,Slack報告說: endpoint not reachable。
· 確保從聊天機器人(不是來自任何真實用戶)發送的任何消息再次不做爲回覆發回。這能夠建立一個循環,由於從聊天機器人發送的消息將被視爲Slack聊天中的新消息,而且它將再次發送到URL。這最終會使聊天沒法使用,從而致使聊天中出現重複的消息。
· 使用將被髮送回Slack的令牌對響應進行身份驗證,以確保來自Slack的響應來自通過身份驗證的源。
代碼以下:
import falcon import json import requests import base64 from splunkquery import run from splunk_alexa import alexa from channel import channel_connect,set_data class Bot_BECJ82A3V(): def on_get(self,req,resp): # Handles GET request resp.status=falcon.HTTP_200 # Default status resp.body=json.dumps({"Server is Up!"}) def on_post(self,req,resp): # Handles POST Request print("In post") data=req.bounded_stream.read() try: bot_id=json.loads(data)["event"]["bot_id"] if bot_id=="BECJ82A3V": print("Ignore message from same bot") resp.status=falcon.HTTP_200 resp.body="" return except: print("Life goes on. . .") try: # Authenticating end point to Slack data=json.loads(data)["challenge"] # Default status resp.status=falcon.HTTP_200 # Send challenge string back as response resp.body=data except: # URL already verified resp.status=falcon.HTTP_200 resp.body="" print(data) data=json.loads(data) #Get the channel and data information channel=data["event"]["channel"] text=data["event"]["text"] # Authenticate Agent to access Slack endpoint token="xoxp-xxxxxx" # Set parameters print(type(data)) print(text) set_data(channel,token,resp) # Process request and connect to slack channel channel_connect(text) return # falcon.API instance , callable from gunicorn app= falcon.API() # instantiate helloWorld class Bot3V=Bot_BECJ82A3V() # map URL to helloWorld class app.add_route("/slack",Bot3V)
執行頻道交互響應:此代碼負責在聊天頻道中解釋使用chat-bot執行的特定聊天。此外,這將經過回覆,特定用戶或通道ID以及對Slack API的身份驗證令牌進行響應,這確保了消息或回覆Slack聊天的消息顯示在特定頻道上,從它發起的位置。做爲示例,咱們將使用聊天來加密或解密特定值。
例如,若是咱們寫encrypt username[:]password,它將返回帶有base64值的加密字符串。
相似地,若是咱們寫,聊天機器人將在解密編碼的字符串後返回。decrypt代碼以下:
import json import requests import base64 from splunk_alexa import alexa channl="" token="" resp="" def set_data(Channel,Token,Response): global channl,token,resp channl=Channel token=Token resp=Response def send_data(text): global channl,token,res print(channl) resp = requests.post("https://slack.com/api/chat.postMessage",data='{"channel":"'+channl+'","text":"'+text+'"}',headers={"Content-type": "application/json","Authorization": "Bearer "+token},verify=False) def channel_connect(text): global channl,token,resp try: print(text) arg=text.split(' ') print(str(arg)) path=arg[0].lower() print(path in ["decode","encode"]) if path in ["decode","encode"]: print("deecode api") else: result=alexa(arg,resp) text="" try: for i in result: print(i) print(str(i.values())) for j in i.values(): print(j) text=text+' '+j #print(j) if text=="" or text==None: text="None" send_data(text) return except: text="None" send_data(text) return decode=arg[1] except: print("Please enter a string to decode") text=" argument cannot be empty" send_data(text) return deencode(arg,text) def deencode(arg,text): global channl,token,resp decode=arg[1] if arg[1]=='--help': #print("Sinput") text="encode/decode " send_data(text) return if arg[0].lower()=="encode": encoded=base64.b64encode(str.encode(decode)) if '[:]' in decode: text="Encoded string: "+encoded.decode('utf-8') send_data(text) return else: text="sample string format username[:]password" send_data(text) return try: creds=base64.b64decode(decode) creds=creds.decode("utf-8") except: print("problem while decoding String") text="Error decoding the string. Check your encoded string." send_data(text) return if '[:]' in str(creds): print("[:] substring exists in the decoded base64 credentials") # split based on the first match of "[:]" credentials = str(creds).split('[:]',1) username = str(credentials[0]) password = str(credentials[1]) status = 'success' else: text="encoded string is not in standard format, use username[:]password" send_data(text) print("the encoded base64 is not in standard format username[:]password") username = "Invalid" password = "Invalid" status = 'failed' temp_dict = {} temp_dict['output'] = {'username':username,'password':password} temp_dict['status'] = status temp_dict['identifier'] = "" temp_dict['type'] = "" #result.append(temp_dict) print(temp_dict) text=" "+username+" "+password send_data(text) print(resp.text) print(resp.status_code) return
此代碼查詢Splunk實例以查找與聊天機器人的特定聊天。聊天會要求任何Loopback45當前關閉的管理界面()。另外,在聊天中,用戶能夠詢問管理接口所在的全部路由器up。此英語響應將轉換爲Splunk查詢,並根據Splunk的響應將狀態返回到Slack聊天。
讓咱們看看執行動做來響應結果的代碼,對Slack聊天:
from splunkquery import run def alexa(data,resp): try: string=data.split(' ') except: string=data search=' '.join(string[0:-1]) param=string[-1] print("param"+param) match_dict={0:"routers management interface",1:"routers management loopback"} for no in range(2): print(match_dict[no].split(' ')) print(search.split(' ')) test=list(map(lambda x:x in search.split(' '),match_dict[no].split(' '))) print(test) print(no) if False in test: pass else: if no in [0,1]: if param.lower()=="up": query="search%20index%3D%22main%22%20earliest%3D0%20%7C%20dedup%20interface_name%2Crouter_name%20%7C%20where%20interface_name%3D%22Loopback45%22%20%20and%20interface_status%3D%22up%22%20%7C%20table%20router_name" elif param.lower()=="down": query="search%20index%3D%22main%22%20earliest%3D0%20%7C%20dedup%20interface_name%2Crouter_name%20%7C%20where%20interface_name%3D%22Loopback45%22%20%20and%20interface_status%21%3D%22up%22%20%7C%20table%20router_name" else: return "None" result=run(query,resp) return result
如下Splunk查詢獲取狀態:
· 對於UP接口:查詢以下:
index="main" earliest=0 | dedup interface_name,router_name | where interface_name="Loopback45" and interface_status="up" | table router_name
· 對於DOWN接口(除了之外的任何狀態):查詢以下:
index="main" earliest=0 | dedup interface_name,router_name | where interface_name="Loopback45" and interface_status!="up" | table router_name
讓咱們看看聊天機器人聊天的最終結果以及根據聊天記錄發回的響應。
編碼/解碼示例以下:
正如咱們在這裏看到的,咱們發送了一條encode abhishek[:]password123 消息聊天。此聊天做爲POST請求發送到API,後者又將其加密到base64並使用添加的單詞做爲回覆。在下一個聊天中,咱們使用decode選項傳遞相同的字符串。這會經過解碼來自API函數的信息進行響應,並使用用戶名和密碼回覆Slack聊天。Encoded string: abhishekpassword123
讓咱們看一下Splunk查詢聊天的示例:
在此查詢中,咱們已關閉 Loopback45 接口rtr1。在咱們經過Python腳本計劃發現這些接口的過程當中 ,數據如今位於Splunk中。當查詢哪一個管理接口(Loopback45)關閉時,它將回復rtr1。鬆弛的聊天,On which routers the management interface is down會將此傳遞給API,在收到此有效負載後,它將運行Splunk查詢以獲取統計信息。返回值(在本例中爲rtr1)將做爲聊天中的響應返回。
相似地,中,反向查詢On which routers the management interface is up,將查詢的Splunk和最終共享迴響應rtr2,rtr3和rtr4(由於全部這些路由器接口是UP)。
能夠擴展此聊天用例,以確保使用簡單聊天能夠進行完整的端到端故障排除。可使用各類後端功能構建大量案例,從問題的基本識別到複雜任務,例如基於已識別狀況的補救。