Hardware, programming and astronomy tutorials and reviews.

Django, Comet and IRC client

On oreilly.com we can find a simple IRC client written in python. It can receive messages from a IRC channel keeping an open connection. With comet and orbited server we can easily move this script functionality to a web application just by emitting events for every received message.

Here is a modified script from oreilly - irc.py:
import sys
import socket
import string

from pyorbited.simple import Client

orbit = Client()
orbit.event(["django, 0, /chat"],  'start')


s=socket.socket( )
s.connect((HOST, PORT))
s.send("NICK %s
" % NICK)
s.send("USER %s %s bla :%s
s.send('JOIN #django

while 1:
	temp=string.split(readbuffer, "
	readbuffer=temp.pop( )
	for line in temp:
		print line
		orbit.event(["django, 0, /chat"], str(line))
It will go to "django" channel and emit signals to orbited client defined as "django, 0, /chat". In this article I reused the code from orbited chat. So we have views.py:
from pyorbited.simple import Client

from django.shortcuts import render_to_response
from django.conf import settings
from django.http import HttpResponse

users = []
orbit = Client()

def chat_page(request):
	return render_to_response('chat.html', {})
chat.html template:
<!DOCTYPE html>
    <meta charset="utf-8">
    <script src="/_/orbited.js"></script>
    <script type="text/javascript" src="/site_media/ajaxroutine.js"></script>
    <link rel="stylesheet" href="/site_media/chat.css">
    <script src="/site_media/chat.js" charset="utf-8"></script>
    <input type="button" value="Connect" name="nickname" onClick="connect();">
    <div id="box"></div>
    <iframe id="events"></iframe>
function connect()
  Orbited.connect(chat_event, "django", "/chat", "0");

chat_event = function(data) {
  var chat_box = document.getElementById('box');
  var div = window.parent.document.createElement('div');
  div.className = "event";
  div.innerHTML = data;
  chat_box.scrollTop = chat_box.scrollHeight;
And urls.py:
from django.conf.urls.defaults import *

urlpatterns = patterns('',
(r'^site_media/(.*)$', 'django.views.static.serve', {'document_root': '/ścieżka'}),
(r'^/?$', 'chat.views.chat_page'),
Other files like in the chat tutorial. In this case the code is simpler as there is no messages sending and we use one orbited client hardcoded as "django, 0, /chat". Now run orbited server with the same config as for the chat example, start django development server, open http://localhost:8000/ in the browser and click "Connect" button. The web client is ready to run. Now run irc.py and watch the box in the browser. You should get all messages send on django channel in real time :)
It's just a matter of polishing irc.py client to make a full web "HTML based" IRC client (or Jabber for example).

Django web framework tutorials, 14 July 2008, Piotr Maliński

Comment article