summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCamil Staps2018-06-11 14:01:39 +0200
committerCamil Staps2018-06-11 14:01:39 +0200
commit06a7f1b21e6e1c5e609b86c8acc0df76333254a8 (patch)
treeb08cf7d45332be2a39e625ccb484cdef69d197be
Probably doesn't work with the new telepot, but still committing this ancient project at least onceHEADmaster
-rw-r--r--bot.py65
-rw-r--r--clean.py80
2 files changed, 145 insertions, 0 deletions
diff --git a/bot.py b/bot.py
new file mode 100644
index 0000000..c80d06e
--- /dev/null
+++ b/bot.py
@@ -0,0 +1,65 @@
+from datetime import datetime
+import time
+import asyncio
+
+import telepot
+import telepot.async
+
+import clean
+
+class CleanBot(telepot.async.Bot):
+ def log(self, msg, date=datetime.now()):
+ date = date.strftime('%a %b %d %Y %H:%M:%S')
+ print('[%s] %s' % (date, msg))
+
+ def log_to(self, msg, user):
+ self.log('%s <-- %s' % (user, msg))
+
+ def log_from(self, msg, user, date):
+ self.log('%s --> %s' % (user, msg), date=date)
+
+ def send(self, user, msg):
+ yield from self.sendMessage(user, msg)
+ self.log_to(msg, user)
+
+ def handle_text(self, msg):
+ date = datetime.fromtimestamp(int(msg['date']))
+ self.log_from(msg['text'], msg['from']['id'], date)
+
+ try:
+ result = clean.single_command(msg['text'])
+ if result == None:
+ raise ValueError()
+ yield from self.send(msg['from']['id'], result)
+ except UnicodeEncodeError:
+ yield from self.send(msg['from']['id'], 'Illegal character')
+ except clean.CompileException:
+ yield from self.send(msg['from']['id'], 'Compile error')
+ except clean.TimeoutException:
+ yield from self.send(msg['from']['id'], 'Timeout exceeded')
+
+ def handle_other(self, msg):
+ date = datetime.fromtimestamp(int(msg['date']))
+ self.log_from('unknown content type', msg['from']['username'], date)
+
+ @asyncio.coroutine
+ def handle(self, msg):
+ content_type, chat_type, chat_id = telepot.glance2(msg)
+ if content_type == 'text':
+ yield from self.handle_text(msg)
+ else:
+ yield from self.handle_other(msg)
+
+ def run(self):
+ while True:
+ time.sleep(10)
+
+def main():
+ bot = CleanBot('177072260:AAESRI146zYqh3iZN0WPboB6Z-LpmKyX3J0')
+ loop = asyncio.get_event_loop()
+ loop.create_task(bot.messageLoop())
+ print('Listening...')
+ loop.run_forever()
+
+if __name__ == '__main__':
+ main()
diff --git a/clean.py b/clean.py
new file mode 100644
index 0000000..5d14c4a
--- /dev/null
+++ b/clean.py
@@ -0,0 +1,80 @@
+import os
+import shutil
+import subprocess
+import tempfile
+import threading
+
+class CompileException(Exception):
+ pass
+
+class TimeoutException(Exception):
+ pass
+
+class KillableThread():
+ def __init__(self, *args, **kwargs):
+ self.popenargs = args
+ self.kwargs = kwargs
+ self.kwargs['stdout'] = subprocess.PIPE
+ self.process = None
+ self.result = None
+
+ def run(self, timeout=5):
+ def target():
+ self.process = subprocess.Popen(*self.popenargs, **self.kwargs)
+ try:
+ self.result = self.process.communicate()[0]
+ except IOError:
+ pass
+
+ thread = threading.Thread(target=target)
+ thread.start()
+
+ thread.join(timeout)
+ if thread.is_alive():
+ self.process.kill()
+ try:
+ self.process.communicate()
+ thread.join()
+ except IOError:
+ pass
+ return self.result
+
+def compile(module):
+ with open(os.devnull, 'w') as FNULL:
+ result = subprocess.call(['clm', module, '-o', module],
+ stdout=FNULL, stderr=FNULL)
+ if result != 0:
+ raise CompileException()
+
+def run(module):
+ t = KillableThread(['./' + module, '-nt'])
+ result = t.run()
+ if result == None:
+ raise TimeoutException()
+ else:
+ return result[:-1]
+
+def cleanup(module):
+ if os.path.exists('Clean System Files'):
+ shutil.rmtree('Clean System Files')
+ if os.path.exists(module + '.icl'):
+ os.unlink(module + '.icl')
+ if os.path.exists(module):
+ os.unlink(module)
+
+def gettempfile():
+ tf = tempfile.mkstemp(dir='.', suffix='.icl')[1]
+ return os.path.basename(tf)[:-4], tf
+
+def single_command(cmd):
+ base_format = 'module %s\nimport StdEnv\nStart = %s\n'
+
+ module, fn = gettempfile()
+ with open(fn, 'w') as f:
+ f.write(base_format % (module, cmd))
+
+ compile(module)
+ output = run(module)
+ cleanup(module)
+
+ return output