天天看點

小I機器人初探

很早就知道小I機器人做的不錯,但是一直沒有時間去研究,趁着元旦放假,下來.Net的SDK好好研究了一下,Demo程式是一個控制台程式,使用者互動還不是很友善,此外代碼中竟然有重複的地方,看來小I機器人的主人們不是那麼認真,唉,真苦了小I這孩子:)

<a target="_blank" href="http://blog.51cto.com/attachment/201005/194949145.jpg"></a>

我重新做一個基于Windows窗體的程式,添加了輸入視窗,這樣機器人不會回答的時候,主人也可以代答。此外代碼也重新進行了整理,所有資訊也都修改為中文,友善了使用者調試和開發。此外發現該程式一旦啟動,便無法正常關閉,不知道為什麼?這也許是Demo示例開發者執意為控制台程式的原因之一吧(瞎猜的,初次接觸該SDK程式,我也有很多不明白的地方)。

程式運作後,還是讓人眼前一亮的,下面是程式運作截圖。

<a target="_blank" href="http://blog.51cto.com/attachment/201005/194956578.jpg"></a>

相關代碼如下,需要的朋友可以參考一下:

using System;  

using System.Collections.Generic;  

using System.ComponentModel;  

using System.Data;  

using System.Drawing;  

using System.Text;  

using System.Windows.Forms;  

using System.IO;  

using System.Configuration;  

using System.Runtime.Serialization;  

using System.Collections.Specialized;  

using System.Xml;  

using System.Xml.Serialization;  

using System.Runtime.Serialization.Formatters.Binary;  

using System.Threading;  

using Incesoft.BotPlatform.SDK;  

using Incesoft.BotPlatform.SDK.Interface;  

namespace YFMGC  

{  

    public partial class frmMain : Form  

    {  

        string address;      //位址  

        int port;            //端口  

        string user;         //使用者  

        string password;     //密碼  

        IRobotServer server;  

        MyHandler m_MyHandler;  

        MyListener m_MyListener;  

        public IRobotSession session = null;  

        public frmMain()  

        {  

            InitializeComponent();  

        }  

        //初始化  

        private void frmMain_Load(object sender, EventArgs e)  

            address = "msnbot.incesoft.com";  

            port = 6602;  

            user = "SP042761";  

            password = "yefan7722";  

            server = RobotServerFactory.Instance.createRobotServer(address, port);  

            m_MyHandler = new MyHandler(server, this);  

            m_MyListener = new MyListener(this);  

            server.addRobotHandler(m_MyHandler);  

            server.addConnectionListener(m_MyListener);  

            lblEx_LinkClicked(null, null);  

            txtInfo.Enabled = false;  

            txtSend.Enabled = false;  

        //關閉  

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)  

            //無法成功關閉  

            //server.removeConnectionistener(m_MyListener);  

            //server.removeRobotHandler(m_MyHandler);  

            //m_MyListener.serverDisconnected(server);  

            //server = null;  

            //m_MyListener = null;  

            //m_MyHandler = null;  

            //Application.Exit();  

        //登入/退出  

        private void btnLogin_Click(object sender, EventArgs e)  

            if (btnLogin.Text == "登入")  

            {  

                try 

                {  

                    btnLogin.Enabled = false;  

                    server.login(user, password, 30000);  

                    btnLogin.Text = "退出";  

                    btnLogin.Enabled = true;  

                    txtInfo.Enabled = true;  

                    txtSend.Enabled = true;  

                }  

                catch (RobotException ex)  

                    ShowInfo("登入錯誤:" + ex.Message);  

            }  

            else 

                    server.logout();  

                    btnLogin.Text = "登入";  

                    txtInfo.Enabled = false;  

                    txtSend.Enabled = false;  

                    ShowInfo("退出錯誤:" + ex.Message);  

        //顯示資訊  

        public delegate void lbInfo_ShowInfo(string strInfo);  

        public void ShowInfo(string strInfo)  

            if (strInfo.Length == 0) return;  

            if (lbInfo.InvokeRequired)  

                lbInfo_ShowInfo run = new lbInfo_ShowInfo(ShowInfo);  

                lbInfo.Invoke(run, new object[] { strInfo });  

                lbInfo.Items.Insert(0, "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] " + strInfo);  

                lbInfo.TopIndex = 0;  

                lbInfo.SelectedIndex = 0;  

        //顯示接收的資料  

        public delegate void txtInfo_ShowInfo(string strInfo);  

        public void TxtShowInfo(string strInfo)  

            if (txtInfo.InvokeRequired)  

                txtInfo_ShowInfo run = new txtInfo_ShowInfo(TxtShowInfo);  

                txtInfo.Invoke(run, new object[] { strInfo });  

