建立聊天机器人以协助网络操做

建立聊天机器人以协助网络操做


  • 来源 | 愿码(ChainDesk.CN)内容编辑
  • 愿码Slogan | 链接每一个程序员的故事
  • 网站 | http://chaindesk.cn
  • 愿码愿景 | 打造全学科IT系统免费课程,助力小白用户、初级工程师0成本免费系统学习、低成本进阶,帮助BAT一线资深工程师成长并利用自身优点创造睡后收入。
  • 官方公众号 | 愿码 | 愿码服务号 | 区块链部落
  • 免费加入愿码全思惟工程师社群 | 任一公众号回复“愿码”两个字获取入群二维码

本文阅读时长:11minpython

在本文中,咱们将了解如何利用聊天机器人来协助网络操做。随着咱们向智能化运营迈进,另外一个须要关注的领域是移动性。有一个脚本能够执行配置,修复甚至故障排除,但它仍然须要存在来监视,启动甚至执行这些程序或脚本。程序员

诺基亚的MIKA是操做人员能够用来进行网络故障排除和修复的聊天机器人的一个很好的例子。根据诺基亚的博客,MIKA根据此单个网络的实际状况响应警报优先级信息,并将当前状况与此网络及其余网络过去事件的整个服务历史进行比较,以肯定当前网络的最佳解决方案。json

让咱们建立一个聊天机器人来协助网络运营。对于这个用例,咱们将使用普遍使用的聊天应用程序Slack。参考Splunk的智能数据分析功能,咱们会看到一些用户聊天与聊天机器人的交互,以得到对环境的一些了解。后端

当咱们部署了咱们的Web框架时,咱们将利用相同的框架与Slack聊天机器人进行交互,然后者又将与Splunk进行交互。它还能够直接与网络设备交互,所以咱们能够启动一些复杂的聊天,例如在须要时从Slack重启路由器。这最终为工程师提供了移动性,他能够从任何地方(甚至是手机)处理任务,而没必要绑定到某个位置或办公室。api

要建立聊天机器人,如下是基本步骤:网络

  1. 在Slack上建立一个工做区(或账户):

  1. 在工做区中建立一个应用程序(在咱们的例子中,咱们建立了一个名为的应用程序mybot):

  1. 如下是有关应用程序的基本信息(应用程序ID和客户端ID能够与惟一标识此应用程序的其余信息一块儿使用):

  1. 为此应用程序添加bot功能:

  1. 添加事件订阅并映射到将要发布消息的外部API。事件订阅是指某人在聊天中键入对聊天机器人的引用,而后将使用此聊天机器人与聊天中键入的数据调用哪一个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

  1. 将此应用程序(或聊天机器人)安装到任何渠道(这相似于在群聊中添加用户):

响应特定聊天消息的核心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)。

能够扩展此聊天用例,以确保使用简单聊天能够进行完整的端到端故障排除。可使用各类后端功能构建大量案例,从问题的基本识别到复杂任务,例如基于已识别状况的补救。

相关文章
相关标签/搜索