summaryrefslogtreecommitdiffstats
path: root/Reaktor/IRC/asybot.py
blob: ceebe844b3a758a1df92ed626e8389e048903809 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#! /usr/bin/env python
#
# //Reaktor/IRC/asybot.py
#
from translate_colors import translate_colors
def is_executable(x):
  import os
  return os.path.exists(x) and os.access(x, os.X_OK)

from asynchat import async_chat as asychat
from asyncore import loop
from socket import AF_INET, SOCK_STREAM,gethostname
from signal import SIGALRM, signal, alarm
from datetime import datetime as date, timedelta
import shlex
from time import sleep
from sys import exit
from re import split, search, match
from textwrap import TextWrapper
import logging,logging.handlers
from getconf import make_getconf
getconf = make_getconf('config.json')
log = logging.getLogger('asybot')
hdlr = logging.handlers.SysLogHandler(facility=logging.handlers.SysLogHandler.LOG_DAEMON)
formatter = logging.Formatter( '%(filename)s: %(levelname)s: %(message)s')
hdlr.setFormatter(formatter)
log.addHandler(hdlr)
logging.basicConfig(level = logging.DEBUG if getconf('main.debug') else logging.INFO)

# s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g -- removes color codes


class asybot(asychat):
  def __init__(self):
    asychat.__init__(self)
    self.server = getconf('irc.server')
    self.port = getconf('irc.port')
    self.channels = getconf('irc.channels')
    self.realname = getconf('irc.nickname')
    self.nickname = getconf('irc.nickname')
    self.username = getconf('irc.nickname')
    self.hostname = getconf('irc.nickname')
    self.ircname = getconf('irc.nickname')
    self.data = ''
    self.set_terminator('\r\n'.encode(encoding='UTF-8'))
    self.create_socket(AF_INET, SOCK_STREAM)
    self.connect((self.server, self.port))
    self.wrapper = TextWrapper(subsequent_indent=" ",width=400)

    log.info('=> irc://%s@%s:%s/%s' % (self.nickname, self.server, self.port, self.channels))

    # When we don't receive data for alarm_timeout seconds then issue a
    # PING every hammer_interval seconds until kill_timeout seconds have
    # passed without a message.  Any incoming message will reset alarm.
    self.alarm_timeout = getconf('irc.alarm_timeout')
    self.hammer_interval = getconf('irc.hammer_interval')
    self.kill_timeout = 360
    signal(SIGALRM, lambda signum, frame: self.alarm_handler())
    self.reset_alarm()


  def reset_alarm(self):
    self.last_activity = date.now()
    alarm(self.alarm_timeout)

  def alarm_handler(self):
    delta = date.now() - self.last_activity
    if delta > timedelta(seconds=self.kill_timeout):
      log.error('No data for %s.  Giving up...' % delta)
      exit(2)
    else:
      log.error('No data for %s.  PINGing server...' % delta)
      self.push('PING :%s' % self.nickname)
      alarm(self.hammer_interval)

  def collect_incoming_data(self, data):
    self.data += data.decode(encoding='UTF-8')

  def found_terminator(self):
    log.debug('<< %s' % self.data)

    message = self.data
    self.data = ''

    _, prefix, command, params, rest, _ = \
        split('^(?::(\S+)\s)?(\S+)((?:\s[^:]\S*)*)(?:\s:(.*))?$', message)
    params = params.split(' ')[1:]

    if command == 'PING':
      self.push('PONG :%s' % rest)
      log.debug("Replying to servers PING with PONG :%s" %rest)

    elif command == 'PRIVMSG':
      self.on_privmsg(prefix, command, params, rest)

    elif command == '433':
      # ERR_NICKNAMEINUSE, retry with another name
      _, nickname, int, _ = split('^.*[^0-9]([0-9]+)$', self.nickname) \
          if search('[0-9]$', self.nickname) \
          else ['', self.nickname, 0, '']
      self.nickname = nickname + str(int + 1)
      self.handle_connect()

    self.reset_alarm()

  def push(self, message):
    msg = (message + self.get_terminator().decode(encoding='UTF-8')).encode(encoding='UTF-8')
    log.debug('>> %s' % msg)
    asychat.push(self, msg)

  def handle_connect(self):
    self.push('NICK %s' % self.nickname)
    self.push('USER %s %s %s :%s' %
        (self.username, self.hostname, self.server, self.realname))
    self.push('JOIN %s' % ','.join(self.channels))

  def on_privmsg(self, prefix, command, params, rest):
    def PRIVMSG(text):
      for line in self.wrapper.wrap(text.decode(encoding='UTF-8')):
        msg = 'PRIVMSG %s :%s' % (','.join(params), line)
        log.info(msg)
        self.push(msg)
        sleep(1)

    def ME(text):
      PRIVMSG(('ACTION ' + text + '').encode(encoding='UTF-8'))

    for command in getconf('irc.commands'):
      y = match(command['pattern'], rest)
      if y:
        self.execute_command(command, y, PRIVMSG, ME)

  def execute_command(self, command, match, PRIVMSG, ME):
    from os.path import realpath, dirname, join
    from subprocess import Popen as popen, PIPE
    from time import time

    #TODO: allow only commands below ./commands/
    exe = join(dirname(realpath(dirname(__file__))), command['argv'][0])
    myargv = [exe] + command['argv'][1:]

    env = {}
    start = time()
    try:
      p = popen(myargv, bufsize=1, stdout=PIPE, stderr=PIPE, env=env)
    except (OSError, Exception) as error:
      ME('brain damaged')
      log.error('OSError@%s: %s' % (myargv, error))
      return
    pid = p.pid
    for line in iter(p.stdout.readline, ''.encode(encoding='UTF-8')):
      try:
        PRIVMSG(translate_colors(line))
      except Exception as error:
        log.error('no send: %s' % error)
      log.debug('%s stdout: %s' % (pid, line))
    p.wait()
    elapsed = time() - start
    code = p.returncode
    log.info('command: %s -> %s in %d seconds' % (myargv, code, elapsed))
    [log.debug('%s stderr: %s' % (pid, x)) for x in p.stderr.readlines()]

    if code != 0:
      ME('mimimi')

if __name__ == "__main__":
  asybot()
  loop()