PDA

Archiv verlassen und diese Seite im Standarddesign anzeigen : C++ Simple IRC Bot



-=Player=-
01.11.2008, 20:30
Achtung: Nicht von mir!


#include <iostream>

#include <errno.h>

#include <cstring>

#include <netdb.h>

#include <sys/types.h>

#include <netinet/in.h>

#include <sys/socket.h>

#include <unistd.h>



using namespace std;



// substr is a clone of PHP's substr that I wrote



char *substr (const char *str, int start, int end) {

char *sub = new char[strlen(str)];

start -=1 ;



for(int i = 0;start<end;i += 1) {

sub[i] = str[start];

start += 1;

}

sub[end] = '\0';



return sub;

}



int main() {



struct hostent *he;

struct sockaddr_in their_addr;

int sockfd;

char msg[512];

char buffer[512];

int length;

int stay = 1;



cout << "SimpleBot" << endl << "A Simple IRC Bot" << endl;



// Connect the socket to the server

// lot of this will look fimiliar.



if ((he=gethostbyname("irc.quickstrike.org")) == NULL) {

perror("gethostbyname");

exit(1);

}



if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {

perror("socket");

exit(1);

}



their_addr.sin_family = AF_INET;

their_addr.sin_port = htons(6667);

their_addr.sin_addr = *((struct in_addr *)he->h_addr);

memset(&(their_addr.sin_zero), '\0', ;



if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) {

perror("connect");

exit(1);

}



// Time to register with USER and NICK



strcpy(msg,"USER simple simple simple :SimpleBot Example>br /<NICK SimpleIRC>br /<");



if (send(sockfd, msg, strlen(msg), 0) == -1) {

perror("send");

}



// Ok, now comes the fun part. Before you are able to do anything

// else you need to reply to a ping with a pong. Since we want

// to be able to respond again next time we get pinged, we'll

// start the loop here.



while (stay) {

// get info from the server, put it in buffer

if ((length=recv(sockfd, buffer, 511, 0)) == -1) {

perror("recv");

exit(1);

}

buffer[length] = '\0';



// Go through buffer looking for ping, or other messages.



for (int i = 0; buffer[i] != '\0'; i += 1) {



// do we have "PING"?

if (strncmp(substr(buffer,i,i+4),"PING",4) == 0) {

// reply to ping with pong, also joining #testchan

sprintf(msg, "PONG %s>br /<join :#testchan>br /<",substr(buffer,i+6,i+13));



if (send(sockfd, msg, strlen(msg), 0) == -1) {

perror("send");

}

}

// do we have a "hello"?

// note: in a real bot you would definatly want to extract the

// user's message and work with that.

if (strncmp(substr(buffer,i,i+5),"hello",5) == 0) {

// send bye! to #testchan, then quit

strcpy(msg, "PRIVMSG #testchan :bye!>br /<QUIT>br /<");



if (send(sockfd, msg, strlen(msg), 0) == -1) {

perror("send");

}



stay = 0; // leave our while()

}



}



}



close(sockfd);



return 0;

}