聊天机器人

前一段时间,突发奇想,开发了一个聊天机器人,本来是想做helpdesk的一个平台。support部门的人先教它,然后有问题的人可以像它请教。

教的越多它越聪明。

但是公司一直没有机器来放,只好自己搞着玩一玩。

作为公司用,只有出现解决方案才有作用。也就是当你问它比较专业的问题时,它会告诉你如何解决,解决方案1,2,3并且要出现图解的内容。所以,最好查找到相应的内容,机器人给你一个网页地址,上面包含你要查找的内容。

好了,不多说了,把开发步骤介绍一下。

(一)分析流程,需求,建立数据库。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sogo_link]’) AND type in (N’U’))
BEGIN
CREATE TABLE [dbo].[sogo_link](
 [id] [int] IDENTITY(1,1) NOT NULL,
 [sogo_link_url] [nvarchar](100) NULL,
 [sogo_link_font] [nvarchar](100) NULL,
 [sogo_link_login] [nvarchar](100) NULL,
 [sogo_link_alt] [nvarchar](100) NULL,
 [sogo_link_logo_or_txt] [int] NULL,
 [sogo_link_yes_no] [int] NULL
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[robot]’) AND type in (N’U’))
BEGIN
CREATE TABLE [dbo].[robot](
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [title] [nvarchar](50) NULL,
 [robot_content] [nvarchar](4000) NULL,
 [BigClassName] [nvarchar](50) NULL,
 [SmallClassName] [nvarchar](50) NULL,
 [kin_demo] [nvarchar](4000) NULL,
 [picUrl] [nvarchar](255) NULL,
 [imagenum] [int] NULL,
 [firstImageName] [nvarchar](50) NULL,
 [robot_user] [nvarchar](50) NULL,
 [infotime] [datetime] NULL CONSTRAINT [DF_robot_infotime]  DEFAULT (getdate()),
 [hits] [int] NULL,
 [ok] [bit] NULL,
 [tuijian] [bit] NULL,
 [web_yes_no] [bit] NOT NULL,
 CONSTRAINT [PK_robot] PRIMARY KEY CLUSTERED
(
 [ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Admin]’) AND type in (N’U’))
BEGIN
CREATE TABLE [dbo].[Admin](
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [admin] [nvarchar](50) NULL,
 [password] [nvarchar](50) NULL,
 [aleave] [nvarchar](50) NULL
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[bigClass]’) AND type in (N’U’))
BEGIN
CREATE TABLE [dbo].[bigClass](
 [BigClassID] [int] NOT NULL,
 [BigClassName] [nvarchar](50) NULL,
 [Admin] [nvarchar](100) NULL
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[shop_pinglun]’) AND type in (N’U’))
BEGIN
CREATE TABLE [dbo].[shop_pinglun](
 [pinglunid] [int] NOT NULL,
 [ID] [int] NULL,
 [pinglunname] [nvarchar](50) NULL,
 [pinglundate] [datetime] NULL,
 [pingluncontent] [nvarchar](max) NULL
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SmallClass]’) AND type in (N’U’))
BEGIN
CREATE TABLE [dbo].[SmallClass](
 [SmallClassID] [int] NOT NULL,
 [SmallClassName] [nvarchar](50) NULL,
 [BigClassName] [nvarchar](50) NULL,
 [Admin] [nvarchar](100) NULL
) ON [PRIMARY]
END

(二)建立解决方案网页。

(三)建立web版机器人

(四)申请小I机器人,下载原程序进行修改。

using System;
using System.IO;
using System.Drawing;
using System.Configuration;
using System.Runtime.Serialization;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;

using Incesoft.BotPlatform.SDK;
using Incesoft.BotPlatform.SDK.Interface;

namespace BotPlatformConsoleServer
{
 public class MyRobot
 {
  public string address;

  public int port;

  public string user;

  public string password;

  static void Main(string[] args)
  {
   MyRobot me = new MyRobot();
   me.address = "msnbot.incesoft.com";
   me.port = 6602;
   me.user = "SP092231";
   me.password = "******";
   
   IRobotServer server = RobotServerFactory.Instance.createRobotServer(me.address, me.port);
   server.addRobotHandler(new MyHandler(server));
   server.addConnectionListener(new MyListener());
   try
   {
    server.login(me.user, me.password, 300000);
    server.requestContactList(haigangdeng@126.com);
   }
   catch (RobotException e)  
   {
    Console.Out.WriteLine("Failed to connect :" + e.Message);
   }
  }
 }

