titlebot.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. continue
  25. print(text)
  26. text_list = text.split(' ')
  27. if text_list[1] == "PRIVMSG":
  28. channel = text_list[2]
  29. msg = ' '.join(text_list[3:])
  30. url = re.findall(r'(https?://[^\s]+)', msg)
  31. for i in url:
  32. parsed_url = urlparse(i)
  33. if parsed_url.netloc.lower() in ['twitter.com','t.co', 'x.com'] or parsed_url.scheme != 'https':
  34. continue
  35. try:
  36. reqs = requests.get(i)
  37. except requests.exceptions.SSLError:
  38. print("SSLERROR: wrong signature type")
  39. continue
  40. soup = BeautifulSoup(reqs.text, 'html.parser')
  41. try:
  42. title_text = soup.find('title').get_text()
  43. except:
  44. print("Error: Title not found!")
  45. continue
  46. title_text = title_text.split('\n')
  47. title_msg = []
  48. # remove empty lines from title body
  49. for line in title_text:
  50. if not line.strip():
  51. continue
  52. title_msg.append(line)
  53. title_msg = " ".join(title_msg)
  54. print(f"Title: {title_msg}")
  55. ircc.send(channel, f"Title: {title_msg}")