Перейти к содержимому

Дополнительные примеры отправки сообщений

Как получить app-токен канала — см. «Отправка сообщений».

Во всех примерах сервер — https://api.notifly.ru, тело запроса — JSON, а app-токен передаётся заголовком X-Notifly-Key. Для Go и Python есть официальные SDK — с ними не нужно собирать запросы вручную.

#!/bin/bash
TITLE="My Title"
MESSAGE="Hello: ![](https://notifly.ru/img/logo.png)"
PRIORITY=5
TOKEN="<apptoken>"
curl -s -S -X POST "https://api.notifly.ru/message" \
-H "X-Notifly-Key: $TOKEN" \
-H "Content-Type: application/json" \
--data '{"message": "'"${MESSAGE}"'", "title": "'"${TITLE}"'", "priority":'"${PRIORITY}"', "extras": {"client::display": {"contentType": "text/markdown"}}}'

Если текст может содержать кавычки или переводы строк, собирайте JSON через jq, а не склейкой строк:

Окно терминала
jq -n --arg t "$TITLE" --arg m "$MESSAGE" '{title: $t, message: $m, priority: 5}' |
curl -s -S -X POST "https://api.notifly.ru/message" \
-H "X-Notifly-Key: $TOKEN" -H "Content-Type: application/json" --data @-
import requests # pip install requests
resp = requests.post(
"https://api.notifly.ru/message",
headers={"X-Notifly-Key": "<apptoken>"},
json={
"message": "Well hello there.",
"priority": 2,
"title": "This is my title",
},
timeout=10,
)
resp.raise_for_status()
package main
import (
"bytes"
"encoding/json"
"log"
"net/http"
)
func main() {
body, _ := json.Marshal(map[string]any{
"title": "My Title",
"message": "My Message",
"priority": 5,
})
req, _ := http.NewRequest("POST", "https://api.notifly.ru/message", bytes.NewReader(body))
req.Header.Set("X-Notifly-Key", "<apptoken>")
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
log.Println(resp.Status)
}
$data = [
"title"=> "Hello World",
"message"=> "Test push From PHP cURL.",
"priority"=> 5,
];
$data_string = json_encode($data);
$url = "https://api.notifly.ru/message";
$headers = [
"Content-Type: application/json; charset=utf-8",
"X-Notifly-Key: <apptoken>",
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close ($ch);
switch ($code) {
case "200":
echo "<strong>Your Message was Submitted</strong>";
break;
case "400":
echo "<strong>Bad Request</strong>";
break;
case "401":
echo "<strong>Unauthorized Error - Invalid Token</strong>";
break;
case "403":
echo "<strong>Forbidden</strong>";
break;
case "429":
echo "<strong>Daily quota exceeded</strong>";
break;
default:
echo "<strong>Hmm Something Went Wrong or HTTP Status Code is Missing</strong>";
}
const response = await fetch('https://api.notifly.ru/message', {
method: 'POST',
headers: {
'X-Notifly-Key': '<apptoken>',
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'Hello from JavaScript',
message: 'Test Push Service from Node.js',
priority: 5,
}),
});
if (!response.ok) {
console.error(response.status, await response.text());
} else {
console.log(await response.json());
}

Не встраивайте app-токен в код публичной веб-страницы: его увидит любой посетитель. Для отправки событий прямо со страницы сайта есть WebScript.

С зависимостью Maven:

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>

И код:

package com.notifly.client;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class NotiflyClient {
private static final String BASE_URL = "https://api.notifly.ru";
private static final String TOKEN = "<YOUR_TOKEN>";
public static void main(String[] args) throws IOException, InterruptedException {
final var client = new NotiflyClient(BASE_URL, TOKEN);
final var message = new Message("My Title", "Hello from Java!", 10);
if (client.sendMessage(message)) {
System.out.println("Message sent!");
} else {
System.out.println("Something went wrong :(.");
}
}
private final String notiflyUrl;
private final String token;
private final HttpClient httpClient;
private final ObjectMapper objectMapper;
public NotiflyClient(String baseUrl, String token) {
this.notiflyUrl = baseUrl + "/message";
this.token = token;
this.httpClient = HttpClient.newHttpClient();
this.objectMapper = new ObjectMapper();
}
private boolean sendMessage(Message message) throws IOException, InterruptedException {
final var bodyData = objectMapper.writeValueAsString(message);
final var request = HttpRequest.newBuilder()
.uri(URI.create(notiflyUrl))
.header("Content-Type", "application/json")
.header("X-Notifly-Key", token)
.POST(HttpRequest.BodyPublishers.ofString(bodyData))
.build();
final var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
return response.statusCode() >= 200 && response.statusCode() < 400;
}
public static class Message {
private String message;
private String title;
private int priority;
public Message(String title, String message, int priority) {
this.message = message;
this.priority = priority;
this.title = title;
}
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
public int getPriority() { return priority; }
public void setPriority(int priority) { this.priority = priority; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
}
}
Const NOTIFLY_URL As String = "https://api.notifly.ru/message"
Const NOTIFLY_TOKEN As String = "<apptoken>"
'--- Based on pushover-vba by Mauricio Arieira (https://github.com/makah/pushover-vba)
' Внимание: title и message вставляются в JSON как есть — экранируйте в них кавычки и обратные слэши.
Public Function PushToNotifly(ByVal title As String, ByVal message As String, ByVal priority As Integer) As String
Dim xhttp As Object, body As String
body = "{""title"": """ & title & """, ""message"": """ & message & """, ""priority"": " & priority & "}"
Set xhttp = CreateObject("MSXML2.ServerXMLHTTP")
With xhttp
.Open "POST", NOTIFLY_URL, False
.setRequestHeader "Content-Type", "application/json; charset=utf-8"
.setRequestHeader "X-Notifly-Key", NOTIFLY_TOKEN
.Send body
PushToNotifly = .responseText
End With
End Function
' Test PushToNotifly function
Public Sub Test_PushToNotifly()
Debug.Print PushToNotifly("My Title", "Hello there!", 2)
End Sub
Окно терминала
token="<apptoken>"
subject="wget"
message="Test push from wget"
priority=5
wget "https://api.notifly.ru/message" \
--header "X-Notifly-Key: $token" \
--header "Content-Type: application/json" \
--post-data "{\"title\": \"$subject\", \"message\": \"$message\", \"priority\": $priority}" \
-O /dev/null