 class MyHandler : IRobotHandler
 {
  public MyHandler(IRobotServer server)
  {
   this.server = server;
  }
  private IRobotServer server;
  private Random rdm = new Random();

        public System.String commandList =  "Hi,你好,我是helpdesk小M。r" +
                                                            "如果你有************问题,可以问我。r" +
                                                            "也许我能帮你解答。";

  public System.String commandListEnt = "*****************************************r" +
                  "**  BOTPLATFORM SDK ENTERPRISE ONLY COMMAND LIST  **r" +
                  "**  Only use the following commands after upgraded your sp account  **r" +
                  "
*****************************************r" +
                  " file —— test file transfer.r" +
                  " bg ——– test background sharing.r" +
                  " ink ——- test send ink.r" +
                  " wink —— test send wink.r" +
                  " voice —– test send voiceclip.r" +
                  " webcam —- test send webcamr" +
                  " cs <account> ——– test create session.r" +
                  " pu <account> —— test push offline message.r" +
                  " iv <account> ——– test invite user.r" +
                  " ent ——— print this command list.";
 
  public virtual void  sessionOpened(IRobotSession session)
  {
   System.Console.Out.WriteLine("EVENT: sessionOpened");
   try
   {
    switch(session.OpenMode)
    {
     case SessionOpenMode.OPEN_MODE_CONV_OPEN:
      session.send(commandList);
      break;
     case SessionOpenMode.OPEN_MODE_ROBOT:
      session.send("You have an alert message: blablabla");
      break;
     default:
      break;
    }
   }
   catch (RobotException e)
   {
    util.consoleOut(e.ToString());
   }
  }
  
  
  public virtual void  sessionClosed(IRobotSession session)
  {
   System.Console.Out.WriteLine("EVENT: sessionClosed");
  }
  
  public virtual void  messageReceived(IRobotSession session, IRobotMessage message)
  {
   System.Console.Out.WriteLine("EVENT: messageReceived");
   
   try
   {
    System.String command = message.String;
    
    IRobotMessage msg = session.createMessage();

                if ("+".ToString().Equals(command[0].ToString()))
                {
                    if (command.IndexOf(‘|’) < 0)
                    {
                        session.send("问题和答案要用“|”分开吆");
                    }
                    else
                    {
                        string wenti = command.Substring(1, (command.IndexOf(‘|’) – 1));
                        string daan = command.Substring(command.IndexOf(‘|’) + 1);

                        string connectionstrings = "server=IP*****;UID=robot;PWD=******;DataBase=robot";
                        SqlConnection connection = new SqlConnection(connectionstrings);
                        string sqlxuexi = "insert into robot (title,robot_content,web_yes_no) values (" + "’" + wenti + "’," + "’" + daan + "’," + 0 + ")";
                        SqlCommand commxuexi = new SqlCommand(sqlxuexi,connection);
                        connection.Open();
                        commxuexi.ExecuteNonQuery();
                        connection.Close();

                        session.send("嗯,我记住了,谢谢你。");
                    }
                }

                else if ("help".ToUpper().Equals(command.ToUpper()) || "?".ToUpper().Equals(command.ToUpper()))
                {
                    session.send(commandList);
                }
                else if ("nudge".ToUpper().Equals(command.ToUpper()))
                {
                    session.sendNudge();
                }
    else if ("bye".ToUpper().Equals(command.ToUpper()))
    {
     session.cl
ose();
    }    
    else
                {
                    string connectionstrings = "server=IP******;UID=robot;PWD=******;DataBase=robot";
                    SqlConnection connection = new SqlConnection(connectionstrings);
                    string sqlcontent = "select * from robot where title like" + "’%" + command.ToString() + "%’";
                    SqlDataAdapter myad = new SqlDataAdapter(sqlcontent, connection);
                    connection.Open();

                    DataSet myds = new DataSet();
                    myad.Fill(myds,"robot");

                    if (myds.Tables["robot"].Rows.Count > 0)
                    {
                        int i = 0;
                        while (i < myds.Tables["robot"].Rows.Count)
                        {
                            int f = i + 1;
                            if (myds.Tables["robot"].Rows[i]["web_yes_no"].GetHashCode() == 0)
                            {
                                session.send(myds.Tables["robot"].Rows[i]["robot_content"].ToString());
                            }
                            else
                            {
                                session.send("解决方案(" + f +")n" + "http://www.xxxxx.com/robot/onews.asp?id=" + myds.Tables["robot"].Rows[i]["ID"].ToString());
                            }
                            i = i + 1;
                        }
                    }
                    else
                    {
                        session.send("对不起,我还不知道这个问题的答案,如果你知道你能告诉我吗?用“+问题|答案”的方式告诉我,我就能记住了。");
                    }
                    connection.Close();
                }
   }
   catch (RobotException e)
   {
    util.consoleOut(e.ToString());
   }   
  }
  
