| 聊天机器人's profile聊天机器人BlogLists | Help |
|
June 12 如何为LumaQQ添加聊天机器人摘要 LumaQQ没有提供功能十足的机器人给你用,所以,实现一个机器人需要靠你自己,LumaQQ只为你提供了一个简单的框架,本文就是向你介绍如何在LumaQQ中插入自己的机器人的。 第一步:实现自己的机器人缺省情况下,LumaQQ提供了一个机器人,但是这个机器人基本上什么也没做,而且,缺省也是没有打开的。这个机器人的代码在edu.tsinghua.lumaqq.qq.robot.DummyRobot.java中,它纯粹是一个演示目的,如果你想看看效果,可以在LumaQQ的xml目录下面找到一个robots.xml文件,这个文件是机器人的配置文件,你可以看到里面我写了一些注释,你把那些注释去掉,保存,然后重启LumaQQ就可以了。使用机器人的方法是打开系统菜单,如果系统配置了至少一个机器人的话,系统菜单中会有一项“聊天机器人”,它的子菜单里面列出了所有存在的机器人,另外包含一个开始/停止菜单,我就不多说了,想来你应该会用。 为了实现一个聊天机器人,你必须实现edu.tsinghua.lumaqq.qq.robot.IRobot接口,这个接口目前相当简单,只包含了一个方法,如下: public interface IRobot {
/**
* 根据message得到一条回复消息
*
* @param packet
* 接受消息包
* @return
* 回复的消息,返回null表示不响应这条消息
*/
public String getReply(ReceiveIMPacket packet);
}
而DummyRobot的实现则是: public class DummyRobot implements IRobot {
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.qq.robot.IRobot#getReply(edu.tsinghua.lumaqq.qq.packets.in.ReceiveIMPacket)
*/
public String getReply(ReceiveIMPacket packet) {
/*
* Example:
* 1. 如何得到发送者QQ号
* packet.header.sender
*
* 2. 如何得到消息内容
* packet.normalIM.messageBytes是消息的字节数组内容,如果需要得到字符串形式
* new String(packet.normalIM.messageBytes, QQ.QQ_CHARSET_DEFAULT)
* 对于消息格式,参见edu.tsinghua.lumaqq.qq.beans.NormalIM
*
* 3. 如何判断这个消息是一个大消息中的分片?
* if(packet.normalIM.totalFragments > 1) {
* // 做你的处理,怎么处理,你决定,你可以把他缓存起来等待所有分片都收到为止
* }
*
* 4. 如何知道这个消息的分片序号?
* packet.normalIM.fragmentSequence
*
* 5. 如何知道这个消息的id?消息id也是用在分片情况时,同一个消息的分片,消息id相同
* packet.normalIM.messageId
*
* 6. 如何知道一个消息是不是自动回复?
* if(packet.normalIM.replyType != QQ.QQ_IM_AUTO_REPLY) {
* // 做你想做的
* }
*
* 更多内容和可用字段
* 参考edu.tsinghua.lumaqq.qq.beans.NormalIMHeader
* 参考edu.tsinghua.lumaqq.qq.beans.ReceiveIMHeader
*/
if(packet.normalIM.replyType != QQ.QQ_IM_AUTO_REPLY)
return "Hello, I am robot";
else
return null;
}
}
所以你也看到了,DummyRobot基本上啥也没干,就是老返回一句相同的话而已,不过它会判断一下是不是自动回复,如果是就不处理了,免得碰到自动回复的时候没完没了。你看到了,DummyRobot里面的有不少注释,应该对你的帮助很直接了。 第二步:部署机器人程序添加一个机器人并不需要修改LumaQQ的源代码,你只要将你的机器人程序打包成jar文件,然后copy到LumaQQ的lib目录下就可以了,这样的好处自然就是你可以随便添加机器人,而且并不一定需要有LumaQQ的源代码,当然,你在编写你的机器人程序的时候,需要导入lumaqq.jar到工程中,不然找不到IRobot接口定义了。 第三步:修改机器人配置文件机器人配置文件位于LumaQQ的xml目录下,这个文件自然是新增的,如果不存在这个文件的话,那么LumaQQ就会认为是没有机器人可用,系统菜单中也就不会有机器人的菜单项了。这个文件的格式也很简单,假设我要配置DummyRobot,那么就是下面这个样子: <?xml version="1.0" encoding="UTF-8"?> <Robots> <Robot> <Name>Dummy Robot</Name> <Implementation>edu.tsinghua.lumaqq.qq.robot.DummyRobot</Implementation> </Robot> </Robots> See? 仅仅就是配置一个机器人的名字,另外配置一下IRobot的实现类即可。如果你有多个机器人,你可以随便添加Robot元素 总结添加一个机器人的工作就结束了,喜欢玩就玩吧。 LumaQQ is a Java QQ client which has a reusable pure Java core and SWT-based GUI 聊天机器人,呻吟(Saying)和友邻前几天利用Smack API(Java XMPP client library)写了一个Google Talk Bot,基本实现了Twitter IM Bot指令,还加了个简单的管理指令,允许指定的管理员查看联系人列表。 来源:http://blog.terac.com/andy/e_1412.html March 06 终于明白孙悟空为何不自己搞定妖怪了我相信大家都看过西游记,但是不知道大家思考过这么一个问题没有:孙悟空为什么不自己搞定妖怪而老是求救?孙悟空号称齐天大圣,72变,本事大是不用置疑,大闹天宫的时候只有如来才可以制服,但是取经路上,碰到几个小妖就搞不定,每次不是求神仙就是求观音求如来!答案只有一个:孙悟空是个自私的老奸巨猾的高手!
※原帖来自于:来福岛爆笑娱乐网http://www.laifu.org August 19 DotMSN Example 解读(一) Coversationform.csCoversationform.cs要完成的是通讯功能,首先声明了一个类 ConversationForm ,定义了一个属性_conversation,在构造方法中初始化界面,并注册了几个监视函数。
using System;
using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using XihSolutions.DotMSN; namespace DotMSNClient
{ /// <summary> /// Summary description for ConversationForm. /// </summary> public class ConversationForm : System.Windows.Forms.Form { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private System.Windows.Forms.TextBox conversationTextBox; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.TextBox inputTextBox; private System.Windows.Forms.Button sendButton; /// <summary>
/// </summary> private Conversation _conversation; /// <summary>
/// The conversation object which is associated with the form. /// </summary> public Conversation Conversation { get { return _conversation; } } public ConversationForm(Conversation conversation)
{ _conversation = conversation; //
// Required for Windows Form Designer support // InitializeComponent(); Conversation.Switchboard.TextMessageReceived += new TextMessageReceivedEventHandler(Switchboard_TextMessageReceived);
Conversation.Switchboard.SessionClosed += new SBChangedEventHandler(Switchboard_SessionClosed); Conversation.Switchboard.ContactJoined += new ContactChangedEventHandler(Switchboard_ContactJoined); Conversation.Switchboard.ContactLeft += new ContactChangedEventHandler(Switchboard_ContactLeft); } /// <summary>
/// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.conversationTextBox = new System.Windows.Forms.TextBox(); this.panel1 = new System.Windows.Forms.Panel(); this.sendButton = new System.Windows.Forms.Button(); this.inputTextBox = new System.Windows.Forms.TextBox(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // conversationTextBox // this.conversationTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.conversationTextBox.Location = new System.Drawing.Point(0, 0); this.conversationTextBox.Multiline = true; this.conversationTextBox.Name = "conversationTextBox"; this.conversationTextBox.Size = new System.Drawing.Size(464, 334); this.conversationTextBox.TabIndex = 0; // // panel1 // this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(163)))), ((int)(((byte)(163)))), ((int)(((byte)(186))))); this.panel1.Controls.Add(this.sendButton); this.panel1.Controls.Add(this.inputTextBox); this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel1.Location = new System.Drawing.Point(0, 256); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(464, 78); this.panel1.TabIndex = 1; // // sendButton // this.sendButton.Location = new System.Drawing.Point(451, 26); this.sendButton.Name = "sendButton"; this.sendButton.Size = new System.Drawing.Size(90, 25); this.sendButton.TabIndex = 1; this.sendButton.Text = "Send"; this.sendButton.Click += new System.EventHandler(this.sendButton_Click); // // inputTextBox // this.inputTextBox.Location = new System.Drawing.Point(10, 9); this.inputTextBox.Multiline = true; this.inputTextBox.Name = "inputTextBox"; this.inputTextBox.Size = new System.Drawing.Size(412, 60); this.inputTextBox.TabIndex = 0; this.inputTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.inputTextBox_KeyDown); // // ConversationForm // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(464, 334); this.Controls.Add(this.panel1); this.Controls.Add(this.conversationTextBox); this.Name = "ConversationForm"; this.Text = "Conversation - DotMSN"; this.Closing += new System.ComponentModel.CancelEventHandler(this.ConversationForm_Closing); this.Load += new System.EventHandler(this.ConversationForm_Load); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); }
#endregion private bool _typingMessageSended = false;
private void SendInput()
{ // check whether there is input if(inputTextBox.Text.Length == 0) return; // if there is no switchboard available, request a new switchboard session
if(Conversation.SwitchboardProcessor.Connected == false) { Conversation.Messenger.Nameserver.RequestSwitchboard(Conversation.Switchboard, this); } // note: you can add some code here to catch the event where the remote contact lefts due to being idle too long
// in that case Conversation.Switchboard.Contacts.Count equals 0. TextMessage message = new TextMessage(inputTextBox.Text);
/* You can optionally change the message's font, charset, color here.
* For example: * message.Color = Color.Red; * message.Decorations = TextDecorations.Bold; */ Conversation.Switchboard.SendTextMessage(message); _typingMessageSended = false; inputTextBox.Text = ""; conversationTextBox.Text += "You say: " + message.Text + "\r\n"; } private void sendButton_Click(object sender, System.EventArgs e) { SendInput(); } private void inputTextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{ if(_typingMessageSended == false) { Conversation.Switchboard.SendTypingMessage(); _typingMessageSended = true; } if(e.KeyCode == Keys.Enter) SendInput(); } private delegate void MakeVisibleDelegate();
private void MakeVisible() { Show(); } private delegate void PrintTextDelegate(string name, string text);
private void PrintText(string name, string text) { conversationTextBox.Text += name + " says: " + text + "\r\n"; } private void Switchboard_TextMessageReceived(object sender, TextMessageEventArgs e)
{ // use Invoke() because this method is not run in the form's thread, but in the DotMSN (worker)thread if(Visible == false) { this.Invoke(new MakeVisibleDelegate(MakeVisible)); } Invoke(new PrintTextDelegate(PrintText), new object[] { e.Sender.Name, e.Message.Text }); } private void Switchboard_SessionClosed(object sender, EventArgs e)
{ conversationTextBox.Text += "* Session was closed\r\n"; } private void Switchboard_ContactJoined(object sender, ContactEventArgs e)
{ conversationTextBox.Text += "* " + e.Contact.Name + " joined the conversation\r\n"; } private void Switchboard_ContactLeft(object sender, ContactEventArgs e)
{ conversationTextBox.Text += "* " + e.Contact.Name + " left the conversation\r\n"; } private void ConversationForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{ Conversation.Switchboard.Close(); } private void ConversationForm_Load(object sender, EventArgs e)
{ } } } August 18 MSN Messenger协议
原作:bhw98 前 言 MSN Messenger 是Microsoft开发的聊天工具,目前在国内拥有很大的用户群。使用MSN Messenger可以与他人进行文字聊天,语音对话,视频会议等即时交流,还可以通过此软件来查看联系人是否联机等。该软件的最新版本是6.1。 1999年,Microsoft向IETF提交了一份"MSN Messenger Service 1.0 Protocol"草案,这是最初版本的MSN Messenger协议。在以后几年,该公司不再公开有关MSN Messenger协议的升级、修改细节的官方文档。但无论是开发第三方的聊天客户端软件(如Gaim, MyIM等),还是做协议分析,必须对其通信协议有深入了解。正因为如此,有一些民间人士对这些协议开展了研究。 当我们还在感叹"这世界,变化快"的时候,MSN Messenger的协议已经到了第10版,简称MSNP10,对应于MSN Messenger 6.1。MSN Messenger 6.0则使用MSNP9。现在Microsoft强迫MSN Messenger用户升级到6.0或6.1版,因为服务器对MSNP8以下的版本不再支持。本文及后续文章所描述的MSN Messenger协议主要针对MSNP9/MSNP10。 1. 连 接 MSN Messenger协议建立在TCP/IP之上。除了文件传输和语音聊天是直接的"点对点"通信之外,其它所有的情形全部通过服务器进行。 在逻辑上,一共有三种类型的服务器,各司其职: 2. 命 令 MSN Messenger命令使用纯ASCII码。对非ASCII码字符使用URL编码。命令的语法是 XXX[<SP>TrID<SP>PARAM1<SP>PARAM2…]<CRLF> 其中,<SP>是空白字符,<CRLF>是回车换行,XXX是一个3字符的命令串,TrID是一个流水号,PARAMx是参数,[ ]内是可选项。最简单的命令没有流水号和参数。为了方便起见,下面讨论时用" "代表<SP>,"\r\n"代表<CRLF>,"\x??"代表一个值为0x??字节。红色表示由客户端发出,蓝色表示由服务器发出。一个MSN Messenger命令的例子如下: USR 18 TWN I example@hotmail.com\r\n
3. 错 误 无论是由于客户端发出的命令无效,参数无效,还是其他什么原因,服务器可以返回一个错误。格式为 XXX[<SP>TrID]<CRLF> 其中,XXX是一个3位数字的串。如 ADD 21 AL non_existent@passport.com non_existent@passport.com\r\n 205 21\r\n 上例中,non_existent@passport.com是一个不存在的账号。 4. 消 息 MSN Messenger消息符合MIME 1.0标准,由消息头与消息体组成。通常使用UTF-8编码,消息头中也需要URL编码格式,消息体则直接用二进制数据。 一个MSN Messenger消息的例子如下: MIME-Version: 1.0\r\n Content-Type: text/plain; charset=UTF-8\r\n X-MMS-IM-Format: FN=%E5%AE%8B%E4%BD%93; EF=; CO=0; CS=86; PF=0\r\n \r\n bhw98\xE4\xBD\xA0\xE5\xA5\xBD\xEF\xBC\x81 经简单分析可知,"%E5%AE%8B%E4%BD%93"是"宋体"的UTF-8加URL编码,而"bhw98\xE4\xBD\xA0\xE5\xA5\xBD\xEF\xBC\x81"是"bhw98你好!"的UTF-8编码。 命令一览
MSN Messenger协议--错误代码一览
过去的MSN Messenger版本(MSNP8以下),简单地使用MD5等Hash算法对用户身份进行认证。MSNP9/MSNP10使用一种TWN(Tweener)认证方式,通过SSL/TLS连接到login.passport.com和loginnet.passport.com等服务器,借助于HTTP协议输入账号和密码,认证通过后,才能取得“入场券”。 真正意义上的身份认证,发生在客户端与通知服务器(NS)之间。客户端登陆NS时,首先交换版本信息。双方均支持MSNP8以上版本时,才能进行认证过程。如果客户端版本较低,不支持TWN,咋办?服务器会将你一脚揣出去,信不信? 好了,废话少说,现在拿一个成功认证的例子看看。在下面的例子中,账号是“example@passport.com”,密码是“password”。 VER 4 MSNP10 MSNP9 CVR0 \r\nVER 4 MSNP9 CVR0 \r\n CVR 5 0x0804 winnt 5.0 i386 MSNMSGR 6.1.0203 MSMSGS example@passport.com \r\n CVR 5 6.0.0602 6.0.0602 5.0.0527 http://download.microsoft.com/download/d/4/f/d4f560d5-6dc6-4901-b149-a568415561d7/SETUPNT.EXE http://messenger.msn.com/cn \r\n USR 6 TWN I example@passport.com \r\n USR 6 TWN Slc=1033,id=507,tw=40,fs=1,ru=http%3A%2F%2Fmessenger%2Emsn%2Ecom,ct=1073355862,kpp=1,kv=5,ver=2.1.0173.1, tpf=ed1c2f217a21c191c61251eb8b73bb60 \r\n (此时通过SSL进行身份认证,获得“入场券”) USR 7 TWN S t=4m1wWfEupDgUNb53qys5gJdw8OTJEtT82fcuDbS3U672gTymOOs6cgKeafj7WjgZNcufAQggxqHRRXko02DoflZA$$ &p=4QXNnX9rFDDgki9ZqvqPZGDGJa2Mrd5H13Zfl0NNjh4I78qPyfpzmkZPZEe0nxJTkzZSNDYtk!57cVqiYVfO86KgCRYWhi2kudS0M !7bdi82EDA1FYp3WboHD!sCQ17OZh7lPQI7fozrgsSMZwgSzRi2FNTPxf13oDNIfDCKCG!2guDvZKEpk78A$$ \r\n USR 7 OK example@passport.com example@passport.com 1 0 \r\n 第一回合(TrID=4),双方协商MSN版本号。客户端说“我能支持MSNP9和MSNP10”,NS说“行,就MSNP9吧”。 第二回合(TrID=5),客户端报告本机信息:OS = windows 2000 (NT 5.0), 语言 = 简体中文,MSN Messenger版本 = 6.1.0203, 账号 = example@passport.com。NS给出了推荐的版本号,能够使用的最老的版本号,新版本下载地址,官方网站地址等信息。 第三回合(TrID=6),客户端要求身份认证(I = Initial),NS则给出所需要的一长串信息(S = Subsequent)。其中tpf相当于challenge,参与Hash运算,能保证每次认证返回的串是不同的。 第四回合(TrID=7),客户端出示从认证服务器得到的“入场券”,NS放行(OK)。 第三、四回合之间,通过SSL的认证过程如下: 首先在HTTPS端口443向login.passport.com发送一个GET请求,将账号、密码和NS给定的一长串信息送出 GET /login2.srf HTTP/1.1 \r\nAuthorization: Passport1.4 OrgVerb=GET,OrgURL=http%3A%2F%2Fmessenger%2Emsn%2Ecom,sign-in=example%40passport.com,pwd=password, lc=1033,id=507,tw=40,fs=1,ru=http%3A%2F%2Fmessenger%2Emsn%2Ecom,ct=1073355862,kpp=1,kv=5,ver=2.1.0173.1, tpf=ed1c2f217a21c191c61251eb8b73bb60 \r\n Host: login.passport.com \r\n \r\n 根据情况,会重定向到不同的URL。本例中,重定向到"https://loginnet.passport.com/login2.srf?lc=1033",服务器应答 HTTP/1.1 302 Found \r\n Server: Microsoft-IIS/5.0 \r\nDate: Mon, 22 Dec 2003 21:10:05 GMT \r\n PPServer: H: LAWPPLOG5C006 \r\n Connection: close \r\n Content-Type: text/html \r\n Expires: Mon, 22 Jun 2003 21:09:05 GMT \r\n Cache-Control: no-cache \r\n cachecontrol: no-store \r\n Pragma: no-cache \r\n P3P: CP="DSP CUR OTPi IND OTRi ONL FIN" \r\n Authentication-Info: Passport1.4 da-status=redir \r\n Location: https://loginnet.passport.com/login2.srf?lc=1033 \r\n \r\n ... ... 然后,重新向指定的URL发出请求,得到如下响应 HTTP/1.1 200 OK \r\n 开始时直接向loginnet.passport.com发出正确的请求,也是可以的。不难看出,在服务器认证成功的返回信息中,Authentication-Info字段的from-PP串值,就是所谓的“入场券”。 如果认证失败,服务器返回401错误 HTTP/1.1 401 Unauthorized \r\n ... ...这样,就无法拿到“入场券”,自然不能在第四回合中输入合法的串。 如果英文够好可以参考:www.hypothetic.org 这里的信息非常全面 DotMSNDotMSNDotMSN is an open-source stand-alone class library to provide connectivity with the MSN Messenger service. The library is built in C# and can therefore be used by all languages the .NET environment supports. Because of a clean natural Object-Oriented approach the library is easy to use and implement. DotMSN is designed to be a flexible, robust and lightweight enhancement to any application. Applications of DotMSN vary from creating messaging robots to creating custom clients. If your application needs to communicate through the messenger service, DotMSN is your tool. FeaturesThe library currently supports the following features:
DotMSN is a stand-alone library. This means there is no interaction with the official MSN Messenger client and therefore it does not need to be installed when using DotMSN. Multiple instances of DotMSN can be executed on the same machine, or even in the same process. Thus making it easy to deploy applications on a single server. How does DotMSN integrate with your application? The following diagram makes clear how DotMSN interacts with your application as well as remote parties.
![]() Get DotMSNYou can download DotMSN at the download page. ResourcesHere is a list of resources that have helped the development of DotMSN tremendously. March 04 AIML OverviewAIML OverviewBy Dr. Richard S. Wallace AIML, or Artificial Intelligence Mark-up Language enables people to input knowledge into chat-bots based on the A.L.I.C.E free software technology. AIML was developed by the Alicebot free software community and I during 1995-2000. It was originally adapted from a non-XML grammar also called AIML, and formed the basis for the first Alicebot, A.L.I.C.E., the Artificial Linguistic Internet Computer Entity. AIML, describes a class of data objects called AIML objects and partially describes the behavior of computer programs that process them. AIML objects are made up of units called topics and categories, which contain either parsed or unparsed data. Parsed data is made up of characters, some of which form character data, and some of which form AIML elements. AIML elements encapsulate the stimulus-response knowledge contained in the document. Character data within these elements is sometimes parsed by an AIML interpreter, and sometimes left unparsed for later processing by a Responder. CATEGORIESThe basic unit of knowledge in AIML is called a category. Each category consists of an input question,an output answer, and an optional context. The question, or stimulus, is called the pattern. Theanswer, or response, is called the template. The two types of optional context are called "that" and"topic." The AIML pattern language is simple, consisting only of words, spaces, and the wildcard symbols _ and *. The words may consist of letters and numerals, but no other characters. The pattern language is case invariant. Words are separated by a single space, and the wildcard characters function like words. The first versions of AIML allowed only one wild card character per pattern. The AIML 1.01 standard permits multiple wildcards in each pattern, but the language is designed to be as simple as possible for the task at hand, simpler even than regular expressions. The template is the AIML respons or reply. In its simplest form, the template consists of only plain, unmarked text. More generally, AIML tags transform the reply into a mini computer program which can save data, activate other programs, give conditional responses, and recursively call the pattern matcher to insert the responses from other categories. Most AIML tags in fact belong to this template side sublanguage. AIML currently supports two ways to interface other languages and systems. The <system> tag executes any program accessible as an operating system shell command, and inserts the results in the reply. Similarly, the <javascript> tag allows arbitrary scripting inside the templates. The optional context portion of the category consists of two variants, called <that> and <topic>. The <that> tag appears inside the category, and its pattern must match the robot’s last utterance. Remembering one last utterance is important if the robot asks a question. The <topic> tag appears outside the category, and collects a group of categories together. The topic may be set inside any template. AIML is not exactly the same as a simple database of questions and answers. The pattern matching "query" language is much simpler than something like SQL. But a category template may contain the recursive <srai> tag, so that the output depends not only on one matched category, but also any others recursively reached through <srai>. RECURSIONAIML implements recursion with the <srai> operator. No agreement exists about the meaning of the acronym. The "A.I." stands for artificial intelligence, but "S.R." may mean "stimulus-response," "syntactic rewrite," "symbolic reduction," "simple recursion," or "synonym resolution." The disagreement over the acronym reflects the variety of applications for <srai> in AIML. Each of these is described in more detail in a subsection below: (1). Symbolic Reduction: Reduce complex grammatic forms to simpler ones. (2). Divide and Conquer: Split an input into two or more subparts, and combine the responses to each. (3). Synonyms: Map different ways of saying the same thing to the same reply. (4). Spelling or grammar corrections. (5). Detecting keywords anywhere in the input. (6). Conditionals: Certain forms of branching may be implemented with <srai>. (7). Any combination of (1)-(6). The danger of <srai> is that it permits the botmaster to create infinite loops. Though posing some risk to novice programmers, we surmised that including <srai> was much simpler than any of the iterative block structured control tags which might have replaced it. (1). Symbolic ReductionSymbolic reduction refers to the process of simplifying complex grammatical forms into simpler ones. Usually, the atomic patterns in categories storing robot knowledge are stated in the simplest possible terms, for example we tend to prefer patterns like "WHO IS SOCRATES" to ones like "DO YOU KNOW WHO SOCRATES IS" when storing biographical information about Socrates. Many of the more complex forms reduce to simpler forms using AIML categories designed for symbolic reduction: <category> Whatever input matched this pattern, the portion bound to the wildcard * may be inserted into the reply with the markup <star/>. This category reduces any input of the form "Do you know who X is?" to "Who is X?" (2). Divide and ConquerMany individual sentences may be reduced to two or more subsentences, and the reply formed by combining the replies to each. A sentence beginning with the word "Yes" for example, if it has more than one word, may be treated as the subsentence "Yes." plus whatever follows it. <category> The markup <sr/> is simply an abbreviation for <srai><star/></srai>. (3). SynonymsThe AIML 1.01 standard does not permit more than one pattern per category. Synonyms are perhaps the most common application of <srai>. Many ways to say the same thing reduce to one category, which contains the reply: <category> <category> <category> <category> <category> (4). Spelling and Grammar correctionThe single most common client spelling mistake is the use of "your" when "you’re" or "you are" is intended. Not every occurrence of "your" however should be turned into "you’re." A small amount of grammatical context is usually necessary to catch this error: <category> Here the bot both corrects the client input and acts as a language tutor. (5). KeywordsFrequently we would like to write an AIML template which is activated by the appearance of a keyword anywhere in the input sentence. The general format of four AIML categories is illustrated by this example borrowed from ELIZA: <category> <category> <category> <category> The first category both detects the keyword when it appears by itself, and provides the generic response. The second category detects the keyword as the suffix of a sentence. The third detects it as the prefix of an input sentence, and finally the last category detects the keyword as an infix. Each of the last three categories uses <srai> to link to the first, so that all four cases produce the same reply, but it needs to be written and stored only once. (6). ConditionalsIt is possible to write conditional branches in AIML, using only the <srai> tag. Consider three categories: <category> <category> <category> Provided that the predicate "he" is initialized to "Unknown," the categories execute a conditional branch depending on whether "he" has been set. As a convenience to the botmaster, AIML also provides the equivalent function through the <condition> tag. TARGETINGBot personalities are created and shaped through a cyclical process of supervised learning called Targeting. Targeting is a cycle incorporating client, bot, and botmaster, wherein client inputs that find no complete match among the categories are logged by the bot and delivered as Targets the botmaster, who then creates suitable responses, starting with the most common queries. The Targeting cycle produces a progressively more refined bot personality. The art of AIML writing is most apparent in creating default categories, which provide noncommittal replies to a wide range of inputs. Here is a very nice example provided found on the alicebot-general mailing list: User: Where do I find the webpage with Australopithecus? Alice: Where do you want to find it? User: Bad Answer Alice, time to Learn a new Line Alice: How would you answer "Where do I find the webpage with Australopithecus?" User: I would say: "http://www.ancientskulls.net/australopithecus.html" Alice: Thanks, human. Try asking me again. User: Where do I find the webpage with Australopithecus? Alice: http://www.ancientskulls.net/australopithecus.html This is a very nice example. This is exactly the same as targeting when the botmaster is the teacher. Or I should say, it is an AIML interface to targeting. Of course this scenario raises many problems, such as how to weed out hackers and other garbage givers, which might mean only turning on the Learn function while in a restricted sandbox, though it is the free labor of many chatters the web that could help the bot grow wise quickly. That is the crux of the learning problem in a nutshell. It all comes down to editing. Either the botmaster edits good quality replies to begin with, or if the bot is "open to the public" then the teacher has to edit out all the crappy answers supplied by all that "free" labor. My personal view is that, compared with a hypothetical learning machine capable of learning language like a child, the AIML targeting approach is more efficient. CONTEXTThe keyword "that" in AIML refers to the robot’s previous utterance. Specifically, if the robot responds with a multiple sentence paragraph, the value of that is set to the last sentence in the sequence. The choice of the keyword "that" is motivated by its use in ordinary language: R: Today is yesterday. C: That makes no sense. R: The answer is 3.1412926 approximately. C: That is cool. In AIML the syntax <that>...</that> encloses a pattern that matches the robot’s previous utterance. A common application of <that> is found in yes-no questions: <category> This category is activated when the client says YES. The robot must find out what is he saying "yes" to. If the robot asked, "Do you like movies?," this category matches, and the response, "What is your favorite movie?," continues the conversation along the same lines. One interesting application of <that> are categories that enable the robot to respond to knock-knock jokes. The categories: <category> <category> <category> produce the following dialogue: C: Knock knock. R: Who’s there? C: Banana. R: Banana who? C: Knock knock. R: Who’s there? C: Banana. R: Banana who? C: Knock knock. R: Who’s there? C: Orange. R: Orange who? C: Orange you glad I didn’t say banana. R: Ha ha very funny, Nancy. Internally the AIML interpreter stores the input pattern, that pattern and topic pattern along a single path, like: INPUT <that> THAT <topic> TOPIC. When the values of <that> or <topic> are not specified, the program implicitly sets the values of the corresponding THAT or TOPIC pattern to the wildcard *. The first part of the path to match is the input. If more than one category have the same input pattern, the program may distinguish between them depending on the value of <that>. If two or more categories have the same <pattern> and <that>, the final step is to choose the reply based on the <topic>. This structure suggests a design rule: never use <that> unless you have written two categories with the same <pattern>, and never use <topic> unless you write two categories with the same <pattern> and <that>. Still, one of the most useful applications for <topic> is to create subject-dependent "pickup lines," like: <topic name="CARS"> <category> Considering the vast size of the set of things people could say that are grammatically correct or semantically meaningful, the number of things people actually do say is surprisingly small. Steven Pinker,in his book How the Mind Works wrote, "Say you have ten choices for the first word to begin a sentence, ten choices for the second word (yielding 100 two-word beginnings), ten choices for the third word (yielding a thousand three-word beginnings), and so on. (Ten is in fact the approximate geometric mean of the number of word choices available at each point in assembling a grammatical and sensible sentence). A little arithmetic shows that the number of sentences of 20 words or less (not an unusual length) is about 1020." Fortunately for chat robot programmers, Pinker’s calculations are way off. Our experiments with A.L.I.C.E. indicate that the number of choices for the "first word" is more than ten, but it is only about two thousand. Specifically, about 2000 words covers 95% of all the first words input to A.L.I.C.E.. The number of choices for the second word is only about two. To be sure, there are some first words ("I" and "You" for example) that have many possible second words, but the overall average is just under two words. The average branching factor decreases with each successive word. We have plotted some beautiful images of the A.L.I.C.E. brain contents represented by this graph (http://alice.sunlitsurf.com/documentation/gallery/). More than just elegant pictures of the A.L.I.C.E. brain, these spiral images (see more) outline a territory of language that has been effectively "conquered" by A.L.I.C.E. and AIML. No other theory of natural language processing can better explain or reproduce the results within our territory. You don’t need a complex theory of learning, neural nets, or cognitive models to explain how to chat within the limits of A.L.I.C.E.’s 25,000 categories. Our stimulus-response model is as good a theory as any other for these cases, and certainly the simplest. If there is any room left for "higher" natural language theories, it lies outside the map of the A.L.I.C.E. brain. Academics are fond of concocting riddles and linguistic paradoxes that supposedly show how difficult the natural language problem is. "John saw the mountains flying over Zurich" or "Fruit flies like a banana" reveal the ambiguity of language and the limits of an A.L.I.C.E.-style approach (though not these particular examples, of course, A.L.I.C.E. already knows about them). In the years to come we will only advance the frontier further. The basic outline of the spiral graph may look much the same, for we have found all of the "big trees" from "A *" to "YOUR *". These trees may become bigger, but unless language itself changes we won’t find any more big trees (except of course in foreign languages). The work of those seeking to explain natural language in terms of something more complex than stimulus response will take place beyond our frontier, increasingly in the hinterlands occupied by only the rarest forms of language. Our territory of language already contains the highest population of sentences that people use. Expanding the borders even more we will continue to absorb the stragglers outside, until the very last human critic cannot think of one sentence to "fool" A.L.I.C.E..
February 27 Blobsy 2 RC 6 released!![]() 04/02/2006: Blobsy 2 RC 6 released! Grab it here: Blobsy2 RC6 18/11/2005: This site is under (re)construction. Sections may offer insufficient information or maybe incomplete. Please bear with us while the site is brought up-to-date. Blobsy is an Open Source MSN Messenger bot, designed for easy setup, flexibility and ease of use. It is highly customizable and adding more functionality is extremely easy. It is freely distributable under the GNU General Public License (GPL). The current version of Blobsy currently supports the following features:
Requirements:
MSN Messenger新增两聊天机器人!微软上周发布了两个新的聊天机器人,采取了与众不同的方向推荐给用户。而微软的竞争对手AOL,在本月为用户密友列表自动添加了两个AIM的聊天机器人后,却引起了用户的连连抱怨。
微软这两个聊天机器人是参考微软的Encarta百科全书和BBC的电视列表来回答问题的。用户可以用这项自动化的服务通过说“hello”并且按照提示进行会话。那些有兴趣的用户可以把encarta@conversagent.com和 bbcbackstage@hotmail.com添加到他们的联系人列表中,这样就可以测试这两个聊天机器人了。
来源:huazi817的BLOG http://blog.sina.com.cn/u/45788636010000v2 用.NET开发MSN聊天机器人 - (中文分词) 写在前面: 我不是开发人员,不是高手,就是自己比较爱玩。在技术上,没有什么喜欢摸索的精神,而是喜欢投机取巧。在这篇文章里,你也不能"少劳而获"地通过我的机器人修改出一个自己的机器人,因为自己觉得程序写的比较臭,所以不会open source。但是,如果你对.net或者C#有点了解的话,相信从这篇文章里,你可以找到一切所需的资源,来开发一个自己的,绝对可用的msn机器人。要和我的机器人聊天,可以加tbot01@hotmail.com,名字叫“塔奇克马”,是从动画片攻壳机动队得名。同时,你也可以去http://www.guanqun.com,那里有一个和这个MSN机器人一样的网页聊天机器人,可以先聊聊看,尽量用中文聊。 这不是一篇新手入门的文章,如果你不知道什么是.NET,不了解数据库方面的哪怕是一丁点东西,建议你先看看。同时,也希望真正的高手不要笑话打击我,毕竟一个普通的,非开发人员的电脑爱好者通过摸索,并告诉大家怎样做一个好玩的东西,不是一件错事。 一、为什么要做MSN聊天机器人 1 我能想到的原因 最重要的是因为很好玩。你的MSN机器人说的话,一定体现你的性格(如果你希望这样的话)。当然,这是我的理由,作这个机器人的初衷仅仅是突然有一天自己想做。也许你也希望你的机器人可以帮助你做一些事情,类似一个专家系统或是客服系统等等。 2 现在的MSN聊天机器人 现在MSN机器人有很多,如果你加过MSN机器人,我想你列表上最多的是一个叫做“小布”或者是他兄弟姐妹一大堆的家伙们(http://www.9zi.com),可能基于负载的考虑,每次上线你都可能被他们一家子的一堆加入好友的请求包围。还有一些所谓的“免费短信”机器人,我一直就是做SP的,我直接说,为了不耽误你们赚钱,我不对这种机器人加以什么评论。可以提一下MsgerAI(msgerai@hotmail.com)这个机器人,开发它的这位老兄非常希望做一个可以像人一样具有智能的东西,虽然可能在他有生之年都无法完成,不过我还是祝他成功。毕竟有梦想就是好的,而且这个机器人现在也可以为他完成些工作(http://www.funnyok.net/nlp)。还有一些其他的MSN机器人,比如专门提供信息查询服务的,帮你搜索google的等等。MSN进行时里面有列表(http://www.msning.com),自己去看看就好了。 二、为什么用.NET 其实理由很简单。C#和Java很像,但是Java我实在找不出一个非常好用的,符合自己使用习惯的IDE来。而C#就不同,Vs.NET(http://msdn.microsoft.com/vstudio/) 当然最好用,C# Builder(http://www.borland.com/csharpbuilder/)也不错,连SharpDevelop(http://www.icsharpcode.net/OpenSource/SD/)用起来都相当舒服。所以选择.NET比较好。 另外,.NET在开发上非常方便,只要你有一点点开发基础,用.NET写程序就不是很难。我是站在一个使用者而非开发者的角度,不用去钻研太多技术层面,或是优化的东西,我没那能力也不想进微软研究院。 建议你使用最新版Visual Studio.NET,可以省去很多麻烦的事儿。 同时,.NET开发可以找到的资源也有很多,我们接下来会提。 三、你要一个什么样的聊天机器人 1 开发前的设想 我这里讨论的就是“聊天机器人”这个概念,意思是,他能做的就是陪你聊天。你要有一个程序去“教”他说话,同时要让他明白话语中包含的大概意义,还能够做基本上不怎么离谱的回答。 2 还可以让他做什么 你还可以让他做很多其他的事情,比如查询ip,手机号码,注册号,航班号,或者直接让他去查google,帮你搜索。这些也都不是什么麻烦的事情,只要你想。 四、先让机器人开口说话 不管你的机器人聪不聪明,让他能在MSN上象摸象样地回答是最重要的。所以,你需要有一个MSN帐号,连接到MSN服务器,取得各种服务器的消息,同时发送消息回服务器。 当然,你可以分析MSN的协议(http://www.hypothetic.org/docs/msn/index.php),自己写通讯部分。不过我提过,我是个喜欢投机取巧的人,所以,找个能用的接口用就好了。所以,我找了些MSN的开发接口。 MSNHelper: http://sourceforge.net/projects/msnphelper/ dotMSN: http://members.home.nl/b.geertsema/dotMSN/ 这两个都是为.NET开发的,我用dotMSN,它使用MSNP8协议。注意dotMSN不要用sourceforge上的版本,要用上面给出的地址。 接下来,下载这个例子: http://members.home.nl/b.geertsema/dotMSN/...ple/Example.zip 用vs.net打开,编译,执行。 看懂了吧。登录之后随便双击列表上的某个人,会发送给这个人一句"Hello world!"。你已经可以不通过MSN原来的程序,而直接和人说话了。 这部分的代码是这样的: private void ContactJoined(Conversation sender, ContactEventArgs e) { // someone joined our conversation! remember that this also occurs when you are // only talking to 1 other person. Log this event. Log.Text += e.Contact.Name + " joined the conversation.\r\n"; // now say something back. You can send messages using the Conversation object. sender.SendMessage("Hello world!"); } 意思是当对方加入聊天后,你就给他发一个"Hello world!"的消息过去。这时候如果你列表上的人双击你的名字,也同样会收到一个Hello World!。 五、让机器人懂中文 1 数据库 因为我们要做中文聊天机器人,语料库的大小直接关系到你的机器人是不是聪明。由于自己的习惯,我用了mysql作为存放语料库和中文分词库的数据库。而且mysql速度极快。当然,你要用Access或者Sql Server,完全可以,而且更容易些。.NET调用Mysql的库可以在这里找到MySQL Driver CS http://sourceforge.net/projects/mysqldrivercs/ 2 整句匹配 整句匹配这个概念很简单。聊天嘛,不认识的人一般都会要上来就说“你好”,或者“hi~~”之类的。这种话通常很简单,而且没有什么太多的变化,直接让机器人回答就行了。比如对方说“你好”,机器人看到这个“你好”,就直接回答“你好”,就可以了。或者对方说"88",你可以让机器人说“再见”,或者88什么的。。这就叫整句匹配。就是机器人拿到整个的句子,在库里面一查,啊,库里有这句话怎么回答,挑出一句回答过去,对方不会觉得这个机器人笨。 甚至如果对方说“你好笨”,你让机器人回答“我才不笨呢”,对方一定会觉得,这个机器人还行,还知道别人说他笨。 3 中文分词 一个聊天机器人当然要懂些中文。中文处理的基础就是中文分词。分词是什么?“分词就是将连续的字序列按照一定的规范重新组合成词序列的过程。”这个定义是我抄的。请查阅这篇文章:http://www.hylanda.com/center/knowledge.htm 他们做中文分词应该有一定成绩。国内的分词系统,ICTCLAS做得也比较好。有VC的源代码,可以下来看看。 http://www.nlp.org.cn/project/project.php?proj_id=6 有人会说,这个东西我不懂,我也没研究过。其实我也不懂。只不过,如果不做中文分词,聊天机器人就只能停留在证据匹配的地步。我们可以使用最大匹配法,对聊天机器人接收到的话做简单的分词。关于算法,请参阅詹卫东先生的这个讲义,估计你一看就明白了。 课程名称:中文信息处理基础 http://ccl.pku.edu.cn/doubtfire/Course/Chi...2002_2003_1.htm 下载这个PPT讲义:http://ccl.pku.edu.cn/doubtfire/Course/Chinese%20Information%20Processing/contents/Chapter_07_1.ppt 分词算法不需要太复杂,简单点就好。 另外分词算法需要一个中文分词库。我提供了一个mysql的,这里可以下载。导入到你的mysql里面就可以。其他数据库其实把sql语句简单改改也可以用。 中文分词库下载:http://www.guanqun.com/down/wordlist.rar 4 词语的匹配 仅仅会分词还不够,如果真的要让机器人了解人说的话,肯定需要一些人工智能的算法。我们就是做个机器人玩玩,没必要研究的那么深。人工智能走到现在,太聪明的聊天机器人也少之又少。而且,让专业的研究人员去研究就好了,我们仅仅就是玩玩。所以呢……我们就用一个最简单的办法。我们的方法是,让机器人找这一句话的关键词,这句话大概的词性搭配,再去语料库里面找到符合这样规则的回答的话。 举个简单的例子: 比如对方说: “你真好玩” 我们先用分词算法,把这句话分成 “你 真 好玩”, 然后找出关键词“好玩”。同时把这句话的词性搭配也记录下来。 这样,当找到关键词“好玩”在语料库中的时候,我们再来找是否有类似这这句话词性搭配的回答,如果有,随机回答出一句:“哈哈。。。我就喜欢你这么说。”,这样,可以给聊天者比较好的感觉。 那么问题来了,如何找出关键词呢? 我的方法是……(比较烂,但是通常有效),找出这句话中长度最长的词作为关键词。没有为什么,因为这样速度会快些。如果一句话中所有的词都被扫描成为关键词,再去查库,会出现些匹配上的问题。(不科学,但是通常有效)。 五、让机器人再“聪明”些 1 整句匹配语料库的设计 第一步当然是做你的整句匹配语料库。语料库都要自己写的,不要偷懒。找出别人最常说的话,比如你好谢谢对不起什么的,多放些回答在里面,免得每次回答都是一样的,然后要回答的时候,先写一句sql来查询,如 select * from reply where `key` = '"+sentense+"' order by rand() limit 1 把找到的话直接回复过去就可以了。如果找不到整句匹配,再做分词处理。 2 分词匹配语料库的设计 因为我们分词算法也没有经过什么优化,同时,我们找出关键字的办法也不是那么的好,所以,你给出的回答一定要不那么清晰。说白了就是,回答的话要有些“含糊不清”才可以。目标就是,让人觉得机器人对他说的话已经理解了,回答出来的还算比较“对路”。不要求100%对路,只要有40%以上对路,聊天的人基本就可能会接受。同时,回答的语料库,最好可以引导对方再次回答的时候,可以说出你语料库里面有的,最好是可以整句匹配的句子。 举个好玩的例子: 问题:你是男的还是女的?/你是男的还是女的/你是男的还是女的? (是否有标点符号没关系,我们要记录句子的词性搭配,同时,要对标点符号做些处理) 像这样一句话,我们可以通过分词,找出关键词:“还是”,而且通过判断词性,可以知道,这是一句问句。而且问的是在两种情况之间选择。(当然,我们通过简单的算法,没法知道这句话其实是问性别) 对于这样的问题,你的机器人怎么回答?其实很简单,首先,回答要“对路”,尽量不让人觉得答非所问,至少让人觉得,你的机器人是知道对方在问什么的。所以,我的机器人这样回答: 机器人回答:都是。。。哈哈 因为回答的是聊天用语,而且带点开玩笑的意味,所以会使聊天者觉得,这个机器人还不是那么笨。 这只是一个简单的例子。很多具体的句子还得你自己去分析。当然,语料库越多,机器人懂的就越多,也就越聪明了。 3 匹配不到关键字怎么办 语料库不是很多的情况下,很可能我们的分词算法匹配不到合适的回答来应付。所以我们还要另外做一个语料库,用来在实在匹配不到关键词的时候,进行回答。这样的回答比较需要类似“算卦”的人的回答技巧,因为对方可能说任何话,而我们的机器人不明白。所以,要想办法“蒙混过关”,同时,尽量引导对方向你机器人可能回答的方面说。你可以试着跟“小布”聊聊天,会发现它回答不出来的时候,就会随便挑一句“佛经”来说。 其实最重要的一个技巧就是,学习一下算卦的人说的话,都是云里雾里的,让人摸不到头脑,还觉得可能是对的。我们就要让机器人学习这种技巧,来达到看上去“聪明”的目的。 最后的话: 其实写这样的一个机器人程序很快的,如果熟悉些的话,估计一天应该就可以写出来。我大概用了一天半,还加上准备些语料库的时间。如果你真想做个稍稍“聪明些”的机器人来玩,这篇文章应该可以为你剩下至少3-5个小时的找资料的时间。如果你懒得自己研究,也有别的公司做的只能整句匹配的程序可以下载,自己下一个玩玩也就算了。 来源:zhiming的BLOG http://blog.sina.com.cn/u/5478ba0a0100008j dotnet+xml开发简单聊天机器人 做一个智能的聊天机器人并不容易,我这里只是实现了一个很简易的聊天机器人。
当你和这个机器人聊天的时候,每次机器人会根据你说的话的关键词找到回答的语句。如果找不到就随机的说一句默认语言。数据存储格式是xml。
以下是xml的原文件:
<?xml version="1.0" encoding="UTF-8"?>
<chat> <!--默认的聊天语句--> <default> <content>你在哪里?</content> <content>你还是学生吗?</content> .........
</default>
<!--回答指定关键词的语句序列--> <answer>
<content key="怪"> 不怪</content>
<content key="慢">是啊,慢</content> <content key="喂">什么事?</content> <content key="88">再见</content> <content key="谢">没什么好谢的</content> <content key="滚">我不会滚,我会走</content> ......
<answer>
</chat> ////////////////////////////////////////////////////////////////////
以下是主要的源代码:
Imports System.Xml
Public Class Form1 Inherits System.Windows.Forms.Form #Region " Windows 窗体设计器生成的代码 "
Public Sub New()
MyBase.New() '该调用是 Windows 窗体设计器所必需的。
InitializeComponent() '在 InitializeComponent() 调用之后添加任何初始化
End Sub
'窗体重写 dispose 以清理组件列表。
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub 'Windows 窗体设计器所必需的
Private components As System.ComponentModel.IContainer '注意: 以下过程是 Windows 窗体设计器所必需的
'可以使用 Windows 窗体设计器修改此过程。 '不要使用代码编辑器修改它。 Friend WithEvents RichTextBox1 As System.Windows.Forms.RichTextBox Friend WithEvents TextBox1 As System.Windows.Forms.TextBox Friend WithEvents Button1 As System.Windows.Forms.Button <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(Form1)) Me.RichTextBox1 = New System.Windows.Forms.RichTextBox Me.TextBox1 = New System.Windows.Forms.TextBox Me.Button1 = New System.Windows.Forms.Button Me.SuspendLayout() ' 'RichTextBox1 ' Me.RichTextBox1.Location = New System.Drawing.Point(0, 0) Me.RichTextBox1.Name = "RichTextBox1" Me.RichTextBox1.ReadOnly = True Me.RichTextBox1.Size = New System.Drawing.Size(560, 304) Me.RichTextBox1.TabIndex = 2 Me.RichTextBox1.Text = "" ' 'TextBox1 ' Me.TextBox1.Location = New System.Drawing.Point(0, 312) Me.TextBox1.Name = "TextBox1" Me.TextBox1.Size = New System.Drawing.Size(456, 21) Me.TextBox1.TabIndex = 0 Me.TextBox1.Text = "" ' 'Button1 ' Me.Button1.Location = New System.Drawing.Point(472, 312) Me.Button1.Name = "Button1" Me.Button1.Size = New System.Drawing.Size(72, 24) Me.Button1.TabIndex = 1 Me.Button1.Text = "Enter" ' 'Form1 ' Me.AutoScaleBaseSize = New System.Drawing.Size(6, 14) Me.ClientSize = New System.Drawing.Size(560, 341) Me.Controls.Add(Me.Button1) Me.Controls.Add(Me.TextBox1) Me.Controls.Add(Me.RichTextBox1) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.MaximizeBox = False Me.Name = "Form1" Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.Text = "青蛙王子" Me.ResumeLayout(False) End Sub
#End Region
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
readxml() End Sub Dim xmlFile As String = "./robot.xml" Dim chatList As New ArrayList Dim answerList As New Hashtable Dim random As New System.Random Private Sub readxml()
Try Dim doc As XmlDocument = New XmlDocument doc.Load(xmlFile) Dim nodeList As XmlNodeList Dim root As XmlElement = doc.DocumentElement '--默认的聊天语句-- nodeList = root.SelectNodes("/chat/default/content") Dim node As XmlNode For Each node In nodeList chatList.Add(node.InnerText) Next '回答指定关键词的语句序列-- nodeList = root.SelectNodes("/chat/answer/content") For Each node In nodeList answerList.Add(node.Attributes("key").Value, node.InnerText) Next Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'RichTextBox1.SelectionBullet = True Dim Content$ = TextBox1.Text.Trim If (Content = "") Then RichTextBox1.AppendText("请不要欺骗我的感情,谢谢!" + ControlChars.Lf) Exit Sub End If If (Content.IndexOf(":") <> -1) Then If learnNewWord(Content) Then RichTextBox1.AppendText("我又学会了新的东西,谢谢!" + ControlChars.Lf) End If Exit Sub End If RichTextBox1.AppendText(Content + ControlChars.Lf) Dim aStr$ = getSimilarContent(Content) If (aStr = Nothing) Then Dim i% = random.Next(1, chatList.Count) aStr = chatList.Item(i) End If RichTextBox1.AppendText(aStr.Trim + ControlChars.Lf) RichTextBox1.Refresh() End Sub '得到相似的字符串 Function getSimilarContent(ByVal content As String) As String Dim keys As System.Collections.ICollection = answerList.Keys Dim enumR As System.Collections.IEnumerator = keys.GetEnumerator While (enumR.MoveNext) Dim str$ = enumR.Current If content.Equals(str) Then Return answerList(str) End If End While enumR.Reset() While (enumR.MoveNext) Dim str$ = enumR.Current If (content.IndexOf(str) <> -1) Or (str.IndexOf(content) <> -1) Then Return answerList(str) End If End While Return Nothing End Function '添加新的语句
Function learnNewWord(ByVal content As String) As Boolean Try Dim doc As XmlDocument = New XmlDocument Dim i% = content.IndexOf(":") Dim str1$ = content.Substring(0, i) Dim str2$ = content.Substring(i + 1) doc.Load(xmlFile) Dim elem As XmlElement = doc.CreateElement("content") Dim attr As XmlAttribute = doc.CreateAttribute("key") attr.Value = str1 elem.InnerText = str2 elem.Attributes.Append(attr) '添加新的语句-- Dim root As XmlElement = doc.DocumentElement Dim xmlNode As XmlNode = root.SelectSingleNode("/chat/answer") xmlNode.AppendChild(elem) answerList.Add(str1, str2) doc.Save(xmlFile) Return True Catch ex As Exception MsgBox(ex.Message) Return False End Try End Function Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar.Equals(ControlChars.Cr) Then Button1_Click(Nothing, Nothing) End If End Sub End Class 来自:Cral的BLOG http://blog.sina.com.cn/u/55fd94d3010000s1 |
|
|