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