-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautomation.py
195 lines (171 loc) · 9.04 KB
/
automation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
import pytz
from datetime import datetime
import time
import openpyxl
import requests
import json
import pycountry
import re
from dotenv import load_dotenv
# Set the API token
load_dotenv()
client=WebClient(token=os.getenv('API'))
# API key for abuse IPdb
api_key = "811f20f61b2f71a30eb3205332868856b5dceef517acb8f243fa310df92936b7725a71a1ec5e6475"
# Set the desired channel ID
channel_id = "C016NLFF03B" #careem channel
# Set the reaction emoji
username = input("Please enter your username: ")
if username == "[email protected]":
reaction_emoji = "mzeeshan"
elif username == "[email protected]":
reaction_emoji = "maryam"
elif username == "[email protected]":
reaction_emoji = "abubakr"
elif username == "[email protected]":
reaction_emoji = "mujtaba"
elif username == "[email protected]":
reaction_emoji = "humna"
elif username == "[email protected]":
reaction_emoji = "abdur_rashid"
elif username == "[email protected]":
reaction_emoji = "haroon"
elif username == "[email protected]":
reaction_emoji = "shehrbano"
elif username == "[email protected]":
reaction_emoji = "saif"
elif username == "[email protected]":
reaction_emoji = "salman"
elif username == "[email protected]":
reaction_emoji = "hamzasaeed"
elif username == "[email protected]":
reaction_emoji = "talhagts"
elif username == "[email protected]":
reaction_emoji = "faraz"
elif username == "[email protected]":
reaction_emoji = "usama_mssp-soc"
else:
reaction_emoji = "👋"
# Define the time range in Pakistan time zone
timezone = pytz.timezone('Asia/Karachi')
start_time = timezone.localize(datetime(2023, 5, 23, 0, 0, 0)) # year, month, day, hour, minute, second
end_time = timezone.localize(datetime(2028, 5, 23, 23, 59, 59))
# Load the Excel file
if os.path.exists('data.xlsx'):
wb = openpyxl.load_workbook('data.xlsx')
else:
wb = openpyxl.Workbook()
wb.save('data.xlsx')
sheet = wb.active
sheet["A1"] = "Timestamp"
sheet["B1"] = "First Message"
sheet["C1"] = "Client"
sheet["D1"] = "Count"
sheet["E1"] = "Reputation"
sheet["F1"] = "Country Name"
# Get the timestamp of the last message that had a reaction added to it
last_message = None
try:
result = client.conversations_history(channel=channel_id, limit=1)
if len(result["messages"]) > 0:
last_message = result["messages"][0]
if len(last_message.get("reactions", [])) > 0:
last_timestamp = last_message["ts"]
except SlackApiError as e:
print("Error getting last message timestamp: {}".format(e))
# Initialize the list of processed message timestamps
processed_messages = []
while True:
try:
# Call the conversations.history method using the WebClient with the oldest and latest timestamp parameters
oldest_timestamp = last_message["ts"] if last_message else start_time.timestamp()
latest_result = client.conversations_history(channel=channel_id, oldest=oldest_timestamp, latest=end_time.timestamp())
# Iterate over each new message and add the reaction if it falls within the time range
for message in latest_result["messages"]:
message_time = datetime.fromtimestamp(float(message["ts"]), tz=pytz.utc).astimezone(timezone)
time_diff = datetime.now(timezone) - message_time
if time_diff.total_seconds() <= 180 and message["ts"] not in processed_messages:
if len(message.get("reactions", [])) == 0:
# Fetch the IP and first line of the message
client_ip = None
first_line = None
countryname= None
count = 1
for i, line in enumerate(message["text"].splitlines()):
# print (line)
if "client:" in line:
print (line)
if i + 1 < len(message["text"].splitlines()):
next_line = message["text"].splitlines()[i + 1]
ip_address = re.search(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', line)
if ip_address:
client_ip = ip_address.group()
print(client_ip)
else:
ip_address = re.search(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', next_line)
if ip_address:
client_ip = ip_address.group()
print(client_ip)
url = f"https://api.abuseipdb.com/api/v2/check?ipAddress={client_ip}"
headers = {"Key": api_key, "Accept": "application/json"}
response = requests.get(url, headers=headers)
if response.status_code == 200:
result = json.loads(response.text)["data"]
if result["abuseConfidenceScore"]:
print(f"IP address: {client_ip}\nReputation: {result['abuseConfidenceScore']}/100")
else:
print(f"IP address: {client_ip}\nReputation: Not available")
if result["countryCode"]:
country_code = result['countryCode']
print(f"Country Code: {country_code}")
try:
country_name = pycountry.countries.get(alpha_2=country_code).name
countryname = country_name
print(f"Country Name: {country_name}")
except Exception as e:
print(f"Error: Unable to retrieve country information from AbuseIPDB. {e}")
else:
print("Country: Not available")
elif first_line is None:
first_line = line.strip()
# Add the reaction and print a success message
client.reactions_add(channel=channel_id, timestamp=message["ts"], name=reaction_emoji)
print("Reaction added successfully for message {} in channel {}!".format(message["ts"], channel_id))
# checking for the duplication of ip addresses
# get the column headers
headers = [cell.value for cell in sheet[1]]
# get the last row index
last_row_index = sheet.max_row
# get the IP address from the new data
new_first_line= first_line
new_ip = client_ip
# check if the IP address already exists in the worksheet
ip_index = None
for i in range(2, last_row_index+1):
if sheet.cell(row=i, column=headers.index('Client')+1).value == new_ip and sheet.cell(row=i, column=headers.index('First Message')+1).value == new_first_line:
ip_index = i
break
# update the count value if the IP address exists, or add a new row otherwise
if ip_index:
count = sheet.cell(row=ip_index, column=headers.index('Count')+1).value + 1
old_row_index = ip_index
sheet.cell(row=ip_index, column=headers.index('Count')+1).value = count
sheet.cell(row=ip_index, column=headers.index('Timestamp')+1).value = message_time.strftime('%Y-%m-%d %H:%M:%S %Z%z')
row = sheet[ip_index]
sheet.delete_rows(old_row_index)
sheet.append(row)
# sheet.move_range(f"A{ip_index}:F{ip_index}", rows=last_row_index-1)
# Write first line and client IP to Excel file
else:
sheet.append([message_time.strftime('%Y-%m-%d %H:%M:%S %Z%z'), first_line, client_ip, count, result['abuseConfidenceScore'], countryname])
wb.save('data.xlsx')
processed_messages.append(message["ts"])
# Update the last message
last_message = latest_result["messages"][-1] if len(latest_result["messages"]) > 0 else last_message
except SlackApiError as e:
print("Error adding reactions: {}".format(e))
# Wait for 180 seconds before checking for new messages again
time.sleep(180)