I want to make a bot that will allow me to define functions from irc and treat my bot like a Python interpreter too.
For example, I want to make a bot that can do something like the following:
<mynick> py print "test"
<bot> test
<mynick> define hi(): print "hi"
<mynick> hi()
<bot> hi
MY QUESTION IS HOW TO DO THIS
If you're not worried about security (and if this is a personal project then that's a valid assumption), then Python has several functions (compile
, exec
, eval
) that can help here. Note that there are differences between Python 2 and Python 3, but the following example works for both:
>>> s = "print('hello world')"
>>> code = compile(s, "<string>", "exec")
>>> exec(code)
hello world
If you're going to let other people use this bot, you will want to pay very careful attention to the functions you let people call. For example, most things in the os
module have potential to do undesirable things in an irc bot context.
I wrote skybot, which has functionality close to what you want.
<rmmh> .py print "hello %03d, %s" % (5, "blah")
<skybot> Scaevolus: hello 005, blah
The Python interpreter runs on GAE and is a clone of http://shell.appspot.com/ modified to not store state, to prevent people from breaking the bot.
You could hook your code into this: http://tumbolia.appspot.com/py/
import urllib, urllib2
uri = 'http://tumbolia.appspot.com/py/'
response = urllib2.urlopen(uri + urllib.quote("print 'hello world!'")).read()
print response
The nice thing about this solution is that you don't have to worry about the code being executed on your server. This is how the IRC bot phenny executes python code for the '.py' command.
来源:https://stackoverflow.com/questions/5520918/python-irc-bot-question