meetbot.py 7.9 KB

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