Creating MSN messenger bot with ruby.
July 8th, 2009If you are willing to make MSN messenger bot program with ruby, there is a good libray, rubymsn. Though it doesn’t seem to be active now, you can download sources and use them. Throughout this article, I will introduce rubymsn library to share you what I’ve learned.
First, you can refer to MSN messenger protocol page.
Login to MSN messenger
Just create MSNConnection with MSN messenger id and password.
@conn = MSNConnection.new(msn[:id], msn[:password])
@conn.signed_in = lambda {
@conn.change_nickname "Twitter Bot"
}
signed_in proc will be executed after successful login. Used change_nickname to change nickname as ‘Twitter Bot’. It does not do anything untils @conn.start is called, though.
Receiving a message and Reply
Use new_chat_session proc to indicate what to do when the session between the bot and a user is created.
@conn.new_chat_session = lambda do |tag, session|
TwitterBot.info "=> new chat session created with tag '#{tag}'!"
session.message_received = lambda do |sender, message|
TwitterBot.info "=> #{sender} says: #{message}"
session.say "hello"
end
session.start
end
@conn.start
message_received proc is called when the message from a user arrives. Possible procs for the session are :message_received, :session_started, :session_ended, and :participants_updated
To reply or send a message to the user, use session.say.
The tag is used to a key to access the users’ session. A session is stored @conn.chatsessions as a hash. So a session can be retrieved like below.
session = @conn.chatsessions[tag]
How to know the state of friends.
A user has several states depending on his connection such as Online, Offline, Busy, etc. The state of user can be checked with @conn.contactlists. The following is how to know whether a user is offline.
def offline?(email) contact = @conn.contactlists["FL"][email] contact ? contact.status.code == "FLN" : true end
Sending a message to the user
In order to send a message to the friend, you have to get or create the session first. To create a session, several handshake messages are needed. This handshake is triggered by @conn.start_chat method.
@conn.start_chat(tag, email)
A tag can be anything unique. An email is the email address of the user to chat. The session is not created immediately, it takes some time until the handshake finished. How to know when the session is created? A session_started proc is called as soon as the session is created.
@conn.new_chat_session = lambda do |tag, session|
...
session.session_started = lambda do
msg = get_message(tag) # assume that a message is possible to get with tag.
session.say msg
session.close
end
session.start
end
When the session is started, A message is sent. Above code assumes that a message is stored before and can be retrieved with a tag.
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=5af1279d-25bd-4336-9e71-1d7d017b9c86)