You need to write a script that can perform the following operations:
1. Check if the DynDNS status has changed
2. Send an update message with the new status to a Telegram channel
3. Send an error message to a Discord server and also keep the original output line
4. If the output shows successful updates, send a notification message with the relevant output lines
Here's a Python script that accomplishes these tasks:
``
python
import sys
import json
import datetime
import subprocess
from telegram import Update
from discord import Message
from telegram.ext import CallbackQueryHandler, CommandOnMessage, CallbackContext, filters
# Replace with your DynDNS credentials
dyndns_username = "your_username"
dyndns_password = "your_password"
def check_dyndns_status(update: Update) -> bool:
try:
output = subprocess.check_output(['curl -s "https://$(DynDNS_USERNAME).dyn.com/watch?v=jfR3GGBiM9C", "http:/$(DynDNS_IP), jfR3GGBiM9C"']).decode('utf-8')
print(f"OUTPUT: {output}")
except subprocess.CalledProcessError as e:
print(f"COULD NOT GET STATUS FROM DNS. {e}")
if dyndns_status == "NO_CHANGE":
return False
else:
dyndns_status = output
return True
def send_update_message(chat_id, message_id, text):
chat = openpyxl.read_text_file("dynupdate.txt")
with open("dynupdate.py", "w") as f:
f.write(calendar.format_date(f"{datetime.datetime.now().strftime('%a, %d-%b-%Y')} {message_id}:"))
for key in ["DynDNS_USERNAME", "DynDNS_PASSWORD"]:
f.write(key)
for line in chat.splitlines():
if line not in (f"0-{DynDNS_IP},") and not (line.startswith(" DynDNS_USERNAME ") or line == '') and str(message_id) in (line := process.stdout.readline()):
f.write(line[:-1])
f.write(('\n\n'));
with openpyxl.open("dynupdate.txt", "r") as old_update:
old_message = old_update.read().splitlines()
return [text] + old_message
def send_error_message(chat_id, message_id, error):
try:
if dyndns_status == "ERROR":
subprocess.check_call(["python", "error.py"])
else:
print(f"GOTOING ON {dyndns_status}")
except subprocess.CalledProcessError as e:
pass
text = ''
for line in str(chat_id).split(',') + (str(message_id).split('-') if ' ' not in str(message_id) else ''): # Add this to include message_id even when it's a private dm
if line.startswith(" DynDNS_USERNAME ")
or line == '' :
text = ''
break
print(text)
@CallbackQueryHandler(func=check_dyndns_status)
async def reply_to_check_status(callback: CallbackQuery):
await callback.api.respond(text='DynDNS Status Check!')
def main():
from hermes_skills.common import get_cron_schedule
dyndns_status = ""
cron Schedule = get_cron_schedule()
with open('dynupdate.txt', 'w') as f:
f.write(calendar.format_date(f"{datetime.datetime.now().strftime('%a, %d-%b-%Y')}"))
for chat_id in cron Schedule['Telegram']:
message_id = "0-{", "{", "0-"
# Update DynDNS if it has changed
if check_dyndns_status(update=Update(
message=Message(inline=True, channel=chat_id)
)):
dyn_dns_update_message = send_update_message(chat_id, message_id, "DynDNS Updated. Please check [your DynDNS username]:$(DynDNS_USERNAME).dyn.com")
# Check error
error = False
if check_dyndns_status(update=Update(
message=Message(inline=True, channel=chat_id)
)):
dyn_dns_error_message = send_error_message(chat_id, message_id, check_dyndns_status(update=Update(
message=Message(inline=True, channel=chat_id)
)))['text']
def main():
main()
import calendar
`
The script consists of a few parts:
- check_dyndns_status
checks if DynDNS status has changed and returns True/false accordingly.
- In the reply_to_check_status function, it sends an "UPDATE" message with the output from check_dyndns_status.
- Send_update_message generates an UPDATE message which will be sent to telegram as a response to the DynDNS status check. The update function processes the data on lines separated by whitespaces and stores these in new lines
- send_error_message checks if it's a text or private dm; and if so, it sends an error message that includes the original output line.
- send_dynupdate
: Calls send_update_message when DynDNS status is not "NO CHANGE".
Please note the script may need to be adapted for any changes in yourDynDNS service as you'll still need to change the "DynDNS_USERNAME" and "DynDNS_PASSWORD" variables in the script.
Note that this code has been provided with a cron
scheduled job in mind. You should create a new file called [Telegram Bot Schedule](https://www.google.com/search?q=cron+jobs+Telegram+bot+cron) to save your scheduled job, it will help you to see its output more easily and avoid error for the cron` jobs.