### Install and Run React App Source: https://github.com/songquanpeng/message-pusher/blob/master/web/README.md Commands to install project dependencies, start the development server, and build the application for production. Ensure Node.js and npm are installed. These commands are executed in the project's root directory. ```shell npm install npm start npm run build ``` -------------------------------- ### Configure React Server URL with Environment Variable Source: https://github.com/songquanpeng/message-pusher/blob/master/web/README.md Example of setting the REACT_APP_SERVER environment variable to change the default server URL before building the production application. This allows customization of the backend API endpoint. ```shell REACT_APP_SERVER=http://your.domain.com ``` -------------------------------- ### Configure and Use Group Channels for Multi-Channel Broadcast Source: https://context7.com/songquanpeng/message-pusher/llms.txt This example shows how to first create individual notification channels and then group them into a single 'group channel'. Messages sent to this group channel are simultaneously delivered to all channels within the group, ensuring broad notification coverage. ```shell # First, create individual channels # (assuming you have channels: telegram_personal, email_work, lark_team) # Create a group channel that combines multiple channels curl -X POST "https://push.example.com/api/channel" \ -H "Content-Type: application/json" \ -H "Cookie: session=your_session_cookie" \ -d '{ "type": "group", "name": "all_channels", "description": "Send to all my notification channels", "other": "{\"channels\":[\"telegram_personal\",\"email_work\",\"lark_team\"]}" }' # Send message to group (will push to all channels in the group) curl -X POST "https://push.example.com/push/admin" \ -H "Content-Type: application/json" \ -d '{ "title": "Critical Alert", "description": "Database connection lost", "content": "## Issue Details\n- **Time**: 2024-01-15 10:30\n- **Affected**: Production DB\n- **Action**: Investigating", "channel": "all_channels", "token": "your_token" }' # Response: {"success":true,"message":"","uuid":"..."} # Message will be sent through Telegram, Email, and Lark simultaneously ``` -------------------------------- ### Bash: Channel-Level Token Authentication Setup Source: https://context7.com/songquanpeng/message-pusher/llms.txt Bash commands using `curl` to demonstrate setting up channel-level authentication tokens and pushing messages using these tokens. This involves creating a channel with a specific token and then using that token to authenticate push requests to that channel. Assumes a running API server. ```bash # Create channel with dedicated token curl -X POST "https://push.example.com/api/channel" \ -H "Content-Type: application/json" \ -H "Cookie: session=your_session_cookie" \ -d '{ "type": "lark", "name": "production_alerts", "description": "Production system alerts only", "secret": "webhook_url_from_lark", "token": "channel_specific_secret_token_123" }' # Push to channel using channel token (not user token) curl -X POST "https://push.example.com/push/admin" \ -H "Content-Type: application/json" \ -d '{ "title": "Production Alert", "description": "High memory usage detected", "channel": "production_alerts", "token": "channel_specific_secret_token_123" }' ``` -------------------------------- ### Push Message via GET Request (Bash) Source: https://context7.com/songquanpeng/message-pusher/llms.txt Send messages using URL query parameters, compatible with Server酱 API format. Supports basic messages, Markdown content, and asynchronous delivery. Requires a token for authentication. ```bash # Basic message push with title and description curl "https://push.example.com/push/admin?title=System+Alert&description=Server+load+high&token=your_token_here" # Markdown content with custom channel curl "https://push.example.com/push/admin?title=Deploy+Success&description=Production+deployed&content=**Version**:+v1.2.3%0A**Time**:+2024-01-15&channel=lark&token=your_token_here" # Async push with code rendering curl "https://push.example.com/push/admin?description=Build+output&content=npm+run+build%0ASuccess!&render_mode=code&async=true&token=your_token_here" # Response for async request: # {"success":true,"message":"","uuid":"a1b2c3d4-e5f6-7890-abcd-ef1234567890"} ``` -------------------------------- ### Push Message via GET Request Source: https://context7.com/songquanpeng/message-pusher/llms.txt Send messages using URL query parameters. This method is compatible with the Server酱 API format and supports basic text, Markdown content, and asynchronous delivery. ```APIDOC ## GET /push/{username} ### Description Send messages using URL query parameters, compatible with Server酱 API format. ### Method GET ### Endpoint `/push/{username}` ### Parameters #### Query Parameters - **title** (string) - Optional - The title of the message. - **description** (string) - Optional - The main body or description of the message. - **content** (string) - Optional - Detailed content, supports Markdown if `render_mode` is not 'code'. - **token** (string) - Required - The authentication token for the user. - **channel** (string) - Optional - Specifies a particular channel to send the message through (e.g., 'lark', 'wechat'). If not provided, messages are sent through default channels. - **render_mode** (string) - Optional - Controls how the `content` is rendered. Supported values: 'markdown', 'code'. Defaults to 'markdown'. - **async** (boolean) - Optional - If true, the message is sent asynchronously. Defaults to false. ### Request Example ```bash # Basic message push with title and description curl "https://push.example.com/push/admin?title=System+Alert&description=Server+load+high&token=your_token_here" # Markdown content with custom channel curl "https://push.example.com/push/admin?title=Deploy+Success&description=Production+deployed&content=**Version**:+v1.2.3%0A**Time**:+2024-01-15&channel=lark&token=your_token_here" # Async push with code rendering curl "https://push.example.com/push/admin?description=Build+output&content=npm+run+build%0ASuccess!&render_mode=code&async=true&token=your_token_here" ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - Details about the operation status. - **uuid** (string) - A unique identifier for the message, especially for asynchronous requests. #### Response Example (Async Request) ```json { "success": true, "message": "", "uuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" } ``` ``` -------------------------------- ### Python: Message Client for API Interaction Source: https://context7.com/songquanpeng/message-pusher/llms.txt A Python client to interact with the Message Pusher API. It supports retrieving paginated messages, getting specific message details, searching messages by keyword, checking message send status, resending, and deleting messages. Requires the 'requests' library. ```python import requests class MessageClient: def __init__(self, server, session_cookie): self.server = server self.session = requests.Session() self.session.headers.update({'Cookie': session_cookie}) def get_messages(self, page=0): """Get paginated message history""" resp = self.session.get(f"{self.server}/api/message?p={page}") result = resp.json() if result["success"]: return result["data"] raise Exception(result["message"]) def get_message(self, message_id): """Get specific message details""" resp = self.session.get(f"{self.server}/api/message/{message_id}") result = resp.json() if result["success"]: return result["data"] raise Exception(result["message"]) def search_messages(self, keyword): """Search messages by keyword""" resp = self.session.get( f"{self.server}/api/message/search", params={"keyword": keyword} ) result = resp.json() if result["success"]: return result["data"] raise Exception(result["message"]) def get_message_status(self, uuid): """Check async message send status""" resp = self.session.get(f"{self.server}/api/message/status/{uuid}") result = resp.json() if result["success"]: status = result["status"] # 1: sent, 2: failed, 3: pending return {1: "sent", 2: "failed", 3: "pending"}[status] raise Exception(result["message"]) def resend_message(self, message_id): """Resend a previous message""" resp = self.session.post(f"{self.server}/api/message/resend/{message_id}") result = resp.json() return result["success"] def delete_message(self, message_id): """Delete a message""" resp = self.session.delete(f"{self.server}/api/message/{message_id}") result = resp.json() return result["success"] # Usage example client = MessageClient("https://push.example.com", "session=cookie_value") # Get recent messages messages = client.get_messages(page=0) for msg in messages: print(f"{msg['id']}: {msg['title']} - {msg['description']}") # Search for error messages errors = client.search_messages("error") # Check async message status status = client.get_message_status("a1b2c3d4-e5f6-7890-abcd-ef1234567890") print(f"Message status: {status}") ``` -------------------------------- ### User Authentication and Management API Source: https://context7.com/songquanpeng/message-pusher/llms.txt APIs for registering, logging in, and managing user accounts, including role-based permissions and API token generation. ```APIDOC ## User Authentication and Management Register, login, and manage user accounts with role-based permissions. ### POST /api/user/login #### Description Logs in a user with provided credentials. #### Method POST #### Endpoint /api/user/login #### Request Body - **username** (string) - Required - The username for login. - **password** (string) - Required - The password for login. #### Response Example (Success) ```json { "success": true, "message": "Login successful", "data": { "id": "user-id", "username": "admin" } } ``` ### GET /api/user/self #### Description Retrieves the information of the currently logged-in user. #### Method GET #### Endpoint /api/user/self #### Parameters #### Query Parameters - **Cookie** (string) - Required - The session cookie obtained after login. #### Response Example (Success) ```json { "success": true, "data": { "id": "user-id", "username": "admin", "display_name": "Administrator", "role": "admin", "status": "active" } } ``` ### GET /api/user/token #### Description Generates an API token for programmatic access for the current user. #### Method GET #### Endpoint /api/user/token #### Parameters #### Query Parameters - **Cookie** (string) - Required - The session cookie obtained after login. #### Response Example (Success) ```json { "success": true, "data": "your_api_token_here" } ``` ### PUT /api/user/self #### Description Updates the preferences and settings for the currently logged-in user. #### Method PUT #### Endpoint /api/user/self #### Parameters #### Query Parameters - **Cookie** (string) - Required - The session cookie obtained after login. #### Request Body - **display_name** (string) - Optional - The display name for the user. - **channel** (string) - Optional - The default push channel for notifications. - **token** (string) - Optional - The API token for programmatic access. #### Response Example (Success) ```json { "success": true, "message": "Profile updated successfully" } ``` ``` -------------------------------- ### Webhook Integration with Go Source: https://context7.com/songquanpeng/message-pusher/llms.txt Enables the creation and triggering of custom webhooks for integrating external notifications. This Go code allows defining extraction and construction rules for incoming data and sending payloads to a specified webhook URL. Requires a running Message Pusher server. ```go package main import ( "bytes" "encoding/json" "fmt" "log" "net/http" ) // Create a webhook adapter func createWebhook(sessionCookie string) (string, error) { webhook := map[string]interface{}{ "name": "github_webhook", "channel": "lark", "extract_rule": map[string]string{ "repo": "repository.name", "action": "action", "sender": "sender.login", }, "construct_rule": map[string]string{ "title": "GitHub Event", "description": "[$action] by $sender on $repo", "content": "**Repository**: $repo\n**Action**: $action\n**User**: $sender", }, } data, _ := json.Marshal(webhook) req, _ := http.NewRequest( "POST", "https://push.example.com/api/webhook", bytes.NewBuffer(data), ) req.Header.Set("Content-Type", "application/json") req.Header.Set("Cookie", sessionCookie) resp, err := http.DefaultClient.Do(req) if err != nil { return "", err } defer resp.Body.Close() var result map[string]interface{} json.NewDecoder(resp.Body).Decode(&result) // Returns webhook URL like: https://push.example.com/webhook/{uuid} return result["data"].(map[string]interface{})["link"].(string), nil } // Trigger webhook from external system func sendToWebhook(webhookURL string, payload interface{}) error { data, _ := json.Marshal(payload) resp, err := http.Post( webhookURL, "application/json", bytes.NewBuffer(data), ) if err != nil { return err } defer resp.Body.Close() var result map[string]interface{} json.NewDecoder(resp.Body).Decode(&result) if !result["success"].(bool) { return fmt.Errorf(result["message"].(string)) } return nil } // Example: GitHub webhook payload func handleGitHubWebhook(webhookURL string) { payload := map[string]interface{}{ "action": "opened", "repository": map[string]interface{}{ "name": "my-project", }, "sender": map[string]interface{}{ "login": "johndoe", }, } err := sendToWebhook(webhookURL, payload) if err != nil { log.Println("Webhook error:", err) } } ``` -------------------------------- ### Send Admin Push Notification using User Token Source: https://context7.com/songquanpeng/message-pusher/llms.txt Demonstrates how to send an admin push notification using a user's global token, which overrides channel-specific tokens. This is useful for privileged operations or system-wide alerts. ```shell curl -X POST "https://push.example.com/push/admin" \ -H "Authorization: Bearer user_global_token" \ -d '{ "title": "Alert", "description": "Message", "channel": "production_alerts" }' ``` -------------------------------- ### User Authentication and Management with JavaScript Source: https://context7.com/songquanpeng/message-pusher/llms.txt Handles user registration, login, and account management using the Axios HTTP client. It supports retrieving user information, generating API tokens, and updating user profiles. Requires a running Message Pusher server and user credentials. ```javascript const axios = require('axios'); const SERVER = 'https://push.example.com'; // User login async function login(username, password) { const response = await axios.post(`${SERVER}/api/user/login`, { username: username, password: password }); if (response.data.success) { console.log('Logged in:', response.data.data); // Store session cookie from response headers return response.headers['set-cookie']; } else { throw new Error(response.data.message); } } // Get current user info async function getSelf(sessionCookie) { const response = await axios.get(`${SERVER}/api/user/self`, { headers: { 'Cookie': sessionCookie } }); return response.data.data; // Returns: { id, username, display_name, role, status } } // Generate API token for programmatic access async function generateToken(sessionCookie) { const response = await axios.get(`${SERVER}/api/user/token`, { headers: { 'Cookie': sessionCookie } }); if (response.data.success) { const token = response.data.data; console.log('API Token:', token); return token; } } // Update user preferences async function updateProfile(sessionCookie, updates) { const response = await axios.put( `${SERVER}/api/user/self`, { display_name: updates.displayName, channel: updates.defaultChannel, // Default push channel token: updates.apiToken }, { headers: { 'Cookie': sessionCookie } } ); return response.data; } // Example usage (async () => { try { const cookie = await login('admin', 'password123'); const user = await getSelf(cookie); const token = await generateToken(cookie); await updateProfile(cookie, { displayName: 'Administrator', defaultChannel: 'telegram' }); } catch (error) { console.error('Error:', error.message); } })(); ``` -------------------------------- ### Webhook Integration API Source: https://context7.com/songquanpeng/message-pusher/llms.txt APIs for creating and managing webhooks to integrate external system notifications with message pushes. ```APIDOC ## Webhook Integration Create custom webhooks to adapt external system notifications into message pushes. ### POST /api/webhook #### Description Creates a new webhook adapter to process incoming notifications from external systems. #### Method POST #### Endpoint /api/webhook #### Parameters #### Query Parameters - **sessionCookie** (string) - Required - The session cookie obtained after login. #### Request Body - **name** (string) - Required - The name of the webhook. - **channel** (string) - Required - The target channel for push notifications (e.g., 'lark', 'telegram'). - **extract_rule** (object) - Required - Rules for extracting relevant data from incoming payloads. - **repo** (string) - Example field for extraction. - **action** (string) - Example field for extraction. - **sender** (string) - Example field for extraction. - **construct_rule** (object) - Required - Rules for constructing the message content. - **title** (string) - Template for the message title. - **description** (string) - Template for the message description. - **content** (string) - Template for the message content. #### Request Example ```json { "name": "github_webhook", "channel": "lark", "extract_rule": { "repo": "repository.name", "action": "action", "sender": "sender.login" }, "construct_rule": { "title": "GitHub Event", "description": "[$action] by $sender on $repo", "content": "**Repository**: $repo\n**Action**: $action\n**User**: $sender" } } ``` #### Response Example (Success) ```json { "success": true, "data": { "link": "https://push.example.com/webhook/{uuid}" } } ``` ### POST /webhook/{uuid} #### Description Triggers a webhook with a specific payload, sending a message through the configured channel. #### Method POST #### Endpoint /webhook/{uuid} #### Path Parameters - **uuid** (string) - Required - The unique identifier of the webhook. #### Request Body - **payload** (object) - Required - The data payload from the external system. #### Request Example ```json { "action": "opened", "repository": { "name": "my-project" }, "sender": { "login": "johndoe" } } ``` #### Response Example (Success) ```json { "success": true, "message": "Message pushed successfully" } ``` ``` -------------------------------- ### Channel-Level Token Authentication API Source: https://context7.com/songquanpeng/message-pusher/llms.txt Enables channel-specific authentication tokens for granular access control. This section details how to create channels with dedicated tokens and how to use these tokens for pushing messages to specific channels. ```APIDOC ## POST /api/channel ### Description Create a new channel with a dedicated token for authentication. ### Method POST ### Endpoint /api/channel ### Parameters #### Request Body - **type** (string) - Required - The type of the channel (e.g., "lark"). - **name** (string) - Required - The unique name of the channel. - **description** (string) - Optional - A description for the channel. - **secret** (string) - Required - The secret associated with the channel (e.g., webhook URL from Lark). - **token** (string) - Required - The channel-specific secret token for authentication. ### Request Example ```json { "type": "lark", "name": "production_alerts", "description": "Production system alerts only", "secret": "webhook_url_from_lark", "token": "channel_specific_secret_token_123" } ``` #### Success Response (201 Created) Indicates the channel was created successfully. ## POST /push/{destination} ### Description Push a message to a specific channel using its channel-specific token. ### Method POST ### Endpoint /push/{destination} ### Parameters #### Path Parameters - **destination** (string) - Required - The destination for the push, often "admin" or similar. #### Request Body - **title** (string) - Required - The title of the message. - **description** (string) - Optional - The description of the message. - **channel** (string) - Required - The name of the target channel. - **token** (string) - Required - The channel-specific secret token for authentication. ### Request Example ```json { "title": "Production Alert", "description": "High memory usage detected", "channel": "production_alerts", "token": "channel_specific_secret_token_123" } ``` #### Success Response (200 OK) Indicates the message was successfully pushed to the specified channel. ``` -------------------------------- ### Channel Management API (Bash) Source: https://context7.com/songquanpeng/message-pusher/llms.txt Manage message delivery channels via REST API endpoints. Supports creating, listing, updating status, and deleting channels. Requires session cookies for authentication and uses JSON payloads for requests. ```bash # Create a new Telegram channel curl -X POST "https://push.example.com/api/channel" \ -H "Content-Type: application/json" \ -H "Cookie: session=your_session_cookie" \ -d '{ "type": "telegram", "name": "my_telegram", "description": "Personal Telegram notifications", "secret": "bot_token_from_botfather", "account_id": "chat_id_or_username" }' # Response: # {"success":true,"message":""} # List all channels (paginated) curl "https://push.example.com/api/channel?p=0" \ -H "Cookie: session=your_session_cookie" # Response: # { # "success": true, # "message": "", # "data": [ # { # "id": 1, # "type": "telegram", # "name": "my_telegram", # "description": "Personal Telegram notifications", # "status": 1, # "created_time": 1705305600 # } # ] # } # Get brief channel list (for dropdowns) curl "https://push.example.com/api/channel?brief=1" \ -H "Cookie: session=your_session_cookie" # Update channel status (enable/disable) curl -X PUT "https://push.example.com/api/channel?status_only=1" \ -H "Content-Type: application/json" \ -H "Cookie: session=your_session_cookie" \ -d '{ "id": 1, "status": 2 }' # Delete a channel curl -X DELETE "https://push.example.com/api/channel/1" \ -H "Cookie: session=your_session_cookie" ``` -------------------------------- ### Push Message via POST JSON (Bash) Source: https://context7.com/songquanpeng/message-pusher/llms.txt Send messages with structured JSON payload for complex scenarios. Requires Content-Type and Authorization headers, including a Bearer token. Supports detailed message content and URLs. ```bash curl -X POST "https://push.example.com/push/admin" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer your_token_here" \ -d '{ "title": "Database Backup Complete", "description": "Daily backup completed successfully", "content": "## Backup Summary\n- **Database**: production_db\n- **Size**: 2.3GB\n- **Duration**: 15 minutes\n- **Status**: ✅ Success", "channel": "email", "url": "https://backup.example.com/logs/2024-01-15" }' # Response: # {"success":true,"message":"","uuid":"message-unique-id"} # Error response example: # {"success":false,"message":"无效的 token"} ``` -------------------------------- ### Send Messages to Multiple Users or Broadcast via Go Source: https://context7.com/songquanpeng/message-pusher/llms.txt This Go function sends messages to specified users or broadcasts to all users ('@all'). It constructs a JSON payload for the push API, handling user list formatting and error checking from the API response. ```go package main import ( "bytes" "encoding/json" "net/http" "strings" "fmt" ) func sendToMultipleUsers(token string, users []string, title, description string) error { // users format: ["user1", "user2", "user3"] or "@all" for broadcast to := "" if len(users) == 1 && users[0] == "@all" { to = "@all" } else { to = strings.Join(users, "|") } message := map[string]interface{}{ "title": title, "description": description, "channel": "email", "to": to, "token": token, } data, _ := json.Marshal(message) resp, err := http.Post( "https://push.example.com/push/admin", "application/json", bytes.NewBuffer(data), ) if err != nil { return err } defer resp.Body.Close() var result map[string]interface{} json.NewDecoder(resp.Body).Decode(&result) if !result["success"].(bool) { return fmt.Errorf(result["message"].(string)) } return nil } // Send to specific users // sendToMultipleUsers( // "your_token", // []string{"alice", "bob", "charlie"}, // "Team Meeting", // "Daily standup at 10 AM", // ) // Broadcast to all users // sendToMultipleUsers( // "your_token", // []string{"@all"}, // "System Maintenance", // "Scheduled maintenance tonight at 2 AM", // ) ``` -------------------------------- ### Channel Management API Source: https://context7.com/songquanpeng/message-pusher/llms.txt APIs for creating, retrieving, updating, and deleting message delivery channels. ```APIDOC ## Channel Management API ### Description Create and manage multiple message delivery channels per user. ### POST /api/channel #### Description Create a new message delivery channel. #### Method POST #### Endpoint `/api/channel` #### Parameters ##### Request Body - **type** (string) - Required - The type of channel (e.g., 'telegram', 'email', 'wechat'). - **name** (string) - Required - A unique name for the channel. - **description** (string) - Optional - A description for the channel. - **secret** (string) - Required - The secret token or key for the channel (e.g., bot token for Telegram). - **account_id** (string) - Optional - The account ID or chat ID for the channel. #### Request Example ```bash # Create a new Telegram channel curl -X POST "https://push.example.com/api/channel" \ -H "Content-Type: application/json" \ -H "Cookie: session=your_session_cookie" \ -d '{ "type": "telegram", "name": "my_telegram", "description": "Personal Telegram notifications", "secret": "bot_token_from_botfather", "account_id": "chat_id_or_username" }' ``` #### Response (Success) - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - Details about the operation status. #### Response Example ```json { "success": true, "message": "" } ``` ### GET /api/channel #### Description List channels, with options for pagination and brief representation. #### Method GET #### Endpoint `/api/channel` #### Parameters ##### Query Parameters - **p** (integer) - Optional - Page number for pagination. Defaults to 0. - **brief** (integer) - Optional - If set to 1, returns a brief list of channels. #### Request Example ```bash # List all channels (paginated) curl "https://push.example.com/api/channel?p=0" \ -H "Cookie: session=your_session_cookie" # Get brief channel list (for dropdowns) curl "https://push.example.com/api/channel?brief=1" \ -H "Cookie: session=your_session_cookie" ``` #### Response (Success) - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - Details about the operation status. - **data** (array) - An array of channel objects. - **id** (integer) - Unique identifier for the channel. - **type** (string) - The type of the channel. - **name** (string) - The name of the channel. - **description** (string) - The description of the channel. - **status** (integer) - The status of the channel (e.g., 1 for enabled, 2 for disabled). - **created_time** (integer) - Timestamp of channel creation. #### Response Example ```json { "success": true, "message": "", "data": [ { "id": 1, "type": "telegram", "name": "my_telegram", "description": "Personal Telegram notifications", "status": 1, "created_time": 1705305600 } ] } ``` ### PUT /api/channel #### Description Update channel status (enable/disable). #### Method PUT #### Endpoint `/api/channel` #### Parameters ##### Query Parameters - **status_only** (integer) - Optional - If set to 1, only the status field can be updated. ##### Request Body - **id** (integer) - Required - The ID of the channel to update. - **status** (integer) - Required - The new status for the channel (e.g., 1 for enabled, 2 for disabled). #### Request Example ```bash curl -X PUT "https://push.example.com/api/channel?status_only=1" \ -H "Content-Type: application/json" \ -H "Cookie: session=your_session_cookie" \ -d '{ "id": 1, "status": 2 }' ``` #### Response (Success) - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - Details about the operation status. ### DELETE /api/channel/{id} #### Description Delete a specific channel. #### Method DELETE #### Endpoint `/api/channel/{id}` #### Parameters ##### Path Parameters - **id** (integer) - Required - The ID of the channel to delete. #### Request Example ```bash curl -X DELETE "https://push.example.com/api/channel/1" \ -H "Cookie: session=your_session_cookie" ``` #### Response (Success) - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - Details about the operation status. ``` -------------------------------- ### POST /api/channel - Channel Management Source: https://context7.com/songquanpeng/message-pusher/llms.txt Manages notification channels, including creating new channels, specifying their type (e.g., 'group'), and configuring their settings. ```APIDOC ## POST /api/channel ### Description Manages notification channels. This endpoint is used to create new channels, including group channels that aggregate multiple individual channels. ### Method POST ### Endpoint https://push.example.com/api/channel ### Parameters #### Request Body - **type** (string) - Required - The type of channel to create. Use 'group' for group channels. - **name** (string) - Required - The name of the channel. - **description** (string) - Optional - A description for the channel. - **other** (string) - Optional - Additional configuration specific to the channel type. For group channels, this should be a JSON string containing a 'channels' array of channel names (e.g., '{"channels":["telegram_personal","email_work"]}') ### Request Example (Create Group Channel) ```bash curl -X POST "https://push.example.com/api/channel" \ -H "Content-Type: application/json" \ -H "Cookie: session=your_session_cookie" \ -d '{ "type": "group", "name": "all_channels", "description": "Send to all my notification channels", "other": "{\"channels\":[\"telegram_personal\",\"email_work\",\"lark_team\"]}" }' ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the channel operation was successful. - **message** (string) - A status message. - **uuid** (string) - The identifier for the created or managed channel. ``` -------------------------------- ### Message Query and Management API Source: https://context7.com/songquanpeng/message-pusher/llms.txt Provides endpoints for retrieving, searching, and managing sent messages with pagination support. These endpoints allow for fetching message history, specific message details, searching messages by keyword, checking asynchronous send status, resending messages, and deleting messages. ```APIDOC ## GET /api/message ### Description Get paginated message history. ### Method GET ### Endpoint /api/message ### Parameters #### Query Parameters - **p** (integer) - Optional - Page number for pagination. Defaults to 0. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **data** (array) - An array of message objects. - **id** (integer) - Unique identifier for the message. - **title** (string) - The title of the message. - **description** (string) - The description of the message. - **content** (string) - The content of the message. - **channel** (string) - The channel the message was sent to. - **timestamp** (integer) - The Unix timestamp when the message was sent. - **status** (integer) - The status of the message (e.g., 1: sent, 2: failed, 3: pending). - **message** (string) - A message describing the outcome of the request. #### Response Example ```json { "success": true, "data": [ { "id": 123, "title": "System Alert", "description": "CPU usage high", "content": "Details about CPU usage", "channel": "system", "timestamp": 1705305600, "status": 1 } ], "message": "Messages retrieved successfully" } ``` ## GET /api/message/{message_id} ### Description Get specific message details by its ID. ### Method GET ### Endpoint /api/message/{message_id} ### Parameters #### Path Parameters - **message_id** (integer) - Required - The ID of the message to retrieve. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **data** (object) - The message object. - **id** (integer) - Unique identifier for the message. - **title** (string) - The title of the message. - **description** (string) - The description of the message. - **content** (string) - The content of the message. - **channel** (string) - The channel the message was sent to. - **timestamp** (integer) - The Unix timestamp when the message was sent. - **status** (integer) - The status of the message. - **message** (string) - A message describing the outcome of the request. #### Response Example ```json { "success": true, "data": { "id": 123, "title": "System Alert", "description": "CPU usage high", "content": "Details about CPU usage", "channel": "system", "timestamp": 1705305600, "status": 1 }, "message": "Message details retrieved successfully" } ``` ## GET /api/message/search ### Description Search messages by a keyword. ### Method GET ### Endpoint /api/message/search ### Parameters #### Query Parameters - **keyword** (string) - Required - The keyword to search for within messages. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **data** (array) - An array of message objects matching the keyword. - **message** (string) - A message describing the outcome of the request. #### Response Example ```json { "success": true, "data": [ { "id": 456, "title": "Error Notification", "description": "An error occurred in the database", "content": "Error details...", "channel": "notifications", "timestamp": 1705305600, "status": 2 } ], "message": "Messages searched successfully" } ``` ## GET /api/message/status/{uuid} ### Description Check the status of an asynchronously sent message using its UUID. ### Method GET ### Endpoint /api/message/status/{uuid} ### Parameters #### Path Parameters - **uuid** (string) - Required - The unique identifier (UUID) of the asynchronous message. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **status** (integer) - The status of the message (1: sent, 2: failed, 3: pending). - **message** (string) - A message describing the outcome of the request. #### Response Example ```json { "success": true, "status": 1, "message": "Message status retrieved successfully" } ``` ## POST /api/message/resend/{message_id} ### Description Resend a previously sent message. ### Method POST ### Endpoint /api/message/resend/{message_id} ### Parameters #### Path Parameters - **message_id** (integer) - Required - The ID of the message to resend. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the message was successfully resent. #### Response Example ```json { "success": true } ``` ## DELETE /api/message/{message_id} ### Description Delete a message. ### Method DELETE ### Endpoint /api/message/{message_id} ### Parameters #### Path Parameters - **message_id** (integer) - Required - The ID of the message to delete. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the message was successfully deleted. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Real-time Message Stream (SSE) API Source: https://context7.com/songquanpeng/message-pusher/llms.txt Allows clients to subscribe to real-time message updates using Server-Sent Events (SSE). This endpoint provides a continuous stream of new messages as they are sent. ```APIDOC ## GET /api/message/stream ### Description Subscribe to real-time message updates using Server-Sent Events (SSE). ### Method GET ### Endpoint /api/message/stream ### Parameters No explicit parameters are required for the endpoint itself, but authentication via session cookie is expected. ### Response #### Success Response (200) This endpoint returns a stream of Server-Sent Events. Each event contains a JSON payload representing a new message. - **Event Data (JSON)**: - **id** (integer) - Unique identifier for the message. - **title** (string) - The title of the message. - **description** (string) - The description of the message. - **content** (string) - The content of the message. - **channel** (string) - The channel the message was sent to. - **timestamp** (integer) - The Unix timestamp when the message was sent. - **status** (integer) - The status of the message. #### Response Example (SSE format) ``` id: 1 event: message data: {"id": 123, "title": "Alert", "description": "System notification", "content": "...", "channel": "telegram", "timestamp": 1705305600, "status": 1} id: 2 event: message data: {"id": 124, "title": "Update", "description": "New version available", "content": "...", "channel": "system", "timestamp": 1705305610, "status": 1} ``` ``` -------------------------------- ### JavaScript: Real-time Message Stream via SSE Source: https://context7.com/songquanpeng/message-pusher/llms.txt JavaScript code to subscribe to real-time message updates using Server-Sent Events (SSE). It establishes a connection to the message stream endpoint, handles incoming messages, displays notifications, and manages connection errors with automatic reconnection. This requires a browser environment. ```javascript // Connect to SSE endpoint for live message updates function subscribeToMessages(sessionCookie) { const eventSource = new EventSource( 'https://push.example.com/api/message/stream', { withCredentials: true } ); eventSource.onmessage = (event) => { const message = JSON.parse(event.data); console.log('New message:', message); // message structure: // { // id: 123, // title: "Alert", // description: "System notification", // content: "...", // channel: "telegram", // timestamp: 1705305600, // status: 1 // } displayNotification(message); }; eventSource.onerror = (error) => { console.error('SSE connection error:', error); eventSource.close(); // Reconnect after 5 seconds setTimeout(() => subscribeToMessages(sessionCookie), 5000); }; return eventSource; } function displayNotification(message) { // Update UI with new message const notification = document.createElement('div'); notification.className = 'notification'; notification.innerHTML = ` ${message.title}

${message.description}

${new Date(message.timestamp * 1000).toLocaleString()} `; document.getElementById('notifications').prepend(notification); } // Start listening const stream = subscribeToMessages(document.cookie); // Clean up when page unloads window.addEventListener('beforeunload', () => { stream.close(); }); ``` -------------------------------- ### Push Message via POST Form (Python) Source: https://context7.com/songquanpeng/message-pusher/llms.txt Send messages using form-encoded data with Python's requests library. This method is suitable for simpler integrations and requires basic message parameters and a token. ```python import requests SERVER = "https://push.example.com" USERNAME = "admin" TOKEN = "your_secret_token" def send_message(title, description, content): res = requests.post( f"{SERVER}/push/{USERNAME}", data={ "title": title, "description": description, "content": content, "token": TOKEN } ) result = res.json() if result["success"]: print(f"Message sent! UUID: {result['uuid']}") else: print(f"Error: {result['message']}") # Send notification send_message( "Training Complete", "Model training finished", "**Accuracy**: 94.5%\n**Loss**: 0.032\n**Epochs**: 50" ) ```