                txtInfo.Text +="[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] " + strInfo+"\r\n";  

        private void frmMain_SizeChanged(object sender, EventArgs e)  

            scBar.Height = this.Height - 159 + (lbInfo.Visible? 0:lbInfo.Height);  

        //顯隐擴充面闆  

        private void lblEx_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)  

            if (lbInfo.Visible)  

                lblEx.Text = "&gt;&gt;&gt;";  

                lbInfo.Visible = false;  

                this.Height = this.Height - lbInfo.Height;  

                lblEx.Text = "&lt;&lt;&lt;";  

                lbInfo.Visible = true;  

                this.Height = this.Height + lbInfo.Height;  

        //發送  

        private void btnSend_Click(object sender, EventArgs e)  

            IRobotMessage msg = session.createMessage();  

            msg.setSignature("[葉帆插話]");  

            msg.setString(txtSend.Text);  

            session.send(msg);  

            txtSend.Text = "";  

    }  

    class MyHandler : IRobotHandler  

        frmMain fm;  

        public MyHandler(IRobotServer server,frmMain fm)  

            this.server = server;  

            this.fm = fm;  

        private IRobotServer server;  

        private Random rdm = new Random();  

        #region指令菜單  

        public System.String commandList = "*****************************************\r" +  

                                            "** BOTPLATFORM SDK DEMO COMMAND LIST **\r" +  

                                            "*****************************************\r" +  

                                            " preface --- test message preface. \r" +  

                                            " emo ------- test emoticon.\r" +  

                                            " nudge ----- test nudge.\r" +  

                                            " p4 -------- test msn activity.\r" +  

                                            " typing ---- test typing info.\r" +  

                                            " name ------ test change friendly name.\r" +  

                                            " pm -------- test change personal msg.\r" +  

                                            " dp -------- test change display picture.\r" +  

                                            " bye --------- test close session.\r" +  

                                            " help ------ print this command list.\r" +  

                                            " ? --------- print this command list.\r" +  

                                            " ent --------- print enterprise only command list.";  

        public System.String commandListEnt = "*****************************************\r" +  

                                            "** BOTPLATFORM SDK ENTERPRISE ONLY COMMAND LIST **\r" +  

                                            "** Only use the following commands after upgraded your sp account **\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 webcam\r" +  

                                            " cs &lt;account&gt; -------- test create session.\r" +  

                                            " pu &lt;account&gt; ------ test push offline message.\r" +  

                                            " iv &lt;account&gt; -------- test invite user.\r" +  

                                            " ent --------- print this command list.";  

        #endregion  

        public virtual void sessionOpened(IRobotSession session)  

            fm.session = session;  

            fm.ShowInfo("會話開始...");  

            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");  

                    default:  

            catch (RobotException e)  

                util.consoleOut(e.ToString());  

        public virtual void sessionClosed(IRobotSession session)  

            fm.ShowInfo("會話結束");  

        //消息處理  

        public virtual void messageReceived(IRobotSession session, IRobotMessage message)  

            fm.TxtShowInfo(message.String);  

                string command = message.String;  

                IRobotMessage msg = session.createMessage();  

                string command_ex = "";  

                if (command.Length &gt; 2)  

                    command_ex = command.Substring(0, 2);  

                    if (command_ex == "cs" || command_ex == "pu" || command_ex == "iv")  

                    {  

                        command = command_ex;  

                        command_ex = command.Substring(2).Trim();  

                    }  

                switch (command.ToLower())  

                    case "help":      //幫助  

                    case "?":  

                    case "preface":   //設定使用者  

                        msg.setSignature("葉葉 - " + rdm.Next());  

                        msg.setString("我來說一下");  

                        session.send(msg);  

                    case "nudge":     //閃屏  

                         session.sendNudge();  

                    case "p4":        //擴充界面  

                        session.sendActivity("http://yfsoft.blog.51cto.com", "葉帆工作室");  

                    case "typing":    //顯示正在輸入資訊狀态  

                        session.sendTyping();  

                    case "name":     //顯示名  

                        server.DisplayName = "YF.MGC-" + rdm.Next();  

                    case "pm":        //悄悄話  

                        server.PersonalMessage = "葉帆-" + rdm.Next();  

                    case "dp":        //顯示圖檔  

                        server.DisplayPicture = "yf01"; //__default.dat";  

                    case "emo":       //發送含圖檔的資訊  

                        msg.registerEmoticon("(1)", "yf001.png");  

                        msg.registerEmoticon("(2)", "yf002.png");  

                        msg.registerEmoticon("(3)", "yf003.png");  

                        msg.setString("a(1)b(2)c(3)d");  

                    case "ent":  

                        session.send(commandListEnt);  

                    case "cs":        //建立一個對話  

                        server.createSession(session.Robot, command_ex);  

                    case "pu":        //彈出消息  

                        server.pushMessage(session.Robot, command_ex, "你的不線上消息:你在哪裡...");  

                    case "iv":        //邀請使用者  

                        session.inviteUser(command_ex);  

                    case "bye":       //退出會話  

                        session.close();  

                        session.send("俺太小,不懂你的意思!請輸入'?',看看我明白什麼?");  

                    //System.String ret = "font name: " + message.FontName + "\r";  

                    //ret = ret + "font style: " + message.FontStyle + "\r";  

                    //ret = ret + "font color: " + message.FontColor.ToString() + "\r";  

                    //ret = ret + "message content: " + "\r";  

                    //ret = ret + message.String;  

                    //session.send(ret);  

        public virtual void nudgeReceived(IRobotSession session)  

            fm.ShowInfo("事件:閃屏已收到");  

        public virtual void activityAccepted(IRobotSession session)  

            fm.ShowInfo("事件:活動面闆已打開");  

        public virtual void activityRejected(IRobotSession session)  

            fm.ShowInfo("事件:活動面闆被拒絕");  

        public virtual void userAdd(String robot, String user)  

            fm.ShowInfo("事件:使用者被添加("+robot+","+user+")");  

        public virtual void userRemove(String robot, String user)  

            fm.ShowInfo("事件:使用者被删除(" + robot + "," + user + ")");  

        public virtual void exceptionCaught(IRobotSession session, System.Exception cause)  

            fm.ShowInfo("伺服器出錯:" + cause.Message);  

        public virtual void activityClosed(IRobotSession session)  

            fm.ShowInfo("事件:活動面闆被關閉");  

        public virtual void fileAccepted(IRobotSession session)  

            fm.ShowInfo("事件:發送的檔案被接收");  

        public virtual void fileRejected(IRobotSession session)  

            fm.ShowInfo("事件:發送的檔案被舍棄");  

        public virtual void fileTransferEnded(IRobotSession session)  

            fm.ShowInfo("事件:檔案傳送完畢");  

        public virtual void backgroundAccepted(IRobotSession session)  

            fm.ShowInfo("事件:會話場景被接收");  

        public virtual void backgroundRejected(IRobotSession session)  

            fm.ShowInfo("事件:會話場景被舍棄");  

        public virtual void backgroundTransferEnded(IRobotSession session)  

            fm.ShowInfo("事件:會話場景設定完畢");  

        public virtual void webcamAccepted(IRobotSession session)  

            fm.ShowInfo("事件:畫面被接收");  

        public virtual void webcamRejected(IRobotSession session)  

            fm.ShowInfo("事件:畫面被舍棄");  

        public virtual void activityLoaded(IRobotSession session)  

            fm.ShowInfo("事件:活動面闆使用者已響應");  

        public virtual void activityReceived(IRobotSession session, System.String data)  

            fm.ShowInfo("事件:活動面闆使用者已輸入資料" + data);  

        public virtual void userJoined(IRobotSession session, IRobotUser user)  

            fm.ShowInfo("事件:使用者已加入(" + user+")");  

        public virtual void userLeft(IRobotSession session, IRobotUser user)  

            fm.ShowInfo("事件:使用者(" + user + ")");  

        public virtual void userUpdated(IRobotUser user)  

            fm.ShowInfo("事件:使用者資訊已更新(" + user.ID + "," + user.Status + "," + user.FriendlyName + ")");  

        public virtual void personalMessageUpdated(System.String robot, System.String user, System.String personalMessage)  

            fm.ShowInfo("事件:悄悄話(" + robot + ", " + user + ", " + personalMessage + ")");  

        public virtual void contactListReceived(System.String robot, System.Collections.ArrayList contactList)  

            fm.ShowInfo("事件:會話使用者清單");  

            for (int i = 0; i &lt; contactList.Count; i++)  

                IRobotUser user = (IRobotUser)contactList[i];  

                fm.ShowInfo("User " + i + ": " + user.ID);  

    class MyListener : IRobotConnectionListener  

        public MyListener(frmMain fm)  

        public void serverConnected(IRobotServer server)  

            fm.ShowInfo("伺服器已連接配接成功,正在登入,請耐心等待 ...");  

        public void serverReconnected(IRobotServer server)  

            fm.ShowInfo("再次與伺服器連接配接...");  

        public void serverDisconnected(IRobotServer server)  

            fm.ShowInfo("伺服器已斷開!");  

        public void serverLoggedIn(IRobotServer sever)  

            fm.ShowInfo("使用者登入成功!");  

}  

本文轉自yefanqiu51CTO部落格,原文連結:http://blog.51cto.com/yfsoft/323876,如需轉載請自行聯系原作者