Yes, you can simplify the script by using the cloudflare package for Python instead of making API calls directly using requests. Here's an updated version of the script using the cloudflare package:
import cloudflare
import socket
# set variables
zone_name = 'your_zone_name_here'
record_name = 'your_record_name_here'
api_token = 'your_api_token_here'
# authenticate with Cloudflare API
cf = cloudflare.CloudFlare(token=api_token)
# get zone ID
zones = cf.zones.get(params={'name': zone_name})
if len(zones) == 0:
raise ValueError(f'Zone "{zone_name}" not found in your Cloudflare account.')
zone_id = zones[0]['id']
# get DNS record ID
records = cf.zones.dns_records.get(zone_id, params={'name': record_name})
if len(records) == 0:
raise ValueError(f'DNS record "{record_name}" not found in your Cloudflare account.')
record = records[0]
record_id = record['id']
record_type = record['type']
# get current public IP address
def get_ip():
return socket.gethostbyname(socket.gethostname())
# get current DNS record IP address
def get_record_ip():
result = cf.zones.dns_records.get(zone_id, record_id)
return result['content']
# update DNS record with new IP address
def update_record_ip(ip_address):
cf.zones.dns_records.put(zone_id, record_id, data={
'type': record_type,
'name': record_name,
'content': ip_address,
})
# main function to check for IP address changes and update DNS records
def main():
current_ip = get_ip()
record_ip = get_record_ip()
print(f'Current IP: {current_ip}')
print(f'Record IP: {record_ip}')
if current_ip != record_ip:
print('IP address has changed. Updating DNS record...')
update_record_ip(current_ip)
print('DNS record has been updated.')
else:
print('IP address has not changed.')
# run the script indefinitely
while True:
try:
main()
except Exception as e:
print(f'Error: {e}')
pass
In this script, we first authenticate with the Cloudflare API using the cloudflare.CloudFlare class and pass in our API token.
We then use the cf.zones.get() and cf.zones.dns_records.get() methods to get the zone and DNS record IDs for our domain/subdomain.
Next, we define our get_ip(), get_record_ip(), and update_record_ip() functions as before, but use the cf.zones.dns_records.put() method to update the DNS record instead of making an API call directly.
Finally, we run the main function in a while loop as before.
Note that in this script, we're using socket.gethostbyname(socket.gethostname()) to get the current public IP address instead of making a request to an external API. This assumes that your Raspberry Pi is directly connected to the internet and not behind a NAT router. If you're behind a NAT router, you'll need to use a service like ipify.org to get your public IP address.