To implement a bot that handles changes in dynDNS, you would need to write an interpreter for the
dynamicdns-update.py script used by the
dyn-dns.sh file. Here's a basic guide on how you can do it:
Step 1: Install Python and the required libraries
``
bash
sudo apt-get update && sudo apt-get install python3
`
Step 2: Create a new Python interpreter configuration file for the bot account
`
bash
sudo nano /root/.hermes/ accounts//bot_config.py
`
Replace with your own account name. We'll create a basic setup that logs to a console.
In bot_config.py, add the following code:
`python
import logging
# Set up logging
logging.basicConfig(format=[%(asctime)s - %(levelname)s - %(module)s: %(message)s],
level=logging.INFO)
# Your bot's credentials here, or use the settings below to auto-generate them
TOKEN='***'
GROUP_ID = '@GROUP_TOKEN'
try:
# ... existing code ...
except Exception as e:
logging.error(f"Error: {e}")
`
Replace TOKEN and GROUP_ID with your bot's actual token, which you'll receive when the bot is set up in Dynamo and receives its tokens.
Step 3: Create an interpreter for the dynDNSUpdate.py script
`bash
sudo nano /root/.hermes/skills/dyn-dns.sh.interpreter
`
Add the following code to enable Python as the interpreter:
`python
#!/bin/python
import sys
sys.argv = ['/root/.hermes/path/to/dyn-dns.sh']
if len(sys.argv) < 1:
print("Usage: $0 [log_file]")
else:
parser = argparse.ArgumentParser()
parser.add_argument('[log_file]', nargs='?', default=sys.stdout)
args = parser.parse_args()
# Use the sys.exit() to prevent Python from exiting when any part of it finishes execution
def parse_args():
return ['python3', '-m', 'argparse', script_name, *args]
dyn_dns_update_script = args.log_file or None
dynUpdate = parse_args()
exec(dyn_update_script + '\n') # ... execute the dynamically-loaded module ...
`
This interpreter uses argparse to parse arguments and run the specified DynDNS update script.
To create your bot's account, follow these steps:
1. Run sudo python3 /root/.hermes/skills/dyn-dns_bot_setup.py --token setup-bot in a terminal that allows you to add or modify accounts.
2. The bot will install the account and ask for its own password to add to the list of trusted accounts.
Please follow these precise directions to create the interpreter: cat /root/.hermes/skills/dyn-dns.sh.interpreter contains details about how it should run on most platforms, but keep in mind that an environment like a production bot may be different. And don’t forget to replace with your actual dynDNS token.
Once the above steps are done, you can execute the dyn-dns.sh script by using the dyn-dns_update.py script in other Python scripts to dynamically update the account's IP addresses.
Here is a python code snippet (DynUpdateScript) that defines two functions: updateAccountAndSendReplies() and sendReplyMessage().
`python
def dynUpdate(script):
# run the command executed by this DynDNS Bot Setup script to get the updated DynDNS server info, update the account list in /root/.hermes/skills/account_list, and execute new commands on the local dynamic IP addresses.
try:
ip = exec.script(script)
# Run a custom executable on 'ip' obtained above
cmd = f"nproc; python3 /root/.hermes/skills/account_send.py {ip}")
os.system(f"{cmd} > /var/log/dyn-dns_update.log")
except Exception as e:
print(f"Error during process: {e}")
def sendReplyMessage(message sender_account_id, sender_username):
# Get the private channels for each user in the database
all_channels = []
for account_data in dyn_dns_account_list:
if account_data['username'] == sender_username:
recipient_info = {
'recipient_id': sender.account_id,
'token': sender_token # the token your bot was authenticated with
}
if not any(account_rec in sender_channel['recipients'] for account_rec in account_data['channels']):
all_channels.append([account_rec, recipient_info])
# Use a dictionary of key-value pairs to build a template for the message we want to send back
reply_message = {
'recipient_id': sender_account_id,
'status_type': 'success',
'user_message': f"""
Reply to: {sender_username}
{{ {list(all_channels) } | join('\n', '.') }}
"""
}
# You may also have a template for when the bot should send this reply:
# reply_template = {
# 'replace_string1': 'string 1',
# 'replace_string2': 'string 2',
# }
response_channel_name = recipient_info.get('recipient_id', "")
message_from = sender.username
if not any(account_rec in sender_channel['recipients'] for account_rec in sender_channel['channels']):
all_channels.append([response_channel_name, {'action':'update account and reply'.format(*sender_name)}])
# Build the actual JSON response
json_response = {
'dyn_dns_update_status': True,
# Include info about each DynDNS channel involved
dyn_dns_data: {
channel_for_the_answer_included: {'status_type': sender_user_id, 'user_message': reply_message} | all_channels
}
}
return json_response
# Now you can create an Account object and let the bot send replies for its own DynDNS account
DynAccount = {
username='Bot Name',
channels=[{'recipient_id':'recipient1', 'token':sender_token}, {'recipient_id':'recipient2','token':sender_token}],
IP_address=ip,
}
sendReplyMessage(DynAccount, DynAccount)
`
Here’s the full Python implementation.
`python
import logging
# Set up logging
logging.basicConfig(format=[%(asctime)s - %(levelname)s - %(module)s: %(message)s],
level=logging.INFO)
# Your bot's credentials here
TOKEN='***'
GROUP_ID = '@Group_token'
try:
# ... existing code ...
except Exception as e:
logging.error(f"Error: {e}")
class DynUpdateScript():
def updateAccountAndSendReplies(self, script):
# ... execute the script passed to this DynDNS Bot Setup script via sys.execv()
print("dynUpdateScript Started")
def dynUpdate(script):
ip = exec.script(script)
updateAccountAndSendReplies(DynDynDNSUpdater())
sendReplyMessage('Bot_username', 'Bot_user')
`
Please ensure that your bot has been properly configured to use the @Token from Dynamo.
Also, be aware about all potential issues with DynDNS and scripts.
Always refer a new issue or question on dyn-dns.sh if you have any problems while executing these steps in your system.
If you find yourself stuck with using non-standard Python interpreter versions for your dynamic IP updates, you can use the same dynUpdate script as used above. To do this:
# In your DynDNS code set the path of /root/.hermes/tools/Python 3.x on other systems to be
# /path/to/dyn-dns.sh.interpreter
python3 dyn-dns-script.js
Now you can still run the same dynUpdate.py script but now it will dynamically update accounts instead of sending messages:
`python
from DynDynamic DNS import dyn_update
dyn_update()
``