tweetifier.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # -*- coding: utf-8 -*-
  2. import re
  3. import signal
  4. import irc
  5. from tweety import Twitter
  6. from urllib.parse import urlparse
  7. ## IRC Config
  8. server = "127.0.0.1"
  9. port = 11069
  10. channels = ["#test", "#test1"]
  11. botnick = "tweetifier"
  12. ircc = irc.IRC()
  13. ircc.connect(server, port, channels, botnick)
  14. def signal_handler(sig, frame):
  15. print("Caught termination signal, cleaning up and exiting...")
  16. ircc.disconnect(server, port)
  17. print("Shut down successfully")
  18. exit(0)
  19. signal.signal(signal.SIGINT, signal_handler)
  20. while True:
  21. text = ircc.get_response().strip()
  22. if not len(text) > 0:
  23. continue
  24. print(text)
  25. text_list = text.split(' ')
  26. if text_list[1] == "PRIVMSG":
  27. channel = text_list[2]
  28. msg = ' '.join(text_list[3:])
  29. url = re.findall(r'(https?://[^\s]+)', msg)
  30. for i in url:
  31. parsed_url = urlparse(i)
  32. if str(parsed_url.path).endswith("/"):
  33. tweetId = str(parsed_url.path)[:-1].split("/")[-1]
  34. else:
  35. tweetId = str(parsed_url.path).split("/")[-1]
  36. print(f"tweet id: {tweetId}")
  37. if not (parsed_url.netloc.lower() in ['twitter.com','t.co', 'x.com'] and parsed_url.scheme == 'https'):
  38. continue
  39. app = Twitter("session")
  40. try:
  41. tweet_text = app.tweet_detail(tweetId)
  42. except:
  43. print("Error: The Identifier provided of the tweet is either invalid or the tweet is private")
  44. continue
  45. author_name = tweet_text.author.name
  46. screen_name = tweet_text.author.screen_name
  47. tt = tweet_text.text.split('\n')
  48. tweet_msg = []
  49. # remove empty lines from tweet body
  50. for line in tt:
  51. if not line.strip():
  52. continue
  53. tweet_msg.append(line)
  54. tweetify = str(' '.join(tweet_msg))
  55. if tweetify.startswith("@"):
  56. tweetify = f"Replying to {tweetify}"
  57. print(tweetify)
  58. ircc.send(channel, f"{author_name}(@{screen_name}): {tweetify}")