Python IRC bot question

六眼飞鱼酱① 提交于 2019-12-01 12:37:32

问题


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


回答1:


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.




回答2:


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.




回答3:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!