This is an example Python code snippet that demonstrates how to create a cron job in the Discord API to handle tasks related to dyn DNS updates. The script logs information about each update and sends notifications accordingly.
Please note that you need to install and configure the
discord.py library, which requires your bot token as an environment variable or using a configuration file for authenticating with the API.
Here's how the code snippet works:
1. It creates a function called
/cf-dyndns.sh, which can be used as a cron job to run this script.
2. The
/cf-dyndns.sh line is executed, and its output will be directed to
/root/.hermes/skills/cf-dyndns.log in your home directory.
3. Based on the output, three notifications are sent:
* If the dyn DNS update status is "STATUS:NO_CHANGE", the message remains unchanged, just sending
NO_REPLY.
* If there's an error ("ERROR" or a non-zero exit), two messages are sent to Telegram private channels and another one to your Discord account.
4. The script checks for dyn DNS updates and sends notifications accordingly.
Please ensure that you have your bot token ready and configured correctly as environmental variables, and configure the Discord API permissions required by this script before running the cron job.
``
bash
#!/usr/bin/env python3
import logging
# Set up logging
logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO)
logger = logging.getLogger(__name__)
def get_updates(token, dryrun=False):
"""
Dyn DNS update function for this script.
Returns a list of dictionaries containing the status of each dyn DNS event.
:param token: The bot's Discord API token
:return:
"""
try:
response = requests.get("https://api.dyndns.net/v1/events",
headers={"Authorization": f"Bearer {token}"})
update_info = {}
for event in response.json()["events"]:
if not update_info[event["status"]]:
logger.info(f"New Dyn DNS update: Event type '{event['type']}' detected")
# Here, we'd fetch the relevant information from any relevant API.
info = {
"title": event.get("source", {}).get("name"),
"description": event.get("source", {}).get("detail"),
"data_link": event["url"],
... # We need to add more properties for each dyn DNS update
}
update_info[event["type"]] = info
return list(update_info.values())
except Exception as e:
logger.error(f"Error fetching updates: {e}")
if dryrun:
print("\n".join((f"[INFO]: {update}" for update in update_info.keys()]))
def main():
# Initialize the Dyn DNS data object
dyn_data = {"events": []}
token = "YOUR_BOT_TOKEN"
while True:
updates = get_updates(token, dryrun=True)
if len(updates['events']) == 0:
logger.info("No update information available")
elif any(update_info[event["type"]] for event, update_info in zip(updates['events'], dyn_data.values())):
print("\nFound updates:")
# Here, you could send notifications or take further action based on these updates.
if updates['events']:
logger.info("Dyn DNS updated:", "\n".join(value for key, value in updates['events'][0].items()))
else:
logger.info("No dyn DNS updates")
else:
print("\nNo dyn DNS events available.")
# Here, the script will wait and check again in 1 second.
time.sleep(1)
if __name__ == "__main__":
main()
``