Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS 

Post a message to identi.ca using XMPP via HTTP

This Ruby code posts a message to identi.ca using XMPP which uses a simple web server.

#!/usr/bin/ruby

require 'rubygems'  
require 'socket'
require 'open-uri'
require 'xmpp4r-simple'

server = TCPServer.new('127.0.0.1', 9090)
messenger = Jabber::Simple.new('my-bot@gmail.com', "bot-password")

while (session = server.accept)
  request = session.gets
  project = request[/(\w+)\?msg=(.*) HTTP\/1.1/,1]
  msg = URI.unescape($2)

  puts request
  session.print "HTTP/1.1 200/OK\rContent-type: text/html\r\n\r\n"
  session.print "<html><head><title>Response from Jeeves</title></head>\r\n"
  session.print "<body>"

  if project != '' and msg != '' then
    case project
      when 'identica'
        messenger.deliver("update@identi.ca", msg)
    else
      puts "Project #{project} wasn't found on this server"
    end
  end
  session.print URI.unescape(request)

  session.print "</body></html>"
  session.close
end


To post the message you would type your message within the browser URL e.g. http://127.0.0.1:9090/identica?msg=just%20testing%20xmpp4r-simple%20from%20tcpserver1

Make your own IM bot in Ruby

The following code was copied from the article 'Make your own IM bot in Ruby, and interface it with your Rails app' [rubypond.com].

installation:
git clone git://github.com/ln/xmpp4r.git xmpp4r
cd xmpp4r
rake gem:install
sudo gem install xmpp4r-simple


connect:
require 'rubygems'  
require 'xmpp4r-simple'
messenger = Jabber::Simple.new('my-bot@gmail.com', "bot-password")

send:
messenger.deliver("a-real-person@gmail.com", "Why hello there Mr. Person, your bot is here now!") 

listen:
while true
  messenger.received_messages do |msg|  
    puts msg.body  
    messenger.deliver("a-real-person@gmail.com", "Got your message, thanks!")  
  end  
  sleep 2  
end

at your service:
require 'rubygems'  
require 'xmpp4r-simple'
messenger = Jabber::Simple.new('my-bot@gmail.com', "bot-password")
while true
  messenger.received_messages do |msg|
    user = User.find_by_im_name(msg.from)
    if user
      case msg.body
      when /^help /i
        messenger.deliver(msg.from, "Valid commands are......")  
      when /^status /i
        user.status = msg.body.sub(/^status /i)
        user.save
        messenger.deliver(msg.from, "Thanks #{user.first_name}, your status has been updated")  
      when /^balance\?/i
        messenger.deliver(msg.from, "#{user.first_name}, your current remaining balance is #{user.remaining_balance}")  
      else
        messenger.deliver(msg.from, "Sorry #{user.first_name}, I didn't understand that. Message me with 'help' for a list of commands")  
      end
    else
      messenger.deliver(msg.from, "Sorry, but we've not got this account registered on our system. Sign-up or update your details at http://www.mysite.com/")  
    end    
  end  
  sleep 2  
end

Using Google Talk as a distributed Twitter client

A distributed Twitter client in the spirit of:
http://blog.labnotes.org/2008/05/05/distributed-twitter-client-in-20-lines-of-code/
#!/usr/bin/env python
import xmpp
import sys

class DistTwit(object):
    def __init__(self,user,pwd,callbacks=None,showself=False):
        self._my_jid = xmpp.protocol.JID(user+"/distwit.py")
        self._client = xmpp.Client(self._my_jid.getDomain(), debug=[])
        if not callbacks:
            self._callbacks=[]
        else:
            self._callbacks=callbacks
        self.showself=showself

        self._connect()
        self._auth(pwd)
        self._run()

    def _connect(self):
        print "Connecting..."
        if self._client.connect(server=('talk.google.com',5223)) == "":
            raise ConnectionException()

    def _auth(self,pwd):
        print "Authenticating..."
        if self._client.auth(self._my_jid.getNode(),pwd) == None:
            raise AuthException()

    def add_callback(self,func):
        self._callbacks.append(func)

    def _run(self):
        self._client.sendInitPresence()
        self._roster = self._client.getRoster()

        self._client.RegisterHandler('presence', self._presence)
        quit=False
        while not quit:
            try:
                self._client.Process(1)
            except KeyboardInterrupt:
                quit=True

    def _presence(self,conn,msg):
        jid=xmpp.protocol.JID(msg.getFrom())
        name=self._roster.getName(jid.getNode()+"@"+jid.getDomain())

        if not name:
            name=jid.getNode()+"@"+jid.getDomain()

        if not self.showself and name == self._my_jid.getNode()+"@"+self._my_jid.getDomain():
            return

        status = msg.getStatus()
        show = msg.getShow()

        if not msg.getPriority():
            status="Signed out"
        elif not status and show:
            status="("+msg.getShow()+")"
        elif show and status:
            status="("+msg.getShow()+") "+status

        for f in self._callbacks:
            f(name,status)
        
class ConnectionException(Exception):
    def __init__(self):
        pass
    def __str__(self):
        return "Error connecting to talk.google.com"

class AuthException(Exception):
    def __init__(self):
        pass
    def __str__(self):
        print "Error authenticating to talk.google.com"


if __name__=="__main__":
    def callback(name,status):
        print "%s: %s" % (name,status)
    
    DistTwit(sys.argv[1],sys.argv[2],callbacks=[callback])

Sending a message using XMPP and Ruby

This Ruby code shows how to send an instant message through XMPP [wikipedia.org] using XMPP4R [gna.org]. Source code origin: Ruby and XMPP/Jabber Part 2: Logging in and sending simple messages [famundo.com].

Preparation
- Installed eJabberd on my Gentoo server
- Created 2 user accounts using Pidgin Internet Messenger on my Ubuntu desktop.
- Tested sending messages using Jabber Instant Messaging (Gabber) and Pidgin Internet Messenger.

Installation
gem install xmpp4r

What we will need
require 'rubygems'
require 'xmpp4r'
include Jabber

Logging in
jid = JID::new('yourname@yourdomain.com/Testing')
password = 'yourpassword'
cl = Client::new(jid)
cl.connect
cl.auth(password)

Sending a simple message
to = "user2@yourdomain.com"
subject = "XMPP4R test"
body = "Hi, this is my first try from XMPP4R!!!"
m = Message::new(to, body).set_type(:normal).set_id('1').set_subject(subject)
cl.send m

References:
- Building a Twitter Agent with Ruby and Rails [rubyinside.com]
- http://gentoo-wiki.com/Ejabberd

* update 15:45 18-Feb-08 *
Here's a simpler example I found from Liminal Existence: Announcing Jabber::Simple [romeda.org]

sudo gem install xmpp4r-simple
require 'xmpp4r-simple'

jabber = Jabber::Simple.new('yourname@yourdomain.com', 'yourpassword')
jabber.deliver("user1@yourdomain.com", "Hey! I'm thinking of going Vegetarian - Any suggestions?")


see also: IM Integration With XMPP4r : Part 2 [rubyfleebie.com]

Send message with Google Talk

Copied from Jkx's code here
http://www.larsen-b.com/Article/214.html
import xmpp

login = 'Your.Login' # @gmail.com 
pwd   = 'YourPassword'

cnx = xmpp.Client('gmail.com')
cnx.connect( server=('talk.google.com',5223) )
cnx.auth(login,pwd, 'botty')

cnx.send( xmpp.Message( "YourFriend@gmail.com" ,"Hello World form Python" ) )
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS