You want to write a script that performs specific tasks in response to certain commands on Telegram or Discord channels. To help you with this, I'll outline the steps for running your script and then provide explanations of each step.
1. **Installation**: Make sure you have Python 3.x installed on your server. You can install it using pip:
sudo apt-get update && sudo pip install python3 (On Ubuntu-based systems) or
sudo yum install python3 (On Rocky-based systems).
2. **Create a Script**: Create a new file with a
.py extension, for example,
dynnats.sh.
3. **Add Shebang Line and Comments**: Add the following line at the top of your script:
#!/usr/bin/env python3. And include comments above each section that shows what the code is doing.
4. **Check Command Parameters**: The first task you can do in Python is use regular expressions to parse text with commands, but this isn't quite right without more info about command parameters.
5. **Get User Input and Exit Message**: Run this part as a cron job (more on that below).
6. **Handle Successful Updates**: When DynDNS's update status changes (
STATUS:OK or
HTTP/1.1 200, which indicates successful connection reestablishment), your script should send an "OK:
" message.
7. **Handle Non-Successful Updates**: If the update fails, your script should send a message stating that something went wrong ("ERROR").
8. **Send No Change Notice**:
Now I'll outline the next steps:
To find out how to add cron jobs on Ubuntu-based systems, you can follow these steps:
``
sudo crontab -e
`
Edit the new file created in step 4. Add a line for your custom cron job. Below * * * * * /bin/your_script_name.sh use */1 to trigger every 1 minute.
You should have the following format:
`
* * * * * /bin/your_script_name.sh
`
To add new lines above it, press shift-tab (TAB) on i, then enter a single line that contains your desired function.
If you want more help with this part of the process: [FAQ - How to schedule tasks in Ubuntu](https://ubuntufocal.org/questions/5039/scheduling-python-tasks-using-cron)
Now, here is an example how to write dynnats for telegram or docker and push it using pydnn:
To start, let's make a python class with function which runs the cron job.
`python
import time
from subprocess import run
class Dynnats:
def __init__(self):
self.target = 'telegra.photogrid.com'
self.user_id = None # you must get telegram user ID using Telegram Bot API
telegram_token, private_token = "your-telegram-bot-token", "your-private-telegram-token" # your bot token & a valid Telegram app token
def get_user_id(self):
return run(f'curl -s -f https://api.telegram.org/bot{self.user_id}/getUpdates', stdout=subprocess.PIPE).stdout.decode('utf-8')
@staticmethod
def dynamnats(dynnats_object):
target_url = f'https://{dynnats_object.target}/status.php'
input_data = {
'user': dynnats_object.get_user_id(),
'action': 'set',
'mode': 0,
'value': ''
}
response = run(['curl', '-X', 'POST', target_url, json=str(input_data)])
try:
if response.stdout != b'HTTP/1.1 200 OK':
raise Exception(f'message:{response.stderr.decode("utf-8")}')
except (OSError, KeyError) as exc:
print(exc)
exit(2)
def run_task(self):
try:
output = 'dynnats:' + request['text'] + '|'
end_output = request['end_output']
if isinstance(end_output,"string"):
task = {
"id": self.get_user_id(),
"command": request["command"],
"parameters": [],
"inputs": []
}
Dynnats.dynamnats(task)
print(f'Command: {request ["command"]}, Task ID: {self.get_user_id()}\ngot reply from dynnats')
else:
task = {
"id": self.get_user_id(),
"command": 'DynNATS',
"parameters": [],
"inputs": []
}
Dynnats.dynamnats(task)
print(f'Command: {request["command"]}')
except Exception as exc:
print(exc)
`
Remember to replace your-telegram-bot-token at the end of this example with your actual Telegram app token. Don't forget to install required libraries by using pip:
`bash
pip install psutil requests json
psql-binary: https://github.com/dnngu/python-dnn-python-binary releases/gh-pages/latest tarballs/tar.gz;git clone https://github.com/dnngu/python-dnn-python-binary.git
``
Your tasks should now run in the background once you've saved them, and the server will update your DynDNS instances based on the input commands and output messages from Telegram.