Created
October 23, 2024 19:09
-
-
Save quang-m-nguyen/21f2c76c3cf9d5cd0aed33f8a98da5cd to your computer and use it in GitHub Desktop.
Notify IP Change Via Slack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import requests | |
from slack_sdk import WebClient | |
from slack_sdk.errors import SlackApiError | |
# Set the environment variables | |
os.environ['SLACK_CLIENT_ID'] = '' | |
os.environ['SLACK_CLIENT_SECRET'] = '' | |
os.environ['SLACK_SIGNING_SECRET'] = '' | |
os.environ['SLACK_BOT_TOKEN'] = '' | |
client = WebClient(token=os.environ['SLACK_BOT_TOKEN']) | |
IP_RECORD_FILE = 'last_ip.txt' | |
def get_ip_info(): | |
try: | |
response = requests.get('https://ipinfo.io/json') | |
response.raise_for_status() | |
ip_info = response.json() | |
ip_address = ip_info['ip'] | |
country = ip_info['country'] | |
return ip_address, country | |
except requests.RequestException as e: | |
print(f"Error getting IP information: {e}") | |
return None, None | |
def send_message(channel, text): | |
try: | |
response = client.chat_postMessage( | |
channel=channel, | |
text=text | |
) | |
print(f"Message sent: {response['message']['text']}") | |
except SlackApiError as e: | |
print(f"Error sending message: {e.response['error']}") | |
def read_last_ip(): | |
if os.path.exists(IP_RECORD_FILE): | |
with open(IP_RECORD_FILE, 'r') as file: | |
return file.read().strip() | |
return None | |
def write_last_ip(ip_address): | |
with open(IP_RECORD_FILE, 'w') as file: | |
file.write(ip_address) | |
if __name__ == "__main__": | |
ip_address, country = get_ip_info() | |
if ip_address and country: | |
if country == 'US': | |
print("IP address is from the US. Skipping save and notification.") | |
else: | |
last_ip_address = read_last_ip() | |
if last_ip_address != ip_address: | |
send_message('#ip-update', f'<@user_id> <@user_id> new IP address is: {ip_address}') | |
write_last_ip(ip_address) | |
else: | |
print(f"No change in IP address: {ip_address}") | |
else: | |
send_message('#ip-update', 'Failed to retrieve IP address and country information.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment