Skip to content

Instantly share code, notes, and snippets.

@vadimreutskiy
Last active April 15, 2023 23:17
Show Gist options
  • Save vadimreutskiy/3822513ba8243c5b1c30db1064f90f41 to your computer and use it in GitHub Desktop.
Save vadimreutskiy/3822513ba8243c5b1c30db1064f90f41 to your computer and use it in GitHub Desktop.
Get external IP of the current machine from one of the services and send it to the Telegram chat using bot API
# Script initially generated by ChatGPT with GPT-4 and manually modified in some details
import requests
import os
import socket
import logging
import smtplib
from email.message import EmailMessage
from typing import Tuple, Optional
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
# Replace with your own bot token and chat_id
bot_token = "TELEGRAM_BOT_TOKEN"
chat_id = "TELEGRAM_CHAT_ID"
# Email credentials
email_address = "SENDER_EMAIL"
email_password = "SENDER_APP_PASSWORD"
recipient_email = "RECIPIENT_EMAIL"
def send_email(subject, body):
msg = EmailMessage()
msg.set_content(body)
msg["Subject"] = subject
msg["From"] = email_address
msg["To"] = recipient_email
try:
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
server.login(email_address, email_password)
server.send_message(msg)
logging.info("Email sent successfully")
except Exception as e:
logging.error(f"Failed to send email: {e}")
def is_valid_ipv4_address(ip):
try:
socket.inet_pton(socket.AF_INET, ip)
except AttributeError: # no inet_pton here, sorry
try:
socket.inet_aton(ip)
except socket.error:
return False
return ip.count(".") == 3
except socket.error: # not a valid address
return False
return True
def get_external_ip(services) -> Tuple[Optional[str], Optional[str]]:
for service in services:
try:
response = requests.get(service, timeout=5)
response.raise_for_status()
ip = response.text.strip()
if is_valid_ipv4_address(ip):
return ip, service
except requests.exceptions.RequestException as e:
logging.warning(f"Getting IP from {service} failed with error {e}")
return None, None
ip_services = [
"https://ipecho.net/plain",
"https://api.ipify.org?format=text",
"http://checkip.amazonaws.com/",
"https://ipinfo.io/ip",
"http://icanhazip.com/",
"http://ifconfig.me/ip",
"http://ip-api.com/line?fields=query",
"https://myexternalip.com/raw",
]
external_ip, service_name = get_external_ip(ip_services)
if external_ip:
# Specify the temporary file to store the last known IP address
temp_file = "last_known_ip.txt"
# Check if the temporary file exists and read the content
if os.path.exists(temp_file):
with open(temp_file, "r") as file:
last_known_ip = file.read()
else:
last_known_ip = ""
# Compare the current external IP with the last known IP
if external_ip != last_known_ip:
# Save the current IP to the temporary file
with open(temp_file, "w") as file:
file.write(external_ip)
# Prepare the message
message = f"The current external IP has changed from {last_known_ip} to: {external_ip} (obtained from {service_name})"
# Send message to the Telegram channel
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
payload = {"chat_id": chat_id, "text": message}
requests.post(url, data=payload)
# Send email notification
send_email("External IP Address Changed", message)
else:
logging.error("Unable to fetch IP address from any of the services.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment