techwithanirudh

Untitled

Oct 13th, 2023
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. import os
  2. import signal
  3. import subprocess
  4. import irc.client
  5. import time
  6. import socket
  7.  
  8. def check_socket(host, port):
  9. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  10. return s.connect_ex((host, port)) == 0
  11.  
  12. def on_connect(connection, event):
  13. print(f"Connected to {event.target}")
  14. connection.join("#main")
  15.  
  16. def on_join(connection, event):
  17. print(f"Joined {event.target}")
  18. connection.privmsg(event.target, "Hi, I am AnirudhGPT! How can I assist you today?")
  19.  
  20. def on_message(connection, event):
  21. print(f"Received message: {event.arguments[0]}")
  22. msg = event.arguments[0].lower()
  23. user_who_pinged = event.source.nick
  24.  
  25. # Checking for bot's dynamic nickname in the message to consider it a "ping"
  26. if connection.get_nickname().lower() in msg:
  27. connection.privmsg(event.target, f"I'm AnirudhGPT {user_who_pinged}!")
  28.  
  29. def main():
  30. server = "127.0.0.1"
  31. port = 7000
  32. nickname = "anirudhgpt"
  33.  
  34. # Start websocat as a subprocess and suppress its output
  35. subprocess.Popen(
  36. ["websocat", "tcp-listen:127.0.0.1:7000", "wss://irc.amcforum.wiki/webirc/websocket/", "--exit-on-eof", "-H", "Origin: https://native-clients.solanum.repl", "-v"],
  37. stdout=subprocess.PIPE,
  38. stderr=subprocess.PIPE
  39. )
  40.  
  41. # Wait for websocat to be ready
  42. while not check_socket(server, port):
  43. print("Waiting for websocat to be available...")
  44. time.sleep(1)
  45.  
  46. print("Websocat is ready. Starting IRC bot.")
  47.  
  48. reactor = irc.client.Reactor()
  49. try:
  50. connection = reactor.server().connect(server, port, nickname)
  51. except irc.client.ServerConnectionError as e:
  52. print(f"Could not connect: {e}")
  53. return
  54.  
  55. connection.add_global_handler("welcome", on_connect)
  56. connection.add_global_handler("join", on_join)
  57. connection.add_global_handler("pubmsg", on_message)
  58.  
  59. reactor.process_forever()
  60.  
  61. if __name__ == "__main__":
  62. main()
  63.  
Advertisement
Add Comment
Please, Sign In to add comment