titlebot.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # -*- coding: utf-8 -*-
  2. import re
  3. import irc
  4. import requests
  5. from bs4 import BeautifulSoup
  6. from urllib.parse import urlparse
  7. ## IRC Config
  8. server = "127.0.0.1"
  9. port = 11070
  10. channels = ["#test", "#test1"]
  11. botnick = "website-title"
  12. ircc = irc.IRC()
  13. ircc.connect(server, port, channels, botnick)
  14. while True:
  15. text = ircc.get_response()
  16. if not len(text) > 0:
  17. continue
  18. print(text)
  19. text_list = text.split(' ')
  20. if text_list[1] == "PRIVMSG":
  21. channel = text_list[2]
  22. msg = ' '.join(text_list[3:])
  23. url = re.findall(r'(https?://[^\s]+)', msg)
  24. for i in url:
  25. parsed_url = urlparse(i)
  26. if parsed_url.netloc.lower() in ['twitter.com','t.co'] or parsed_url.scheme != 'https':
  27. continue
  28. reqs = requests.get(i)
  29. soup = BeautifulSoup(reqs.text, 'html.parser')
  30. try:
  31. title_text = soup.find('title').get_text()
  32. except:
  33. print("Error: Title not found!")
  34. continue
  35. title_text = title_text.split('\n')
  36. title_msg = []
  37. # remove empty lines from tweet body
  38. for line in title_text:
  39. if not line.strip():
  40. continue
  41. title_msg.append(line)
  42. title_msg = " ".join(title_msg)
  43. print(f"Title: {title_msg}")
  44. ircc.send(channel, f"Title: {title_msg}")