Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ touch .env

```sh
NTFY_WS = "ntfy.sh/"
NTFY_ACCESS_CONTROL = "<ACCESS TOKEN>" # This field is optional, only there in case you need to use some authentication. You will need to generate an access token as explained here: https://docs.ntfy.sh/publish/#access-tokens
NTFY_TOPIC ="<YOUR TOPIC>"
TELEGRAM_BOT = "https://api.telegram.org/bot<YOUR BOT API TOKEN>/sendMessage"
TELEGRAM_ID = "<CHAT ID>"
Expand All @@ -54,6 +55,7 @@ RUN pip install --upgrade pip
RUN pip3 install requests python-dotenv websocket-client
ENV NTFY_WS = "ntfy.sh/"
ENV NTFY_TOPIC ="<YOUR TOPIC>"
ENV NTFY_ACCESS_CONTROL = "<ACCESS TOKEN>"
ENV TELEGRAM_BOT = "https://api.telegram.org/bot<YOUR BOT API TOKEN>/sendMessage"
ENV TELEGRAM_ID = "<CHAT ID>"
COPY ntfy.py /usr/bin
Expand Down
33 changes: 29 additions & 4 deletions ntfy.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,37 @@
load_dotenv()

ntfy_ws = os.environ["NTFY_WS"]
ntfy_access_control = os.environ.get("NTFY_ACCESS_CONTROL") # Use .get to handle if not defined
ntfy_topic = os.environ["NTFY_TOPIC"]
telegram_bot = os.environ["TELEGRAM_BOT"]
chat_id = os.environ["TELEGRAM_ID"]

def escape_markdown_v2(text):
"""Escapes characters for MarkdownV2."""
escape_chars = '_*[]()~`>#+-=|{}.!'
return ''.join(['\\' + char if char in escape_chars else char for char in text])

def on_message(ws, message):
msg = json.loads(message)
if not 'title' in msg or len(msg['title']) == 0:
if not msg.get('title', '').strip() and not msg.get('message', '').strip():
print('\n >>> Ntfy.sh websocket Successfully Passing...! \n')
else:
# Only add the title and \n\n if there is a non-empty title key
text_content = ''
if msg.get('title', '').strip():
escaped_title = escape_markdown_v2(msg['title'].strip())
text_content += '**' + escaped_title + '**\n\n' # Add the escaped title, if any

if msg.get('message', '').strip():
escaped_message = escape_markdown_v2(msg['message'].strip())
text_content += escaped_message # Add the escaped message, if any

headers = {"content-type": "application/x-www-form-urlencoded"}
querystring = {"chat_id": chat_id, "text": msg['title'] + "\n\n" + msg['message']}
querystring = {
"chat_id": chat_id,
"text": text_content,
"parse_mode": "MarkdownV2" # Enable Markdown v2 formatting
}
response = requests.request(
"POST", telegram_bot, headers=headers, params=querystring)
print("websocket: " + message + "Ntfy: " + response.text)
Expand All @@ -32,9 +52,14 @@ def on_open(ws):
print("\n >> Opened NTFY websocket connection..! \n")

if __name__ == "__main__":
headers = []
if ntfy_access_control: # Add the header only if ntfy_access_control is defined and not empty
headers.append("Authorization: Bearer " + str(ntfy_access_control))

wsapp = websocket.WebSocketApp("wss://" + str(ntfy_ws) + ntfy_topic + "/ws",
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close)
wsapp.run_forever()
on_close=on_close,
header=headers) # headers is now conditionally populated
wsapp.run_forever()