1 /* mod-python.c - Script module for x3
2 * Copyright 2003-2004 Martijn Smit and srvx Development Team
3 * Copyright 2005-2006 X3 Development Team
5 * This file is part of x3.
7 * x3 is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with srvx; if not, write to the Free Software Foundation,
19 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
23 #ifdef WITH_PYTHON /* just disable this file if python doesnt exist */
39 * - Impliment most of proto-p10 irc_* commands for calling from scripts
40 * - Impliment functions to look up whois, channel, account, and reg-channel info for scripts
41 * - Impliment x3.conf settings for python variables like include path, etc.
42 * - modpython.py calls for everything you can reg_ a handler for in x3
43 * - Some kind of system for getting needed binds bound automagicaly to make it easier
44 * to run peoples scripts and mod-python in general.
45 * - An interface to reading/writing data to x3.db. Maybe generic, or attached to account or channel reg records?
48 static const struct message_entry msgtab
[] = {
49 { "PYMSG_RELOAD_SUCCESS", "Reloaded Python scripts successfully." },
50 { "PYMSG_RELOAD_FAILED", "Error reloading Python scripts." },
51 { "PYMSG_RUN_UNKNOWN_EXCEPTION", "Error running python: unknown exception." },
52 { "PYMSG_RUN_EXCEPTION", "Error running python: %s: %s." },
53 { NULL
, NULL
} /* sentenal */
56 #define MODPYTHON_CONF_NAME "modules/python"
60 char const* scripts_dir
;
61 char const* main_module
;
64 static struct log_type
*PY_LOG
;
65 const char *python_module_deps
[] = { NULL
};
66 static struct module *python_module
;
68 PyObject
*base_module
= NULL
; /* Base python handling library */
69 PyObject
*handler_object
= NULL
; /* instanciation of handler class */
72 extern struct userNode
*global
, *chanserv
, *opserv
, *nickserv
, *spamserv
;
74 /* ---------------------------------------------------------------------- *
75 Some hooks you can call from modpython.py to interact with the
76 service, and IRC. These emb_* functions are available as _svc.*
81 emb_dump(UNUSED_ARG(PyObject
*self
), PyObject
*args
)
83 /* Dump a raw string into the socket
84 usage: _svc.dump(<P10 string>)
91 if(!PyArg_ParseTuple(args
, "s:dump", &buf
))
94 safestrncpy(linedup
, buf
, sizeof(linedup
));
96 if(parse_line(linedup
, 1)) {
100 PyErr_SetString(PyExc_Exception
, "invalid protocol message");
104 return Py_BuildValue("i", ret
);
108 emb_send_target_privmsg(UNUSED_ARG(PyObject
*self
), PyObject
*args
)
111 usage: _svc.send_target_privmsg(<servicenick_from>, <nick_to>, <message>)
118 struct service
*service
;
121 if(!PyArg_ParseTuple(args
, "sss:reply", &servicenick
, &channel
, &buf
))
124 if (buf
== NULL
|| strlen(buf
) == 0) {
125 PyErr_SetString(PyExc_Exception
, "invalid empty message");
129 if(!(service
= service_find(servicenick
))) {
130 PyErr_SetString(PyExc_Exception
, "no such service nick");
134 ret
= send_target_message(5, channel
, service
->bot
, "%s", buf
);
135 return Py_BuildValue("i", ret
);
139 emb_send_target_notice(UNUSED_ARG(PyObject
*self
), PyObject
*args
)
142 usage: _svc.send_target_notice(<servicenick_from>, <nick_to>, <message>)
149 struct service
*service
;
151 if(!PyArg_ParseTuple(args
, "sss:reply", &servicenick
, &target
, &buf
))
154 if (buf
== NULL
|| strlen(buf
) == 0) {
155 PyErr_SetString(PyExc_Exception
, "invalid empty message");
159 if(!(service
= service_find(servicenick
))) {
160 PyErr_SetString(PyExc_Exception
, "no such service nick");
164 ret
= send_target_message(4, target
, service
->bot
, "%s", buf
);
166 return Py_BuildValue("i", ret
);
170 pyobj_from_usernode(struct userNode
* user
) {
173 PyObject
* pChanList
= PyTuple_New(user
->channels
.used
);
175 for (n
=0; n
< user
->channels
.used
; n
++) {
176 mn
= user
->channels
.list
[n
];
177 PyTuple_SetItem(pChanList
, n
, Py_BuildValue("s", mn
->channel
->name
));
180 return Py_BuildValue("{"
184 "s: s, " /* hostname */
186 "s: s, " /* fakehost */
187 "s: s, " /* sethost */
188 "s: s, " /* crypthost */
189 "s: s, " /* cryptip */
190 #ifdef WITH_PROTOCOL_P10
191 "s: s, " /* numeric */
192 #endif /* WITH_PROTOCOL_P10 */
194 "s: i, " /* no_notice */
196 "s: s, " /* version_reply */
197 "s: s, " /* account */
198 "s: O}", /* channels */
200 "ident", user
->ident
,
202 "hostname", user
->hostname
,
203 "ip", irc_ntoa(&user
->ip
),
204 "fakehost", user
->fakehost
,
205 "sethost", user
->sethost
,
206 "crypthost", user
->crypthost
,
207 "cryptip", user
->cryptip
,
208 #ifdef WITH_PROTOCOL_P10
209 "numeric", user
->numeric
,
210 #endif /* WITH_PROTOCOL_P10 */
212 "no_notice", user
->no_notice
,
214 "version_reply", user
->version_reply
,
215 "account", user
->handle_info
? user
->handle_info
->handle
: NULL
,
216 "channels", pChanList
);
220 emb_get_user(UNUSED_ARG(PyObject
*self
), PyObject
*args
)
222 /* Get a python object containing everything x3 knows about a user, by nick.
223 usage: _svc.get_user(<nick>)
226 struct userNode
*user
;
228 if(!PyArg_ParseTuple(args
, "s", &nick
))
231 if(!(user
= GetUserH(nick
))) {
232 PyErr_SetString(PyExc_Exception
, "no such user");
236 return pyobj_from_usernode(user
);
240 emb_get_channel(UNUSED_ARG(PyObject
*self
), PyObject
*args
)
242 /* Returns a python dict object with all sorts of info about a channel.
243 usage: _svc.get_channel(<name>)
246 struct chanNode
*channel
;
248 PyObject
*pChannelMembers
;
249 PyObject
*pChannelBans
;
250 PyObject
*pChannelExempts
;
253 if(!PyArg_ParseTuple(args
, "s", &name
))
256 if(!(channel
= GetChannel(name
))) {
257 PyErr_SetString(PyExc_Exception
, "unknown channel");
261 /* build tuple of nicks in channel */
262 pChannelMembers
= PyTuple_New(channel
->members
.used
);
263 for(n
=0;n
< channel
->members
.used
;n
++) {
264 struct modeNode
*mn
= channel
->members
.list
[n
];
265 PyTuple_SetItem(pChannelMembers
, n
, Py_BuildValue("s", mn
->user
->nick
));
268 /* build tuple of bans */
269 pChannelBans
= PyTuple_New(channel
->banlist
.used
);
270 for(n
=0; n
< channel
->banlist
.used
;n
++) {
271 struct banNode
*bn
= channel
->banlist
.list
[n
];
272 PyTuple_SetItem(pChannelBans
, n
,
273 Py_BuildValue("{s:s,s:s,s:i}",
280 /* build tuple of exempts */
281 pChannelExempts
= PyTuple_New(channel
->exemptlist
.used
);
282 for(n
=0; n
< channel
->exemptlist
.used
;n
++) {
283 struct exemptNode
*en
= channel
->exemptlist
.list
[n
];
284 PyTuple_SetItem(pChannelExempts
, n
,
285 Py_BuildValue("{s:s,s:s,s:i}",
292 return Py_BuildValue("{s:s,s:s,s:s,s:i"
293 ",s:i,s:i,s:O,s:O,s:O}",
295 "name", channel
->name
,
296 "topic", channel
->topic
,
297 "topic_nick", channel
->topic_nick
,
298 "topic_time", channel
->topic_time
,
300 "timestamp", channel
->timestamp
,
301 "modes", channel
->modes
,
302 "members", pChannelMembers
,
303 "bans", pChannelBans
,
304 "exempts", pChannelExempts
309 emb_get_account(UNUSED_ARG(PyObject
*self
), PyObject
*args
)
311 /* Returns a python dict object with all sorts of info about an account.
312 usage: _svc.get_account(<account name>)
315 struct handle_info
*hi
;
318 if(!PyArg_ParseTuple(args
, "s", &name
))
321 hi
= get_handle_info(name
);
325 return Py_BuildValue("{s:s,s:i,s:s,s:s,s:s"
328 "account", hi
->handle
,
329 "registered", hi
->registered
,
330 "last_seen", hi
->lastseen
,
331 "infoline", hi
->infoline
? hi
->infoline
: "",
332 "email", hi
->email_addr
? hi
->email_addr
: "",
334 "fakehost", hi
->fakehost
? hi
->fakehost
: "",
335 "last_quit_host", hi
->last_quit_host
338 /* users online authed to this account */
340 /* nicks (nickserv nets only?) */
348 emb_get_info(UNUSED_ARG(PyObject
*self
), UNUSED_ARG(PyObject
*args
))
350 /* return some info about the general setup
351 * of X3, such as what the chanserv's nickname
356 return Py_BuildValue("{s:s,s:s,s:s,s:s,s:s}",
357 "chanserv", chanserv
? chanserv
->nick
: "ChanServ",
358 "nickserv", nickserv
?nickserv
->nick
: "NickServ",
359 "opserv", opserv
?opserv
->nick
: "OpServ",
360 "global", global
?global
->nick
: "Global",
361 "spamserv", spamserv
?spamserv
->nick
: "SpamServ");
365 emb_log_module(UNUSED_ARG(PyObject
*self
), PyObject
*args
)
367 /* a gateway to standard X3 logging subsystem.
368 * level is a value 0 to 9 as defined by the log_severity enum in log.h.
369 * LOG_INFO is 3, LOG_WARNING is 6, LOG_ERROR is 7.
371 * for now, all logs go to the PY_LOG log. In the future this will change.
378 if(!PyArg_ParseTuple(args
, "is", &level
, &message
))
381 log_module(PY_LOG
, level
, "%s", message
);
383 return Py_BuildValue("i", ret
);
386 static PyMethodDef EmbMethods
[] = {
387 /* Communication methods */
388 {"dump", emb_dump
, METH_VARARGS
, "Dump raw P10 line to server"},
389 {"send_target_privmsg", emb_send_target_privmsg
, METH_VARARGS
, "Send a message to somewhere"},
390 {"send_target_notice", emb_send_target_notice
, METH_VARARGS
, "Send a notice to somewhere"},
391 {"log_module", emb_log_module
, METH_VARARGS
, "Log something using the X3 log subsystem"},
392 //TODO: {"exec_cmd", emb_exec_cmd, METH_VARARGS, "execute x3 command provided"},
393 // This should use environment from "python command" call to pass in, if available
397 //TODO: {"gline", emb_gline, METH_VARARGS, "gline a mask"},
398 //TODO: {"ungline", emb_ungline, METH_VARARGS, "remove a gline"},
399 //TODO: {"kick", emb_kick, METH_VARARGS, "kick someone from a channel"},
400 //TODO: {"channel_mode", emb_channel_mode, METH_VARARGS, "set modes on a channel"},
401 //TODO: {"user_mode", emb_user_mode, METH_VARARGS, "Have x3 set usermodes on one of its own nicks"},
403 //TODO: {"get_config", emb_get_config, METH_VARARGS, "get x3.conf settings into a nested dict"},
404 //TODO: {"config_set", emb_config_set, METH_VARARGS, "change a config setting 'on-the-fly'."},
406 //TODO: {"timeq_add", emb_timeq_new, METH_VARARGS, "some kind of interface to the timed event system."},
407 //TODO: {"timeq_del", emb_timeq_new, METH_VARARGS, "some kind of interface to the timed event system."},
408 /* Information gathering methods */
409 {"get_user", emb_get_user
, METH_VARARGS
, "Get details about a nickname"},
410 {"get_channel", emb_get_channel
, METH_VARARGS
, "Get details about a channel"},
411 {"get_account", emb_get_account
, METH_VARARGS
, "Get details about an account"},
412 {"get_info", emb_get_info
, METH_VARARGS
, "Get various misc info about x3"},
413 /* null terminator */
414 {NULL
, NULL
, 0, NULL
}
418 /* ------------------------------------------------------------------------------------------------ *
419 Thes functions set up the embedded environment for us to call out to modpython.py class
423 void python_log_module() {
424 /* Attempt to convert python errors to x3 log system */
425 PyObject
*exc
, *tb
, *value
, *tmp
;
426 char *str_exc
= "NONE";
427 char *str_value
= "NONE";
428 char *str_tb
= "NONE";
430 PyErr_Fetch(&exc
, &value
, &tb
);
433 if((tmp
= PyObject_Str(exc
)))
434 str_exc
= PyString_AsString(tmp
);
437 if((tmp
= PyObject_Str(value
)))
438 str_value
= PyString_AsString(tmp
);
441 if((tmp
= PyObject_Str(tb
)))
442 str_tb
= PyString_AsString(tmp
);
445 /* Now restore it so we can print it (just in case)
446 * (should we do this only when running in debug mode?) */
447 PyErr_Restore(exc
, value
, tb
);
448 PyErr_Print(); /* which of course, clears it again.. */
450 log_module(PY_LOG
, LOG_WARNING
, "PYTHON error: %s, value: %s", str_exc
, str_value
);
452 /* TODO: get the traceback using the traceback module via C api so we can add it to the X3 logs. See
453 * http://mail.python.org/pipermail/python-list/2003-March/192226.html */
454 // (this doesnt work, str_tb is just an object hashid) log_module(PY_LOG, LOG_INFO, "PYTHON error, traceback: %s", str_tb);
458 PyObject
*python_build_handler_args(size_t argc
, char *args
[], PyObject
*pIrcObj
) {
459 /* Sets up a python tuple with passed in arguments, prefixed by the Irc instance
460 which handlers use to interact with c.
461 argc = number of args
463 pIrcObj = instance of the irc class
466 PyObject
*pArgs
= NULL
;
468 pArgs
= PyTuple_New(argc
+ 1);
470 PyTuple_SetItem(pArgs
, i
++, pIrcObj
);
474 for(n
= 0; n
< argc
; ++n
) {
475 pValue
= PyString_FromString(args
[n
]);
478 log_module(PY_LOG
, LOG_INFO
, "Unable to convert '%s' to python string", args
[n
]);
481 PyTuple_SetItem(pArgs
, n
+i
, pValue
);
487 PyObject
*python_build_args(size_t argc
, char *args
[]) {
488 /* Builds the passed in arguments into a python argument tuple.
489 argc = number of args
493 PyObject
*pArgs
= NULL
;
496 pArgs
= PyTuple_New(argc
);
498 for(i
= 0; i
< argc
; ++i
) {
499 pValue
= PyString_FromString(args
[i
]);
502 log_module(PY_LOG
, LOG_INFO
, "Unable to convert '%s' to python string", args
[i
]);
505 PyTuple_SetItem(pArgs
, i
, pValue
);
512 PyObject
*new_irc_object(char *command_service
, char *command_caller
, char *command_target
) {
513 /* Creates a new instance of the irc class (from modpython.py) which is initalized
514 with current environment details like which service were talking to.
515 command_service = which service we are talking to, or empty string if none
516 command_caller = nick of user generating message, or empty string if none
517 command_target = If were reacting to something on a channel, this will
518 be set to the name of the channel. Otherwise empty
520 PyObject
*pIrcArgs
= NULL
;
524 log_module(PY_LOG
, LOG_INFO
, "Attempting to instanciate irc class; %s %s %s", command_service
, command_caller
, command_target
);
525 pIrcClass
= PyObject_GetAttrString(base_module
, "irc");
526 /* pIrcClass is a new reference */
527 if(pIrcClass
&& PyCallable_Check(pIrcClass
)) {
529 char *ircargs
[] = {command_service
, command_caller
, command_target
};
532 pIrcArgs
= python_build_args(3, ircargs
);
533 pIrcObj
= PyObject_CallObject(pIrcClass
, pIrcArgs
);
535 log_module(PY_LOG
, LOG_ERROR
, "IRC Class failed to load");
539 if(pIrcArgs
!= NULL
) {
542 Py_DECREF(pIrcClass
);
546 /* need to free pIrcClass here if it WAS found but was NOT callable? */
547 log_module(PY_LOG
, LOG_ERROR
, "Unable to find irc class");
552 int python_call_handler(char *handler
, char *args
[], size_t argc
, char *command_service
, char *command_caller
, char *command_target
) {
553 /* This is how we talk to modpython.c. First a new instance of the irc class is created using these
554 arguments to setup the current environment. Then the named method of the handler object is called
555 with the givin arguments.
562 log_module(PY_LOG
, LOG_INFO
, "attempting to call handler %s.", handler
);
563 if(base_module
!= NULL
&& handler_object
!= NULL
) {
564 pIrcObj
= new_irc_object(command_service
, command_caller
, command_target
);
566 log_module(PY_LOG
, LOG_INFO
, "Can't get irc object. Bailing.");
570 pArgs
= python_build_handler_args(argc
, args
, pIrcObj
);
571 pMethod
= PyObject_GetAttrString(handler_object
, handler
);
572 if(pMethod
&& PyCallable_Check(pMethod
)) {
573 /* Call the method, with the arguments */
574 pValue
= PyObject_CallObject(pMethod
, pArgs
);
580 ret
= PyInt_AsLong(pValue
);
581 if(ret
== -1 && PyErr_Occurred()) {
583 log_module(PY_LOG
, LOG_INFO
, "error converting return value of handler %s to type long. ", handler
);
587 log_module(PY_LOG
, LOG_INFO
, "handler %s was run successfully, returned %d.", handler
, ret
);
594 /* TODO: instead of print errors, get them as strings
595 * and deal with them with normal x3 log system. */
596 log_module(PY_LOG
, LOG_WARNING
, "call to handler %s failed", handler
);
604 else { /* couldn't find handler methed */
606 /* Free pMethod if it was found but not callable? */
607 log_module(PY_LOG
, LOG_ERROR
, "Cannot find handler %s.", handler
);
612 else { /* No base module.. no python? */
613 log_module(PY_LOG
, LOG_INFO
, "Cannot handle %s, Python is not initialized.", handler
);
618 PyObject
*python_new_handler_object() {
619 /* Create a new instance of the handler class.
620 This is called during python initilization (or reload)
621 and the result is saved and re-used.
623 PyObject
*pHandlerClass
, *pHandlerObj
;
625 log_module(PY_LOG
, LOG_INFO
, "Attempting to instanciate python class handler");
626 pHandlerClass
= PyObject_GetAttrString(base_module
, "handler");
627 /* Class is a new reference */
628 if(pHandlerClass
&& PyCallable_Check(pHandlerClass
)) {
629 /*PyObject *pValue; */
631 pHandlerObj
= PyObject_CallObject(pHandlerClass
, NULL
);
632 if(pHandlerObj
!= NULL
) {
633 log_module(PY_LOG
, LOG_INFO
, "Created new python handler object.");
637 log_module(PY_LOG
, LOG_ERROR
, "Unable to instanciate handler object");
644 log_module(PY_LOG
, LOG_ERROR
, "Unable to find handler class");
648 Py_DECREF(pHandlerClass
);
654 /* ------------------------------------------------------------------------------- *
655 Some gateway functions to convert x3 callbacks into modpython.py callbacks.
656 Mostly we just build relevant args and call the proper handler method
658 debate: do we just register these and check them in python
659 for every one (slow?) or actually work out if a plugin needs
660 it first? We will start by doing it every time.
663 python_handle_join(struct modeNode
*mNode
)
665 /* callback for handle_join events.
667 struct userNode
*user
= mNode
->user
;
668 struct chanNode
*channel
= mNode
->channel
;
671 log_module(PY_LOG
, LOG_INFO
, "python module handle_join");
672 if(!channel
||!user
) {
673 log_module(PY_LOG
, LOG_WARNING
, "Python code got join without channel or user!");
677 char *args
[] = {channel
->name
, user
->nick
};
678 return python_call_handler("join", args
, 2, "", "", "");
683 python_handle_server_link(struct server
*server
)
685 log_module(PY_LOG
, LOG_INFO
, "python module handle_server_link");
687 log_module(PY_LOG
, LOG_WARNING
, "Python code got server link without server!");
691 char *args
[] = {server
->name
, server
->description
};
692 return python_call_handler("server_link", args
, 2, "", "", "");
697 python_handle_new_user(struct userNode
*user
)
699 log_module(PY_LOG
, LOG_INFO
, "Python module handle_new_user");
701 log_module(PY_LOG
, LOG_WARNING
, "Python code got new_user without the user");
705 char *args
[] = {user
->nick
, user
->ident
, user
->hostname
, user
->info
};
706 return python_call_handler("new_user", args
, 4, "", "", "");
711 python_handle_nick_change(struct userNode
*user
, const char *old_nick
)
713 log_module(PY_LOG
, LOG_INFO
, "Python module handle_nick_change");
715 log_module(PY_LOG
, LOG_WARNING
, "Python code got nick_change without the user!");
718 char *args
[] = {user
->nick
, (char *)old_nick
};
719 python_call_handler("nick_change", args
, 2, "", "", "");
723 /* ----------------------------------------------------------------------------- */
727 /* Init the python engine and do init work on modpython.py
728 This is called during x3 startup, and on a python reload
732 char* env
= getenv("PYTHONPATH");
738 setenv("PYTHONPATH", modpython_conf
.scripts_dir
, 1);
739 else if (!strstr(env
, modpython_conf
.scripts_dir
)) {
740 buffer
= (char*)malloc(strlen(env
) + strlen(modpython_conf
.scripts_dir
) + 2);
741 sprintf(buffer
, "%s:%s", modpython_conf
.scripts_dir
, env
);
742 setenv("PYTHONPATH", buffer
, 1);
748 Py_InitModule("_svc", EmbMethods
);
749 pName
= PyString_FromString(modpython_conf
.main_module
);
750 base_module
= PyImport_Import(pName
);
753 Py_XDECREF(handler_object
);
754 handler_object
= NULL
;
756 if(base_module
!= NULL
) {
757 handler_object
= python_new_handler_object();
759 python_call_handler("init", NULL
, 0, "", "", "");
763 /* error handler class not found */
764 log_module(PY_LOG
, LOG_WARNING
, "Failed to create handler object");
771 log_module(PY_LOG
, LOG_WARNING
, "Failed to load modpython.py");
778 python_finalize(void) {
779 /* Called after X3 is fully up and running.
780 Code can be put here that needs to run to init things, but
781 which is sensitive to everything else in x3 being up and ready
785 PyRun_SimpleString("print 'Hello, World of Python!'");
786 log_module(PY_LOG
, LOG_INFO
, "python module finalize");
792 python_cleanup(void) {
793 /* Called on shutdown of the python module (or before reloading)
796 log_module(PY_LOG
, LOG_INFO
, "python module cleanup");
797 if (PyErr_Occurred())
799 Py_Finalize(); /* Shut down python enterpriter */
802 /* ---------------------------------------------------------------------------------- *
803 Python module command handlers.
805 static MODCMD_FUNC(cmd_reload
) {
806 /* reload the python system completely
808 log_module(PY_LOG
, LOG_INFO
, "Shutting python down");
810 log_module(PY_LOG
, LOG_INFO
, "Loading python stuff");
812 reply("PYMSG_RELOAD_SUCCESS");
815 reply("PYMSG_RELOAD_FAILED");
820 static char* format_python_error(int space_nls
) {
821 PyObject
* extype
= NULL
, *exvalue
= NULL
, *extraceback
= NULL
;
822 PyObject
* pextypestr
= NULL
, *pexvaluestr
= NULL
;
823 char* extypestr
= NULL
, *exvaluestr
= NULL
;
824 size_t retvallen
= 0;
825 char* retval
= NULL
, *tmp
;
827 PyErr_Fetch(&extype
, &exvalue
, &extraceback
);
831 pextypestr
= PyObject_Str(extype
);
834 extypestr
= PyString_AsString(pextypestr
);
838 pexvaluestr
= PyObject_Str(exvalue
);
840 exvaluestr
= PyString_AsString(pexvaluestr
);
842 retvallen
= strlen(extypestr
) + (exvaluestr
? strlen(exvaluestr
) + 2 : 0) + 1;
843 retval
= (char*)malloc(retvallen
);
845 snprintf(retval
, retvallen
, "%s: %s", extypestr
, exvaluestr
);
847 strncpy(retval
, extypestr
, retvallen
);
859 if (PyErr_Occurred())
860 PyErr_Clear(); /* ignore errors caused by formatting */
863 Py_XDECREF(extraceback
);
864 Py_XDECREF(pextypestr
);
865 Py_XDECREF(pexvaluestr
);
870 return strdup("unknown exception");
873 static MODCMD_FUNC(cmd_run
) {
874 /* this method allows running arbitrary python commands.
878 PyObject
* py_main_module
;
879 PyObject
* py_globals
;
882 PyObject
* extype
, *exvalue
, *extraceback
;
883 PyObject
* exvaluestr
= NULL
;
884 char* exmsg
= NULL
, *exmsgptr
;
886 py_main_module
= PyImport_AddModule("__main__");
887 py_globals
= py_locals
= PyModule_GetDict(py_main_module
);
889 msg
= unsplit_string(argv
+ 1, argc
- 1, NULL
);
891 py_retval
= PyRun_String(msg
, Py_file_input
, py_globals
, py_locals
);
892 if (py_retval
== NULL
) {
893 PyErr_Fetch(&extype
, &exvalue
, &extraceback
);
894 if (exvalue
!= NULL
) {
895 exvaluestr
= PyObject_Str(exvalue
);
896 exmsg
= strdup(PyString_AS_STRING(exvaluestr
));
898 while (exmsgptr
&& *exmsgptr
) {
899 if (*exmsgptr
== '\n' || *exmsgptr
== '\r' || *exmsgptr
== '\t')
904 if (extype
!= NULL
&& exvalue
!= NULL
&& PyType_Check(extype
)) {
905 reply("PYMSG_RUN_EXCEPTION", ((PyTypeObject
*)extype
)->tp_name
, exmsg
);
907 reply("PYMSG_RUN_UNKNOWN_EXCEPTION");
913 if (extraceback
!= NULL
)
914 Py_DECREF(extraceback
);
915 if (exvaluestr
!= NULL
)
916 Py_DECREF(exvaluestr
);
920 Py_DECREF(py_retval
);
926 #define numstrargs(X) sizeof(X) / sizeof(*X)
927 static MODCMD_FUNC(cmd_command
) {
928 char *plugin
= argv
[1];
929 char *command
= argv
[2];
930 char *msg
; /* args */
932 msg
= unsplit_string(argv
+ 3, argc
- 3, NULL
);
937 char *args
[] = {plugin
, command
, msg
};
938 python_call_handler("cmd_command", args
, numstrargs(args
), cmd
->parent
->bot
->nick
, user
?user
->nick
:"", channel
?channel
->name
:"");
942 static void modpython_conf_read(void) {
946 if (!(conf_node
= conf_get_data(MODPYTHON_CONF_NAME
, RECDB_OBJECT
))) {
947 log_module(PY_LOG
, LOG_ERROR
, "config node '%s' is missing or has wrong type", MODPYTHON_CONF_NAME
);
951 str
= database_get_data(conf_node
, "scripts_dir", RECDB_QSTRING
);
952 modpython_conf
.scripts_dir
= str
? str
: "./";
954 str
= database_get_data(conf_node
, "main_module", RECDB_QSTRING
);
955 modpython_conf
.main_module
= str
? str
: "modpython";
958 int python_init(void) {
959 /* X3 calls this function on init of the module during startup. We use it to
960 do all our setup tasks and bindings
963 PY_LOG
= log_register_type("Python", "file:python.log");
964 python_module
= module_register("python", PY_LOG
, "mod-python.help", NULL
);
965 conf_register_reload(modpython_conf_read
);
967 log_module(PY_LOG
, LOG_INFO
, "python module init");
968 message_register_table(msgtab
);
971 reg_auth_func(python_check_messages);
972 reg_handle_rename_func(python_rename_account);
973 reg_unreg_func(python_unreg_account);
974 conf_register_reload(python_conf_read);
975 saxdb_register("python", python_saxdb_read, python_saxdb_write);
976 modcmd_register(python_module, "send", cmd_send, 3, MODCMD_REQUIRE_AUTHED, NULL);
978 modcmd_register(python_module
, "reload", cmd_reload
, 1, MODCMD_REQUIRE_AUTHED
, "flags", "+oper", NULL
);
979 modcmd_register(python_module
, "run", cmd_run
, 2, MODCMD_REQUIRE_AUTHED
, "flags", "+oper", NULL
);
980 modcmd_register(python_module
, "command", cmd_command
, 3, MODCMD_REQUIRE_STAFF
, NULL
);
982 // Please help us by implimenting any of the callbacks listed as TODO below. They already exist
983 // in x3, they just need handle_ bridges implimented. (see python_handle_join for an example)
984 reg_server_link_func(python_handle_server_link
);
985 reg_new_user_func(python_handle_new_user
);
986 reg_nick_change_func(python_handle_nick_change
);
987 //TODO: reg_del_user_func(python_handle_del_user);
988 //TODO: reg_account_func(python_handle_account); /* stamping of account name to the ircd */
989 //TODO: reg_handle_rename_func(python_handle_handle_rename); /* handle used to ALSO mean account name */
990 //TODO: reg_failpw_func(python_handle_failpw);
991 //TODO: reg_allowauth_func(python_handle_allowauth);
992 //TODO: reg_handle_merge_func(python_handle_merge);
994 //TODO: reg_oper_func(python_handle_oper);
995 //TODO: reg_new_channel_func(python_handle_new_channel);
996 reg_join_func(python_handle_join
);
997 //TODO: reg_del_channel_func(python_handle_del_channel);
998 //TODO: reg_part_func(python_handle_part);
999 //TODO: reg_kick_func(python_handle_kick);
1000 //TODO: reg_topic_func(python_handle_topic);
1001 //TODO: reg_channel_mode_func(python_handle_channel_mode);
1003 //TODO: reg_privmsg_func(python_handle_privmsg);
1004 //TODO: reg_notice_func
1005 //TODO: reg_svccmd_unbind_func(python_handle_svccmd_unbind);
1006 //TODO: reg_chanmsg_func(python_handle_chanmsg);
1007 //TODO: reg_allchanmsg_func
1008 //TODO: reg_user_mode_func
1010 reg_exit_func(python_cleanup
);
1016 #endif /* WITH_PYTHON */