parse.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import socket, asyncio, time, re, ircstates, importlib
  2. from config import *
  3. import shared
  4. def _send(msg: str, log=True):
  5. shared.sock.send(f"{msg}\n".encode('utf-8'))
  6. if log == True: print(f"> {msg}")
  7. def usermodes(chan, user, srv):
  8. try: return srv.channels[chan].users[user].modes
  9. except KeyError: return []
  10. #def _send(msg: str, log=True):
  11. #s.send(f"{msg}\n".encode('utf-8'))
  12. #if log == True: print(f"> {msg}")
  13. def botdesc():
  14. return fileload('desc')
  15. def is_admin(source):
  16. #return 'julian@envs.net' == source.split('!')[1]
  17. #db['oper'].insert(dict(hostmask='friend!good@person'))
  18. #db['oper'].delete(hostmask='nick!badowner@bad.opers')
  19. try:
  20. for i in db['oper'].all():
  21. if source == i['hostmask']: return True
  22. else: continue
  23. except Exception as e:
  24. _send(f"PRIVMSG julian :{source} caused {e}")
  25. return False
  26. return False
  27. def nslogin():
  28. _send("CAP REQ :echo-message")
  29. _send("CAP END")
  30. _send(f"PRIVMSG NickServ@services.tilde.chat :IDENTIFY {NICK} {SERVICES_PW}", log=False)
  31. print("Logged into services")
  32. _send(f"MODE {NICK} +B")
  33. Chan.joins()
  34. class Chan:
  35. def joins():
  36. for i in db['chan'].all():
  37. _send(f"JOIN {','.join([i['name']])}")
  38. def join(channel):
  39. _send(f"JOIN {channel}")
  40. db['chan'].insert(dict(name=channel))
  41. def leave(channel, msg="", kick=False):
  42. if not kick: _send(f"PART {channel} :{msg}")
  43. db['chan'].delete(name=channel)
  44. class Command:
  45. def ExplicitCommandParser(line, srv):
  46. commandargs = line.params[1].split(' ')
  47. command = ''.join(commandargs[0].split('*.')[1:])
  48. args = commandargs[1:]
  49. usernick = line.source.split('!')[0]
  50. chan = line.params[0]
  51. if command == "help": _send(f"PRIVMSG {chan} :{botdesc()}")
  52. elif command == "echo": _send(f"PRIVMSG {chan} :\x033[Echo]\x0F \x032{usernick}\x0F said: \x039{' '.join(args[0:])}")
  53. elif command == "psa" and args[0].startswith('#'):
  54. if 'o' in usermodes(args[0], usernick, srv) or 'q' in usermodes(args[0], usernick, srv): _send(f"PRIVMSG {args[0]} :\x0307**PSA:\x0F {' '.join(args[1:])}")
  55. else: _send(f"PRIVMSG {chan} :{usernick}: Sorry, you aren't allowed to make public service anouncements.")
  56. elif command == "psa" and not args[0].startswith('#'): _send(f"PRIVMSG {chan} :Sorry, the syntax for PSA is: *.psa <channel> <MESSAGE>")
  57. elif 'o' in usermodes(chan, usernick, srv) or 'q' in usermodes(chan, usernick, srv):
  58. if command == "part": Chan.leave(chan, msg=f"Leaving per request of {usernick}")
  59. if command == "topic": _send(f"TOPIC {chan} :{' '.join(args[0:])}")
  60. if command.endswith("op"):
  61. cmd = command.split("op")[0]
  62. if cmd == 'de': _send("MODE {} -vhoaq {}".format(chan, 5*f"{usernick} "))
  63. elif command == "op": _send("MODE {} +vhoa {}".format(chan, 4*f"{usernick} "))
  64. elif cmd == "deh": _send("MODE {} -h {}".format(chan, 1*f"{usernick} "))
  65. elif cmd == "dev": _send("MODE {} -v {}".format(chan, 1*f"{usernick} "))
  66. elif cmd == "dea": _send("MODE {} -a {}".format(chan, 1*f"{usernick} "))
  67. elif cmd == "deo": _send("MODE {} -o {}".format(chan, 1*f"{usernick} "))
  68. def AdminCommandParser(line, srv):
  69. cmdargs = line.params[1].split(' ')
  70. cmd = ''.join(cmdargs[0].split('%')[1:])
  71. args = cmdargs[1:]
  72. usernick = line.source.split('!')[0]
  73. chan = line.params[0]
  74. if cmd == "mode": _send(f"MODE {chan} {' '.join(args)}")
  75. elif cmd == "quit": _send(f"QUIT :{' '.join(args)}")
  76. elif cmd == "msg": _send(f"PRIVMSG {args[0]} :{' '.join(args[1:])}")
  77. elif cmd == "raw": _send(f"{' '.join(args)}")
  78. elif cmd == "join": Chan.join(args[0])
  79. elif cmd == "part": Chan.leave(args[0])
  80. elif cmd == "rpart": _send(f"PART {chan} :~Bye")
  81. elif cmd == "rjoin" and len(args) > 0: _send(f"JOIN {args[0]}")
  82. elif cmd == "regdrop":
  83. try:
  84. if len(args) > 0: thatchan = args[0]
  85. else:
  86. thatchan = ["#"]
  87. for i in range(0, 5): thatchan.append(importlib.import_module('random').choice(importlib.import_module('string').ascii_letters))
  88. thatchan = ''.join(thatchan)
  89. _send(f"JOIN {thatchan}")
  90. _send(f"PRIVMSG {chan} :{thatchan}")
  91. _send(f"PRIVMSG ChanServ :REGISTER {thatchan}")
  92. _send(f"PRIVMSG ChanServ :DROP {thatchan} {thatchan}")
  93. if len(args) > 1: db['ops'].insert(dict(mask=line.source, chan=thatchan, delete=True, modes=args[1]))
  94. else: db['ops'].insert(dict(mask=line.source, chan=thatchan, delete=True, modes='o'))
  95. _send(f"INVITE {usernick} {thatchan}")
  96. except Exception as e: print(e)
  97. elif cmd == "oper":
  98. try:
  99. if args[0].startswith('-'):
  100. db['oper'].delete(hostmask=args[0][1:])
  101. _send(f"PRIVMSG {chan} :Hostmask {args[0][1:]} is no longer oper")
  102. elif args[0].startswith('+'):
  103. db['oper'].insert(dict(hostmask=args[0][1:]))
  104. _send(f"PRIVMSG {chan} :Hostmask {args[0][1:]} is now oper")
  105. except Exception as e: _send(f"PRIVMSG {chan} :Exception({e})")
  106. elif cmd == "op" and len(args) > 2:
  107. #db['ops'].insert(dict(mask=line.source, chan=thatchan, delete=True, modes=args[1]))
  108. try:
  109. if args[1].startswith('-'):
  110. db['ops'].delete(chan=args[0], modes=args[1][1:])
  111. _send(f"PRIVMSG {chan} :Mode {args[0]}:-{args[1][1:]} {args[2].split('!')[0]}")
  112. elif args[1].startswith('+'):
  113. if len(args) > 3: db['ops'].insert(dict(chan=args[0], modes=args[1][1:], mask=args[2], delete=True))
  114. else: db['ops'].insert(dict(chan=args[0], modes=args[1][1:], mask=args[2], delete=False))
  115. _send(f"PRIVMSG {chan} :Mode {args[0]}:+{args[1][1:]} {args[2].split('!')[0]}")
  116. except Exception as e: _send(f"PRIVMSG {chan} :Exception({e})")
  117. elif cmd == "eval":
  118. try: _send(f"PRIVMSG {chan} :{eval(' '.join(args))}")
  119. except Exception as e: _send(f"PRIVMSG {chan} :Exception({e})")
  120. def privmsg(line, srv):
  121. if line.params[1].startswith('%') and is_admin(line.source): Command.AdminCommandParser(line, srv)
  122. elif line.params[0] != NICK and line.params[1] == "!botlist": _send(f"PRIVMSG {line.params[0]} :{botdesc()}")
  123. elif line.params[0] == NICK and line.params[1] == "!botlist": _send(f"PRIVMSG {line.source.split('!')[0]} :{botdesc()}")
  124. if line.params[1].startswith('*.'): Command.ExplicitCommandParser(line, srv)
  125. def Parse(_send=None, srv=None, line=None):
  126. try: Parser(_send, srv, line)
  127. except Exception as e: print(e)
  128. def Parser(_send=None, srv=None, line=None):
  129. if not line.command == "PING": print(f"< {line.format()}")
  130. if line.command == "PING":
  131. _send(f"PONG :{line.params[0]}", log=False)
  132. if shared.nick_has_changed: _send(f"NICK {NICK}")
  133. elif line.command == "433": _send(f"NICK {NICK}_"); shared.nick_has_changed = True
  134. elif (line.source == f"NickServ!{SERVICES_HOSTMASK}" and line.command == 'NOTICE' and line.params == ['util','If you do not change within 1 minute, I will change your nick.']): nslogin()
  135. elif (line.command == "INVITE" and line.params[0] == NICK): Chan.join(line.params[1])
  136. elif line.command == "KICK" and line.params[1] == NICK: Chan.leave(line.params[0], kick=True)
  137. elif line.command == "PRIVMSG": Command.privmsg(line, srv)
  138. elif line.command == "JOIN":
  139. try:
  140. for i in db['ops'].all():
  141. if line.command == "JOIN" and line.source == i['mask'] and line.params[0] == i['chan']:
  142. nickspace = f"{i['mask'].split('!')[0]} "
  143. _send(f"MODE {i['chan']} +{i['modes']} {len(i['modes'])*nickspace}")
  144. if i['delete']: db['ops'].delete(mask=i['mask'], chan=i['chan'], modes=i['modes'])
  145. except Exception as e: print(e)