forked from Themaister/simple-irc-bot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.c
111 lines (92 loc) · 2.14 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/* Bradley Rasmussen
*
* forked from maister for educational purposes
*
* TO DO:
* Learn backend magic
* See what it would take to make the bot modular. Multiple servers & channels
* Add functionality
* Make code more "secure"
*/
#include "socket.h"
#include "irc.h"
#include "cmd.h"
#include <string.h>
#define OUTPUT "/dev/stdout"
#define CONFIG "config"
char *getln(FILE *conf);
void init_conf(irc_t *irc, FILE * conf);
int main(int argc, char **argv) {
FILE * conf;
conf = fopen(CONFIG, "r");
irc_t irc;
irc_set_output(&irc, OUTPUT);
irc.chanlist = NULL;
init_conf(&irc, conf);
while ( irc_handle_data(&irc) >= 0 );
irc_close(&irc);
fclose(conf);
return 0;
}
void init_conf (irc_t * irc, FILE * conf) {
char *servname = NULL, *servport = NULL, *line = NULL, *tok = NULL, ch = 0;
int state = 0;
do {
line = getln(conf);
ch = 0;
tok = NULL;
if (line != NULL)
tok = strtok(line, " :");
if (tok != NULL) {
if (strcmp(tok, "") == 0)
tok = NULL;
if (tok != NULL)
ch = tok[0];
}
if (ch == '{') {
state = 1;
}
else if (ch == '}') {
state = 0;
}
else if (state == 0 && tok != NULL) {
servname = tok;
servport = strtok(NULL, " :");
if ( irc_connect(irc, servname, servport) < 0 ) {
fprintf(stderr, "Connection to %s:%sfailed.\n", servname, servport);
}
else {
if ( irc_login(irc, BOTNAME) < 0 ) {
fprintf(stderr, "Couldn't log in.\n");
}
}
}
else if (state == 1 && ch == '#') {
char *chan = malloc(strlen(tok)+1);
strcpy(chan, tok);
irc_join(irc, chan);
}
if (line != NULL) {
free(line);
}
} while (line != NULL);
}
// This method is kind of cludgy for making dynamic strings
// Does not cut whitespace
char* getln(FILE *file) {
char *line = NULL, tmp[MSG_LEN];
size_t index = 0;
int ch = EOF;
while (ch) {
ch = getc(file);
// Check if we need to stop.
if (ch == EOF)
return NULL;
if (ch == '\n')
ch = 0;
tmp[index++] = ch;
}
line = malloc(strlen(tmp)+1);
strcpy(line, tmp);
return line;
}