titlebot.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # -*- coding: utf-8 -*-
  2. import re
  3. import signal
  4. import irc
  5. import requests
  6. from bs4 import BeautifulSoup
  7. from urllib.parse import urlparse
  8. ## IRC Config
  9. server = "127.0.0.1"
  10. port = 22025
  11. channels = ["#test", "#test1"]
  12. botnick = "website-title"
  13. ircc = irc.IRC()
  14. ircc.connect(server, port, channels, botnick)
  15. def signal_handler(sig, frame):
  16. print("Caught termination signal, cleaning up and exiting...")
  17. ircc.disconnect(server, port)
  18. print("Shut down successfully")
  19. exit(0)
  20. signal.signal(signal.SIGINT, signal_handler)
  21. while True:
  22. text = ircc.get_response()
  23. if not len(text) > 0:
  24. print("Error: disconnected from server")
  25. exit(-1)
  26. print(text)
  27. text_list = text.split(' ')
  28. if text_list[1] == "PRIVMSG":
  29. channel = text_list[2]
  30. msg = ' '.join(text_list[3:])
  31. url = re.findall(r'(https?://[^\s]+)', msg)
  32. for i in url:
  33. parsed_url = urlparse(i)
  34. if parsed_url.netloc.lower() in ['twitter.com','t.co', 'x.com'] or parsed_url.scheme != 'https':
  35. continue
  36. try:
  37. reqs = requests.get(i)
  38. except requests.exceptions.SSLError:
  39. print("SSLERROR: wrong signature type")
  40. continue
  41. soup = BeautifulSoup(reqs.text, 'html.parser')
  42. try:
  43. title_text = soup.find('title').get_text()
  44. except:
  45. print("Error: Title not found!")
  46. continue
  47. title_text = title_text.split('\n')
  48. title_msg = []
  49. # remove empty lines from title body
  50. for line in title_text:
  51. if not line.strip():
  52. continue
  53. title_msg.append(line)
  54. title_msg = " ".join(title_msg)
  55. print(f"Title: {title_msg}")
  56. ircc.send(channel, f"Title: {title_msg}")