Skip to content

Instantly share code, notes, and snippets.

@hlfbt
Forked from kylef/pyeval.py
Created January 21, 2012 20:16
Show Gist options
  • Save hlfbt/1653868 to your computer and use it in GitHub Desktop.
Save hlfbt/1653868 to your computer and use it in GitHub Desktop.
Python Evaluate for ZNC modpython
# pythoneval.py
import sys
import re
from code import InteractiveInterpreter
import znc
class pythoneval(znc.Module, InteractiveInterpreter):
# module_types makes it unable to load
# module_types = [znc.CModInfo.UserModule, znc.CModInfo.NetworkModule]
description = "Evaluates python code and listens to OnUserMsg. Use \".py <code>\" to evaluate <code> inside a channel"
targetchan = '*pythoneval'
def write(self, data):
for line in data.split('\n'):
if len(line):
self.PutModule(line)
def write_to(self, data):
for line in data.split('\n'):
if len(line):
self.PutIRC("PRIVMSG "+targetchan+" :python: "+line)
self.PutUser(":"+str(self.GetUser())+" PRIVMSG "+targetchan+" :python: "+line)
def resetbuffer(self):
"""Reset the input buffer."""
self.buffer = []
def push(self, line):
self.buffer.append(line)
source = "\n".join(self.buffer)
more = self.runsource(source, self.filename)
if not more:
self.resetbuffer()
return more
def OnLoad(self, args, message):
# if not self.GetUser().IsAdmin():
# message.s = 'You must have admin privileges to load this module.'
# return False
self.filename = "<console>"
self.resetbuffer()
self.locals['znc'] = znc
self.locals['module'] = self
self.locals['user'] = self.GetUser()
self.indent = re.compile(r'^>+')
return True
def OnModCommand(self, line):
self.locals['client'] = self.GetClient()
# Hijack sys.stdout.write
stdout_write = sys.stdout.write
sys.stdout.write = self.write
m = self.indent.match(line)
if m:
self.push((' ' * len(m.group())) + line[len(m.group()):])
elif line == ' ' or line == '<':
self.push('')
else:
self.push(line)
# Revert sys.stdout.write
sys.stdout.write = stdout_write
del self.locals['client']
def OnUserMsg(self, target, message):
fmatch = re.compile("^.py .*")
message = str(message)
target = str(target)
if fmatch.match(message):
message=message.replace(".py ","")
global targetchan
targetchan = target
# Hijack sys.stdout.write
stdout_write = sys.stdout.write
sys.stdout.write = self.write_to
m = self.indent.match(message)
if m:
self.push((' ' * len(m.group())) + message[len(m.group()):])
elif message == ' ' or message == '<':
self.push('')
else:
self.push(message)
# Revert sys.stdout.write
sys.stdout.write = stdout_write
targetchan = '*pythoneval'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment