tweetifier.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. print("Error: disconnected from server")
  24. exit(-1)
  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 str(parsed_url.path).endswith("/"):
  34. tweetId = str(parsed_url.path)[:-1].split("/")[-1]
  35. else:
  36. tweetId = str(parsed_url.path).split("/")[-1]
  37. print(f"tweet id: {tweetId}")
  38. if not (parsed_url.netloc.lower() in ['twitter.com','t.co', 'x.com'] and parsed_url.scheme == 'https'):
  39. continue
  40. app = Twitter("session")
  41. try:
  42. tweet_text = app.tweet_detail(tweetId)
  43. except:
  44. print("Error: The Identifier provided of the tweet is either invalid or the tweet is private")
  45. continue
  46. author_name = tweet_text.author.name
  47. screen_name = tweet_text.author.screen_name
  48. tt = tweet_text.text.split('\n')
  49. tweet_msg = []
  50. # remove empty lines from tweet body
  51. for line in tt:
  52. if not line.strip():
  53. continue
  54. tweet_msg.append(line)
  55. tweetify = str(' '.join(tweet_msg))
  56. if tweetify.startswith("@"):
  57. tweetify = f"Replying to {tweetify}"
  58. print(tweetify)
  59. ircc.send(channel, f"{author_name}(@{screen_name}): {tweetify}")