meetbot.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. #!/usr/bin/env python3
  2. import asyncio
  3. import logging
  4. import pickle
  5. from base58 import b58decode
  6. from nacl.public import PrivateKey, Box
  7. from meetbot_cfg import config
  8. # Initialized channels from the configuration
  9. CHANS = {}
  10. # Pickle DB
  11. PICKLE_DB = "meetbot.pickle"
  12. # TODO: while this is nice to support, it would perhaps be better to do it
  13. # all over the same connection rather than opening a socket for each channel.
  14. async def channel_listen(host, port, nick, chan):
  15. try:
  16. logging.info("%s: Connecting to %s:%s", chan, host, port)
  17. reader, writer = await asyncio.open_connection(host, port)
  18. logging.debug("%s: Send CAP msg", chan)
  19. msg = "CAP REQ : no-history\r\n"
  20. writer.write(msg.encode("utf-8"))
  21. await writer.drain()
  22. logging.debug("%s: Send NICK msg", chan)
  23. msg = f"NICK {nick}\r\n"
  24. writer.write(msg.encode("utf-8"))
  25. await writer.drain()
  26. logging.debug("%s: Send CAP END msg", chan)
  27. msg = "CAP END\r\n"
  28. writer.write(msg.encode("utf-8"))
  29. await writer.drain()
  30. logging.debug("%s: Send JOIN msg", chan)
  31. msg = f"JOIN {chan}\r\n"
  32. writer.write(msg.encode("utf-8"))
  33. await writer.drain()
  34. logging.info("%s: Listening to channel", chan)
  35. while True:
  36. msg = await reader.readline()
  37. msg = msg.decode("utf8")
  38. if not msg:
  39. continue
  40. split_msg = msg.split(" ")
  41. command = split_msg[1]
  42. nick_c = split_msg[0][1:].rsplit("!", 1)[0]
  43. logging.debug("%s: Recv: %s", chan, msg.rstrip())
  44. if command == "PRIVMSG":
  45. msg_title = msg.split(" ")[3][1:].rstrip()
  46. if not msg_title:
  47. logging.info("%s: Recv empty PRIVMSG, ignoring", chan)
  48. continue
  49. if msg_title == "!start":
  50. logging.info("%s: Got !start", chan)
  51. topics = CHANS[chan]["topics"]
  52. reply = f"PRIVMSG {chan} :Meeting started"
  53. logging.info("%s: Send: %s", chan, reply)
  54. writer.write((reply + "\r\n").encode("utf-8"))
  55. await writer.drain()
  56. if len(topics) == 0:
  57. reply = f"PRIVMSG {chan} :No topics"
  58. logging.info("%s: Send: %s", chan, reply)
  59. writer.write((reply + "\r\n").encode("utf-8"))
  60. await writer.drain()
  61. continue
  62. reply = f"PRIVMSG {chan} :Topics:"
  63. logging.info("%s: Send: %s", chan, reply)
  64. writer.write((reply + "\r\n").encode("utf-8"))
  65. await writer.drain()
  66. for i, topic in enumerate(topics):
  67. reply = f"PRIVMSG {chan} :{i+1}. {topic}"
  68. logging.info("%s: Send: %s", chan, reply)
  69. writer.write((reply + "\r\n").encode("utf-8"))
  70. await writer.drain()
  71. cur_topic = topics.pop(0)
  72. reply = f"PRIVMSG {chan} :Current topic: {cur_topic}\r\n"
  73. CHANS[chan]["topics"] = topics
  74. writer.write(reply.encode("utf-8"))
  75. await writer.drain()
  76. continue
  77. if msg_title == "!end":
  78. logging.info("%s: Got !end", chan)
  79. reply = f"PRIVMSG {chan} :Meeting ended"
  80. logging.info("%s: Send: %s", chan, reply)
  81. writer.write((reply + "\r\n").encode("utf-8"))
  82. await writer.drain()
  83. continue
  84. if msg_title == "!topic":
  85. logging.info("%s: Got !topic", chan)
  86. topic = msg.split(" ", 4)
  87. if len(topic) != 5:
  88. logging.debug("%s: Topic msg len not 5, skipping",
  89. chan)
  90. continue
  91. topic = topic[4].rstrip() + f" (by {nick_c})"
  92. if topic == "":
  93. logging.debug("%s: Topic message empty, skipping",
  94. chan)
  95. continue
  96. topics = CHANS[chan]["topics"]
  97. if topic not in topics:
  98. topics.append(topic)
  99. CHANS[chan]["topics"] = topics
  100. logging.debug("%s: Appended topic to channel topics",
  101. chan)
  102. reply = f"PRIVMSG {chan} :Added topic: {topic}"
  103. logging.info("%s: Send: %s", chan, reply)
  104. else:
  105. logging.debug("%s: Topic already in list of topics",
  106. chan)
  107. reply = f"PRIVMSG {chan} :Topic already in list"
  108. logging.info("%s: Send: %s", chan, reply)
  109. writer.write((reply + "\r\n").encode("utf-8"))
  110. await writer.drain()
  111. continue
  112. if msg_title == "!list":
  113. logging.info("%s: Got !list", chan)
  114. topics = CHANS[chan]["topics"]
  115. if len(topics) == 0:
  116. reply = f"PRIVMSG {chan} :No topics"
  117. else:
  118. reply = f"PRIVMSG {chan} :Topics:"
  119. logging.info("%s: Send: %s", chan, reply)
  120. writer.write((reply + "\r\n").encode("utf-8"))
  121. await writer.drain()
  122. for i, topic in enumerate(topics):
  123. reply = f"PRIVMSG {chan} :{i+1}. {topic}"
  124. logging.info("%s: Send: %s", chan, reply)
  125. writer.write((reply + "\r\n").encode("utf-8"))
  126. await writer.drain()
  127. continue
  128. if msg_title == "!next":
  129. logging.info("%s: Got !next", chan)
  130. topics = CHANS[chan]["topics"]
  131. if len(topics) == 0:
  132. reply = f"PRIVMSG {chan} :No further topics"
  133. else:
  134. cur_topic = topics.pop(0)
  135. CHANS[chan]["topics"] = topics
  136. reply = f"PRIVMSG {chan} :Current topic: {cur_topic}"
  137. logging.info("%s: Send: %s", chan, reply)
  138. writer.write((reply + "\r\n").encode("utf-8"))
  139. await writer.drain()
  140. continue
  141. except KeyboardInterrupt:
  142. return
  143. except ConnectionRefusedError:
  144. logging.warning("%s: Connection refused, trying again in 3s...", chan)
  145. await asyncio.sleep(3)
  146. await channel_listen(host, port, nick, chan)
  147. except Exception as e:
  148. logging.error("EXCEPTION: %s", e)
  149. logging.warn("%s: Connection interrupted. Reconnecting in 3s...", chan)
  150. await asyncio.sleep(3)
  151. await channel_listen(host, port, nick, chan)
  152. async def main(debug=False):
  153. global CHANS
  154. loglevel = logging.DEBUG if debug else logging.INFO
  155. logfmt = "%(asctime)s [%(levelname)s]\t%(message)s"
  156. logging.basicConfig(format=logfmt,
  157. level=loglevel,
  158. datefmt="%Y-%m-%d %H:%M:%S")
  159. try:
  160. with open(PICKLE_DB, "rb") as pickle_fd:
  161. CHANS = pickle.load(pickle_fd)
  162. logging.info("Loaded pickle database")
  163. except:
  164. logging.info("Did not find pickle database")
  165. for i in config["channels"]:
  166. name = i["name"]
  167. logging.info("Found config for channel %s", name)
  168. # TODO: This will be useful when ircd has a CAP that tells it to
  169. # give **all** messages to the connected client, no matter if ircd
  170. # itself has a configured secret or not.
  171. # This way the ircd itself doesn't have to keep channel secrets, but
  172. # they can rather only be held by this bot. In turn this means the bot
  173. # can be deployed with any ircd.
  174. if i["secret"]:
  175. logging.info("Instantiating NaCl box for %s", name)
  176. secret = b58decode(i["secret"].encode("utf-8"))
  177. secret = PrivateKey(secret)
  178. public = secret.public_key
  179. box = Box(secret, public)
  180. else:
  181. box = None
  182. if not CHANS.get(name):
  183. CHANS[name] = {}
  184. if not CHANS[name].get("topics"):
  185. CHANS[name]["topics"] = []
  186. CHANS[name]["box"] = box
  187. coroutines = []
  188. for i in CHANS.keys():
  189. logging.debug("Creating async task for %s", i)
  190. task = asyncio.create_task(
  191. channel_listen(config["host"], config["port"], config["nick"], i))
  192. coroutines.append(task)
  193. await asyncio.gather(*coroutines)
  194. if __name__ == "__main__":
  195. from sys import argv
  196. DBG = bool(len(argv) == 2 and argv[1] == "-v")
  197. try:
  198. asyncio.run(main(debug=DBG))
  199. except KeyboardInterrupt:
  200. print("\rCaught ^C, saving pickle and exiting")
  201. with open(PICKLE_DB, "wb") as fdesc:
  202. pickle.dump(CHANS, fdesc, protocol=pickle.HIGHEST_PROTOCOL)