  public virtual void  nudgeReceived(IRobotSession session)
  {
   System.Console.Out.WriteLine("EVENT: nudgeReceived");
  }
  
  
  public virtual void  activityAccepted(IRobotSession session)
  {
   System.Console.Out.WriteLine("EVENT: activityAccepted");
  }
  
  
  public virtual void  activityRejected(IRobotSession session)
  {
   System.Console.Out.WriteLine("EVENT: activityRejected");
  }

  public virtual void userAdd(String robot, String user)
  {
   System.Console.Out.WriteLine("EVENT: userAdd");
  }
  
  public virtual void userRemove(String robot, String user)
  {
   System.Console.Out.WriteLine("EVENT: userRemove");
  }
  
  public virtual void  exceptionCaught(IRobotSession session, System.Exception cause)
  {
   System.Console.Out.WriteLine("SERVER ERROR: " + cause.Message);
  }

  public virtual void  activityClosed(IRobotSession session)
  {
   System.Console.Out.WriteLine("EVENT: activityClosed");
  }
  public virtual void  fileAccepted(IRobotSession session)
  {
   System.Console.Out.WriteLine("EVENT: fileAccepted");
  }
  
  public virtual void  fileRejected(IRobotSession session)
  {
   System.Console.Out.WriteLine("EVENT: fileRejected");
  }
  
  public virtual void  fileTransferEnded(IRobotSession session)
  {
   System.Console.Out.WriteLine("EVENT: fileTransferEnded");
  }
  
  public virtu
al void  backgroundAccepted(IRobotSession session)
  {
   System.Console.Out.WriteLine("EVENT: backgroundAccepted");
  }
  
  public virtual void  backgroundRejected(IRobotSession session)
  {
   System.Console.Out.WriteLine("EVENT: backgroundRejected");
  }
  
  public virtual void  backgroundTransferEnded(IRobotSession session)
  {
   System.Console.Out.WriteLine("EVENT: backgroundTransferEnded");
  }
  
  public virtual void  webcamAccepted(IRobotSession session)
  {
   System.Console.Out.WriteLine("EVENT: webcamAccepted");
  }
  
  public virtual void  webcamRejected(IRobotSession session)
  {
   System.Console.Out.WriteLine("EVENT: webcamRejected");
  }
    
  public virtual void  activityLoaded(IRobotSession session)
  {
   System.Console.Out.WriteLine("EVENT: activityLoaded");
  }

  public virtual void  activityReceived(IRobotSession session, System.String data)
  {
   System.Console.Out.WriteLine("EVENT: activityReceived:" + data);
  }

  public virtual void  userJoined(IRobotSession session, IRobotUser user)
  {
   System.Console.Out.WriteLine("EVENT: userJoined : " + user);
  }

  public virtual void  userLeft(IRobotSession session, IRobotUser user)
  {
   System.Console.Out.WriteLine("EVENT: userLeft :" + user);
  }
  
  public virtual void  userUpdated(IRobotUser user)
  {
   System.Console.Out.WriteLine("EVENT: userUpdated (" + user.ID +","+user.Status+","+user.FriendlyName+ ")");
  }
  
  public virtual void  personalMessageUpdated(System.String robot, System.String user, System.String personalMessage)
  {
   System.Console.Out.WriteLine("EVENT: personalMessageUpdated (" + robot + ", " + user + ", " + personalMessage + ")");
  }   
  public virtual void contactListReceived(System.String robot, System.Collections.ArrayList contactList)
  {
   System.Console.Out.WriteLine("EVENT: contactListRecieved ");
   for (int i=0; i<contactList.Count; i++)
   {
    IRobotUser user = (IRobotUser)contactList[i];
    System.Console.Out.WriteLine("User "+i+": "+user.ID);
   }
  } 
  
 }
 class MyListener : IRobotConnectionListener
 {
  public void serverConnected(IRobotServer server)
  {
   Console.Out.WriteLine("Server connected.");
  }

  public void serverReconnected(IRobotServer server)
  {
   Console.Out.WriteLine("Server reconnected.");
  }

  public void serverDisconnected(IRobotServer server)
  {
   Console.Out.WriteLine("Server disconnected.");
  }

  public void serverLoggedIn(IRobotServer sever)
  {
   Console.Out.WriteLine("Server logged in.");
  }
 }
}