C, Java, and Python IRC bot examples

Each of these programs are roughly equivalent implementations of a simple irc bot that connects to a channel, and replies “Someone spoke to me!” when spoken to. Let’s take a look at these examples starting from the higher-level language.

Python:
Very simple and elegant. There’s the built-in connect, send and string constant concatenation methods that make it easy to read and type. The only downside I see is that the recv buffer string cannot have it’s individual characters manipulated (example: str[3] = ‘A’). So when receiving a ping message, we can’t just conveniently replace the ‘I’ with the ‘O’ and send it back, we actually have to do a “PING” to “PONG” string replacement.

import socket
bot_owner = "Jakash3"
nick = "MrRoboto"
chan = "#botfactory"
sock = socket.socket()
sock.connect(("irc.foonetic.net",6667))
sock.send("USER " + nick + " 0 * :" + bot_owner + "\r\n")
sock.send("NICK " + nick + "\r\n")
while 1:
   data = sock.recv(512)
   print data
   if data[0:4] == "PING":
      sock.send(data.replace("PING", "PONG"))
   if data[0]!=':':
      continue
   if data.split(" ")[1] == "001":
      sock.send("MODE " + nick + " +B\r\n")
      sock.send("JOIN " + chan + "\r\n")
   elif data.split(" ")[1] == "PRIVMSG" and data.split(":")[2].startswith(nick):
      sock.send("PRIVMSG " + chan + " :Someone just spoke to me!\r\n")

Java:
Looks a little harder than Python, but the code is more object oriented and explicit.
Java is less ambiguous than Python in a sense that we declare the variables with their type. Java also appears to have a lot of abstract classes and inheritance going on. While Java is more robust with all this OOP functionality, it also shares the same drawback as Python when it comes to strings and character manipulation.

package javaapplication1;
import java.io.IOException;
import java.net.Socket;
import java.lang.String;
import java.io.*;

public class Main {

    static String
            bot_owner = "Jakash3",
            nick = "MrRoboto",
            serv = "irc.foonetic.net",
            chan = "#botfactory";

    public static void main(String[] args) throws IOException {
        String str;
        Socket s = new Socket(serv, 6667);
        BufferedReader i;
        PrintWriter o;
        i = new BufferedReader(new InputStreamReader(s.getInputStream()));
        o = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
        o.print(
                "USER " + nick + " 0 * :" + bot_owner + "\r\n" +
                "NICK " + nick + "\r\n");
        o.flush();
        while (s.isConnected()) {
            str = i.readLine();
            System.out.println(str);
            if (str.startsWith("PING ")) {
                o.print("PONG " + str.substring(5) + "\r\n");
                o.flush();
            }
            if (str.charAt(0) != ':') continue;
            if (str.split(" ")[1].equals("001")) {
                o.print(
                        "MODE " + nick + " +B\r\n" +
                        "JOIN " + chan + "\r\n");
                o.flush();
            } else if (str.split(" ")[1].equals("PRIVMSG")) {
                if (!str.split(":")[2].startsWith(nick)) continue;
                o.print("PRIVMSG " + chan + " :Someone just spoke to me!\r\n");
                o.flush();
            }
        }
        s.close();
    }
    
}

C:
Looks much more complex and is less portable than Python and Java.
C makes up for this by allowing more control over the small details while demonstrating it is just as capable with parsing strings despite not having a sophisticated string manipulation library. C also allows the programmer to manipulate the characters within a string since strings in C are just character arrays with a null terminator.

#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib,"ws2_32.lib")
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char \
	*bot_owner = "Jakash3",
	*nick = "MrRoboto",
	*serv = "irc.foonetic.net",
	*chan = "#botfactory";

int main() {
	int ret;
	char buf[512];
#ifdef _WIN32
	SOCKET sock;
	struct WSAData* wd = (struct WSAData*)malloc(sizeof(struct WSAData));
	ret = WSAStartup(MAKEWORD(2, 0), wd);
	free(wd);
	if (ret) { puts("Error loading Windows Socket API"); return 1; }
#else
	int sock;
#endif
	struct addrinfo hints, *ai;
	memset(&hints, 0, sizeof(struct addrinfo));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	if (ret = getaddrinfo(serv, "6667", &hints, &ai)) {
		puts(gai_strerror(ret));
		return 1;
	}
	sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
	if (ret = connect(sock, ai->ai_addr, ai->ai_addrlen)) {
		puts(gai_strerror(ret));
		return 1;
	}
	freeaddrinfo(ai);
	sprintf(buf, "USER %s 0 * :%s\r\n", nick, bot_owner);
	send(sock, buf, strlen(buf), 0);
	sprintf(buf, "NICK %s\r\n", nick);
	send(sock, buf, strlen(buf), 0);
	while (recv(sock, buf, 512, 0) > 0) {
		fputs(buf, stdout);
		if (!strncmp(buf, "PING ", 5)) {
			buf[1] = 'O';
			send(sock, buf, strlen(buf), 0);
		}
		if (buf[0] != ':') continue;
		if (!strncmp(strchr(buf, ' ') + 1, "001", 3)) {
			sprintf(buf, "MODE %s +B\r\nJOIN %s\r\n", nick, chan);
			send(sock, buf, strlen(buf), 0);
		} else if (!strncmp(strchr(buf, ' ') + 1, "PRIVMSG", 7)) {
			if (strncmp(strchr(buf + 1, ':') + 1, nick, strlen(nick))) continue;
			sprintf(buf, "PRIVMSG %s :Someone just spoke to me!\r\n", chan);
			send(sock, buf, strlen(buf), 0);
		}
	}
#ifdef _WIN32
	closesocket(sock);
	WSACleanup();
#else
	close(sock);
#endif
	return 0;
}

I’m mainly a C and C++ coder. But I’m a complete beginner at Python and Java so there possibly could be better ways to do it than my examples.
The C irc bot example should work in *nix. I haven’t tested it for Windows but it should also compile and run on that too, pm me if it doesn’t.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: