An IRC bot built for tubes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
2.7KB

  1. #!/usr/bin/python3
  2. # See the LICENSE file for licensing information
  3. import re
  4. nick = 'seddy'
  5. server = 'chat.freenode.net'
  6. channel = '#example'
  7. gecos = 'A text processing bot'
  8. receive = open('/tmp/' + server + '.in', 'r')
  9. send = open('/tmp/' + server + '.out', 'w')
  10. parse_msg = re.compile(' :(.*)')
  11. parse_sed = re.compile('(?<!\\\\)/')
  12. is_sed = re.compile('s/.*/.*')
  13. class Queue:
  14. size = 0
  15. data = []
  16. head = 0
  17. tail = 0
  18. count = 0
  19. def __init__(self, size):
  20. self.size = size
  21. self.data = [None]*size
  22. def enqueue(self, s):
  23. if not self.full():
  24. self.count += 1
  25. self.data[self.tail] = s
  26. self.tail = (self.tail + 1) % self.size
  27. def dequeue(self):
  28. if not self.empty():
  29. self.count -= 1
  30. s = self.data[self.head]
  31. self.head = (self.head + 1) % self.size
  32. return s
  33. def full(self):
  34. return self.size == self.count
  35. def empty(self):
  36. return self.head == self.count
  37. def find(self, s):
  38. i = self.tail-1
  39. while True:
  40. if i == -1:
  41. i = self.size-1
  42. if re.search(s, self.data[i]):
  43. return self.data[i]
  44. i -= 1
  45. if i == self.tail-1:
  46. return False
  47. def seddy(sed, history):
  48. regex = parse_sed.split(sed)
  49. msg = history.find(regex[1])
  50. f = 0
  51. if msg == False:
  52. return False
  53. if 'i' in regex[3]:
  54. f |= re.I
  55. if "g" in regex[3]:
  56. return re.sub(regex[1], regex[2], msg, flags=f)
  57. else:
  58. return re.sub(regex[1], regex[2], msg, 1)
  59. def notice(msg):
  60. send.write('NOTICE ' + channel + ' :' + msg + '\r\n')
  61. send.flush()
  62. def privmsg(msg):
  63. send.write('PRIVMSG ' + channel + ' :' + msg + '\r\n')
  64. send.flush()
  65. if __name__ == "__main__":
  66. history = Queue(48)
  67. send.write('NICK ' + nick + '\r\n')
  68. send.flush()
  69. send.write('USER ' + nick + ' * 8 :' + gecos + '\r\n')
  70. send.flush()
  71. send.write('JOIN ' + channel + '\r\n')
  72. send.flush()
  73. for line in receive:
  74. msg = parse_msg.search(line)
  75. if msg is None:
  76. continue
  77. else:
  78. msg = msg.group(1)
  79. if history.full():
  80. history.dequeue()
  81. if 'PRIVMSG' in line and not is_sed.match(msg):
  82. history.enqueue(msg)
  83. if 'PING' in line:
  84. send.write('PONG\r\n')
  85. send.flush()
  86. if '.bots' in msg or '.bot ' + nick in msg:
  87. notice("I was written to correct your mistakes.")
  88. if '.source ' + nick in msg:
  89. notice('[Python] https://github.com/sys-fs/seddy')
  90. elif is_sed.match(msg):
  91. foo = seddy(msg, history)
  92. if foo != False:
  93. privmsg(re.sub('\\\\/', '/', foo))