现在我们就开始实现自制MSN机器人梦想。
我们先不要去研究通篇韩文的开发文档。先跟笔者一起来研究一个有趣的机器人,看看它是怎么工作的。然后再一步步深入研究机器人的工作原理。
这是一个有趣的机器人,你对它说什么,它就应什么。我把它叫做应声虫机器人。来看看它的结构:
import java.util.Properties;
import rath.msnm.MSNMessenger;import rath.msnm.SwitchboardSession;import rath.msnm.UserStatus;import rath.msnm.entity.MsnFriend;import rath.msnm.event.MsnListener;import rath.msnm.ftp.VolatileDownloader;import rath.msnm.ftp.VolatileTransferServer;import rath.msnm.msg.MimeMessage;
/**?* MSN应声虫机器人。?* @author Turbo Chen?* @create 2004-7-29?*/public class YesmanRobot{??? public static void main(String[] args)??? {??????? MSNMessenger msn = new MSNMessenger("yourname@hotmail.com", "xxxxxxxx");??????? msn.setInitialStatus(UserStatus.ONLINE);??????? msn.addMsnListener(new YesmanRobotAdapter(msn));??????? msn.login(); ??? }??? ?? }
class YesmanRobotAdapter implements MsnListener{
??? MSNMessenger msn;
??? public YesmanRobotAdapter(MSNMessenger msn)??? {??????? this.msn = msn;??? }
??? /**???? * 收到消息事件。当收到消息时,会自动调用此方法。???? */??? public void instantMessageReceived(SwitchboardSession ss, MsnFriend friend,??????????? MimeMessage mmsg)??? {??????? try??????? {??????????? //发送相同的回复信息给发送者??????????? MimeMessage newMsg = new MimeMessage(??????????????????? "我是MSN应声虫,你说啥我应啥:" + mmsg.getMessage());??????????? newMsg.setKind(MimeMessage.KIND_MESSAGE);??????????? System.out.println(newMsg.getMessage());??????????? msn.sendMessage(friend.getLoginName(), newMsg);??????? } catch (Exception e)??????? {??????????? e.printStackTrace();??????? }??? }
?? ....??? }
其中YesmanRobot是机器人的主类,为了让机器人工作,要先让它登入到MSN才行,相关代码如下:
??????? MSNMessenger msn = new MSNMessenger("yourname@hotmail.com", "xxxxxxxx");??????? msn.setInitialStatus(UserStatus.ONLINE);??????? msn.addMsnListener(new YesmanRobotAdapter(msn));??????? msn.login();
在这里创建了一个MSNMessenger对象,传入登入帐号和密码,使用setInitialStatus方法设置它登入的的状态为'在线',最后是调用login方法登入。
为了使机器人可以达到“应声虫”的功能,在登入之前,我们为它添加了一个监听器。这个监听器是MSNListener的一个实现类。在这里我们实现了一个YesmanRobotAdapter类,它里面只实现一个instantMessageReceived方法,当有消息送给机器人时,会触发此方法,在这个方法里,我们的机器人将对方送过来的消息又送回给了对方。这样就实现的应声虫的功能。
在实际的完整例子中,你会发现MSNListener有多达28个接口,也就是说它除了可以监听收到消息的事件,还提供了许多其它的事件供我们使用。在以后的文章中,我们会慢慢的接触到这些事件。
通过这个应声虫机器人,我们知道,实现自己功能的机器人一点都不难。只需要在instantMessageReceived方法中处理收到的消息并回应,就变成你自己的机器人了。在后面的内容中,我们会更深入机器人内部,看看它的工作原理。
发表于 @ 2004年07月29日 14:11:00|评论(loading...)|编辑