### C: ServerChan Notification Implementation with libcurl Source: https://context7.com/easychen/serverchan-demo/llms.txt A low-level implementation of ServerChan notifications in C using the libcurl library. It handles sending POST requests with custom text and descriptions. Requires libcurl to be installed and linked during compilation. The SENDKEY should be set as an environment variable. ```c #include #include #include #include #define MAX_BUFFER_SIZE 1024 typedef struct { char* text; char* desp; char* key; } SCData; size_t write_callback(void* contents, size_t size, size_t nmemb, char* buffer) { size_t total_size = size * nmemb; strncat(buffer, contents, total_size); return total_size; } void sc_send(SCData* data) { CURL* curl; CURLcode res; char url[MAX_BUFFER_SIZE]; char post_data[MAX_BUFFER_SIZE]; char response[MAX_BUFFER_SIZE] = {0}; curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init(); if (curl) { // Determine endpoint based on sendkey format if (strncmp(data->key, "sctp", 4) == 0) { int num; if (sscanf(data->key, "sctp%dt", &num) == 1) { snprintf(url, MAX_BUFFER_SIZE, "https://%d.push.ft07.com/send/%s.send", num, data->key); } else { fprintf(stderr, "Invalid sendkey format\n"); curl_easy_cleanup(curl); curl_global_cleanup(); return; } } else { snprintf(url, MAX_BUFFER_SIZE, "https://sctapi.ftqq.com/%s.send", data->key); } snprintf(post_data, MAX_BUFFER_SIZE, "text=%s&desp=%s", data->text, data->desp); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, response); res = curl_easy_perform(curl); if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } else { printf("Response: %s\n", response); } curl_easy_cleanup(curl); } curl_global_cleanup(); } // Compile: gcc main.c -o serverchan -lcurl // Usage example int main() { char* sendkey = getenv("SENDKEY"); if (!sendkey) { fprintf(stderr, "SENDKEY not found in environment\n"); return 1; } SCData data = { .text = "Temperature Alert", .desp = "CPU: 85C\nGPU: 78C\n\nCooling system check required", .key = sendkey }; sc_send(&data); return 0; } ``` -------------------------------- ### Node.js Implementation Source: https://context7.com/easychen/serverchan-demo/llms.txt Example of sending Server酱 notifications using Node.js with the native `fetch` API. It demonstrates asynchronous sending and promise-based error handling. ```APIDOC ## Node.js Server酱 Notification ### Description This Node.js code snippet provides an asynchronous function `sc_send` to send notifications via Server酱 using the native `fetch` API. It handles endpoint detection and uses `async/await` for cleaner asynchronous operations. ### Method POST ### Endpoint Dynamically determined based on `sendkey` format: - Standard: `https://sctapi.ftqq.com/${key}.send` - Private Server: `https://${key.match(/^sctp(\d+)t/i)[1]}.push.ft07.com/send/${key}.send` ### Parameters #### Function Parameters - **text** (string) - Required - The title of the notification. - **desp** (string) - Optional - The content of the notification. Defaults to an empty string. - **key** (string) - Optional - Your Server酱 sendkey. Defaults to `[SENDKEY]`. It's recommended to load this from environment variables. ### Request Example ```javascript const https = require('https'); // Note: fetch is globally available in Node.js 18+ const querystring = require('querystring'); const fs = require('fs'); async function sc_send(text, desp = '', key = process.env.SENDKEY || '[SENDKEY]') { if (key === '[SENDKEY]') { console.warn('Warning: SENDKEY is not set. Using placeholder. Notifications will not be sent.'); } const postData = querystring.stringify({ text, desp }); // Determine endpoint based on sendkey format const isPrivateServer = String(key).match(/^sctp(\d+)t/i); const url = isPrivateServer ? `https://${isPrivateServer[1]}.push.ft07.com/send/${key}.send` : `https://sctapi.ftqq.com/${key}.send`; try { const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(postData) }, body: postData }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.text(); // ServerChan typically returns plain text or JSON try { return JSON.parse(data); // Attempt to parse as JSON } catch (e) { return data; // Return as text if not JSON } } catch (error) { console.error('Error sending notification:', error); throw error; // Re-throw the error to be caught by the caller } } // Load environment variables if using a .env file // Ensure you have 'dotenv' installed: npm install dotenv // require('dotenv').config(); // Get sendkey from environment variable const sendkey = process.env.SENDKEY; // Send notification with async/await (async () => { if (!sendkey) { console.error('Error: SENDKEY environment variable not set.'); return; } try { const result = await sc_send('Application Error', 'Out of memory\n\nPlease check server status', sendkey); console.log('Notification sent successfully:', result); } catch (error) { console.error('Failed to send notification:', error.message); } })(); ``` ### Response #### Success Response Returns the response from the Server酱 API, typically a JSON object indicating success or failure. #### Response Example ```json { "code": 0, "message": "success", "data": { "pushid": "12345", "readkey": "abcde" } } ``` ``` -------------------------------- ### Python Implementation Source: https://context7.com/easychen/serverchan-demo/llms.txt Example of sending Server酱 notifications using Python's `requests` library. It includes automatic endpoint detection and JSON payload support. ```APIDOC ## Python Server酱 Notification ### Description This Python function `sc_send` sends notifications using the `requests` library. It automatically determines the correct Server酱 API endpoint based on the `sendkey` format and sends a JSON payload. ### Method POST ### Endpoint Dynamically determined based on `sendkey` format: - Standard: `https://sctapi.ftqq.com/{sendkey}.send` - Private Server: `https://{num}.push.ft07.com/send/{sendkey}.send` ### Parameters #### Function Parameters - **sendkey** (string) - Required - Your Server酱 sendkey. - **title** (string) - Required - The title of the notification. - **desp** (string) - Optional - The content of the notification. Defaults to an empty string. - **options** (dict) - Optional - Additional parameters to send in the JSON payload. ### Request Example ```python import os import requests import re def sc_send(sendkey, title, desp='', options=None): if options is None: options = {} # Automatic endpoint detection based on sendkey format if sendkey.startswith('sctp'): match = re.match(r'sctp(\d+)t', sendkey) if match: num = match.group(1) url = f'https://{num}.push.ft07.com/send/{sendkey}.send' else: raise ValueError('Invalid sendkey format for sctp') else: url = f'https://sctapi.ftqq.com/{sendkey}.send' params = { 'title': title, 'desp': desp, **options } headers = { 'Content-Type': 'application/json;charset=utf-8' } response = requests.post(url, json=params, headers=headers) result = response.json() return result # Load environment variables # Assuming a .env file with SENDKEY=your_sendkey # For production, use a more secure method to manage secrets. try: with open('.env', 'r') as f: env_data = {} for line in f: if '=' in line: key, value = line.strip().split('=', 1) env_data[key] = value sendkey = env_data.get('SENDKEY') if not sendkey: raise ValueError("SENDKEY not found in .env file") # Send notification with error handling result = sc_send(sendkey, 'Server Down Alert', 'Database connection lost\n\nTimestamp: 2024-10-26 10:30:00') print(f"Success: {result}") except FileNotFoundError: print("Error: .env file not found. Please create it and add your SENDKEY.") except ValueError as ve: print(f"Configuration Error: {ve}") except requests.exceptions.RequestException as e: print(f"Network Error sending notification: {e}") except Exception as e: print(f"An unexpected error occurred: {e}") ``` ### Response #### Success Response Returns a dictionary parsed from the JSON response of the Server酱 API. #### Response Example ```json { "code": 0, "message": "success", "data": { "pushid": "12345", "readkey": "abcde" } } ``` ``` -------------------------------- ### Send HTTP POST Notification with cURL Source: https://context7.com/easychen/serverchan-demo/llms.txt Demonstrates sending push notifications to Server酱 using cURL with both standard and private server endpoints. It shows how to format the POST request with title and description, and includes an example of the expected JSON response. ```bash # Standard endpoint (sendkey without sctp prefix) curl -X POST "https://sctapi.ftqq.com/YOUR_SENDKEY.send" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "text=Server Alert&desp=First line\n\nSecond line" # Private server endpoint (sendkey with sctp prefix like sctp123t...) curl -X POST "https://123.push.ft07.com/send/sctp123txxx.send" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "text=Server Alert&desp=First line\n\nSecond line" # Response example (JSON) # {"code":0,"message":"success","data":{"pushid":"12345","readkey":"abcde"}} ``` -------------------------------- ### C#: ServerChan Notification Implementation with HttpClient Source: https://context7.com/easychen/serverchan-demo/llms.txt A .NET implementation of ServerChan notifications using C# and the `HttpClient` class. It supports modern asynchronous programming patterns. This example reads the SENDKEY from a .env file, demonstrating a common practice for managing credentials. Error handling for missing SENDKEY or invalid format is included. ```csharp using System; using System.IO; using System.Net.Http; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; class ServerChanClient { static async Task ScSend(string text, string desp = "", string key = "[SENDKEY]") { var postData = $"text={Uri.EscapeDataString(text)}&desp={Uri.EscapeDataString(desp)}"; string url; // Determine endpoint based on sendkey format if (key.StartsWith("sctp")) { var match = Regex.Match(key, @"^sctp(\d+)t"); if (match.Success) { var num = match.Groups[1].Value; url = $"https://{num}.push.ft07.com/send/{key}.send"; } else { throw new ArgumentException("Invalid key format for sctp"); } } else { url = $"https://sctapi.ftqq.com/{key}.send"; } using var httpClient = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Post, url); request.Content = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await httpClient.SendAsync(request); return await response.Content.ReadAsStringAsync(); } static async Task Main(string[] args) { try { string envContent = File.ReadAllText(".env"); string sendkey = envContent.Split('=')[1].Trim(); var result = await ScSend( "Build Complete", "Project: MyApp\nDuration: 2m 34s\n\nStatus: Success", sendkey ); Console.WriteLine($"Response: {result}"); } catch (Exception ex) { Console.Error.WriteLine($"Error: {ex.Message}"); } } } ``` -------------------------------- ### Java ServerChan Client Implementation Source: https://context7.com/easychen/serverchan-demo/llms.txt An enterprise-ready Java implementation using HttpURLConnection for sending push notifications. It handles endpoint determination based on the sendkey format and manages resources properly. Requires a .env file for the SENDKEY. ```java import java.io.*; import java.net.*; import java.util.Properties; import java.util.regex.*; public class ServerChanClient { public static String scSend(String title, String description, String sendkey) throws Exception { String apiUrl; // Determine endpoint based on sendkey format if (sendkey.startsWith("sctp")) { Pattern pattern = Pattern.compile("sctp(\d+)t"); Matcher matcher = pattern.matcher(sendkey); if (matcher.find()) { String num = matcher.group(1); apiUrl = "https://" + num + ".push.ft07.com/send/" + sendkey + ".send"; } else { throw new IllegalArgumentException("Invalid sendkey format for sctp"); } } else { apiUrl = "https://sctapi.ftqq.com/" + sendkey + ".send"; } String postData = "text=" + URLEncoder.encode(title, "UTF-8") + "&desp=" + URLEncoder.encode(description, "UTF-8"); URL url = new URL(apiUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) { out.writeBytes(postData); out.flush(); } int responseCode = conn.getResponseCode(); StringBuilder response = new StringBuilder(); try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String line; while ((line = in.readLine()) != null) { response.append(line); } } return response.toString(); } public static void main(String[] args) { try { Properties props = new Properties(); props.load(new FileInputStream(".env")); String sendkey = props.getProperty("SENDKEY"); String result = scSend("System Alert", "CPU usage: 95%\n\nAction required", sendkey); System.out.println("Response: " + result); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(); } } } ``` -------------------------------- ### Rust ServerChan Client Implementation Source: https://context7.com/easychen/serverchan-demo/llms.txt An asynchronous Rust implementation using tokio and reqwest for sending push notifications. It emphasizes strong type safety and proper error handling. Requires a .env file for the SENDKEY and crates like dotenv, reqwest, serde_urlencoded, and regex. ```rust use std::env; use reqwest::header::{CONTENT_TYPE, CONTENT_LENGTH}; use serde_urlencoded; use regex::Regex; async fn sc_send(text: String, desp: String, key: String) -> Result> { let params = [("text", text), ("desp", desp)]; let post_data = serde_urlencoded::to_string(params)?; // Determine endpoint based on sendkey format let url = if key.starts_with("sctp") { let re = Regex::new(r"sctp(\d+)t")?; if let Some(captures) = re.captures(&key) { let num = &captures[1]; format!("https://{}.push.ft07.com/send/{}.send", num, key) } else { return Err("Invalid sendkey format for sctp".into()); } } else { format!("https://sctapi.ftqq.com/{}.send", key) }; let client = reqwest::Client::new(); let res = client.post(&url) .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .header(CONTENT_LENGTH, post_data.len() as u64) .body(post_data) .send() .await?; let data = res.text().await?; Ok(data) } #[tokio::main] async fn main() -> Result<(), Box> { dotenv::dotenv().ok(); let key = env::var("SENDKEY")?; // Send notification with error handling match sc_send( "Container Restart".to_string(), "Service: web-api\n\nReason: Health check failed".to_string(), key ).await { Ok(response) => println!("Success: {}", response), Err(e) => eprintln!("Failed: {}", e), } Ok(()) } ``` -------------------------------- ### Send Server酱 Notification in Dart/Flutter Source: https://context7.com/easychen/serverchan-demo/llms.txt Cross-platform implementation for Flutter mobile and web applications using the http package. It handles different sendkey formats and sends POST requests with text and description. Loadingsendkey from environment variables is demonstrated. ```dart import 'package:http/http.dart' as http; import 'dart:io'; Future scSend(String text, [String desp = '', String? key]) async { key = key ?? '[SENDKEY]'; String url; // Determine endpoint based on sendkey format if (key.startsWith('sctp')) { final regExp = RegExp(r'sctp(\d+)t'); final match = regExp.firstMatch(key); if (match != null) { final num = match.group(1); url = 'https://$num.push.ft07.com/send/$key.send'; } else { throw ArgumentError('Invalid key format'); } } else { url = 'https://sctapi.ftqq.com/$key.send'; } final request = http.MultipartRequest('POST', Uri.parse(url)); request.fields['text'] = text; request.fields['desp'] = desp; final response = await request.send(); final responseBody = await response.stream.bytesToString(); return responseBody; } void main() async { // Load sendkey from environment final envFile = File('.env'); final envContent = await envFile.readAsString(); final sendkey = envContent.split('=')[1].trim(); try { // Send notification from Flutter app final result = await scSend( 'User Registration', 'New user: john@example.com\n\nTimestamp: ${DateTime.now()}', sendkey ); print('Notification sent: $result'); } catch (e) { print('Error sending notification: $e'); } } ``` -------------------------------- ### Shell Script ServerChan Client Implementation Source: https://context7.com/easychen/serverchan-demo/llms.txt A lightweight bash implementation using curl for quick integration into shell scripts. It determines the ServerChan API endpoint based on the sendkey format and sends POST requests. Requires a .env file for the SENDKEY. ```bash #!/bin/bash function sc_send() { local text=$1 local desp=$2 local key=$3 postdata="text=$text&desp=$desp" opts=( "--header" "Content-type: application/x-www-form-urlencoded" "--data" "$postdata" ) # Determine URL based on sendkey format if [[ "$key" =~ ^sctp([0-9]+)t ]]; then num=${BASH_REMATCH[1]} url="https://${num}.push.ft07.com/send/${key}.send" else url="https://sctapi.ftqq.com/${key}.send" fi # Send request and capture response result=$(curl -X POST -s "$url" "${opts[@]}") echo "$result" } # Load environment variables source .env ``` -------------------------------- ### HTTP POST Notification API Source: https://context7.com/easychen/serverchan-demo/llms.txt Send push notifications using Server酱 REST API. This endpoint supports both standard and private server formats, automatically detecting the correct endpoint based on the sendkey. ```APIDOC ## POST /send ### Description Send push notifications via Server酱 REST API with title and description parameters. The API automatically routes to the correct endpoint based on the sendkey format (standard or private server). ### Method POST ### Endpoint - Standard: `https://sctapi.ftqq.com/YOUR_SENDKEY.send` - Private Server: `https://.push.ft07.com/send/sctpt...send` ### Parameters #### Query Parameters - **text** (string) - Required - The title of the notification. - **desp** (string) - Required - The content/description of the notification. Supports newline characters (`\n`) for formatting. ### Request Example ```bash # Standard endpoint curl -X POST "https://sctapi.ftqq.com/YOUR_SENDKEY.send" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "text=Server Alert&desp=First line\n\nSecond line" # Private server endpoint curl -X POST "https://123.push.ft07.com/send/sctp123txxx.send" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "text=Server Alert&desp=First line\n\nSecond line" ``` ### Response #### Success Response (200) - **code** (integer) - Indicates success (0 for success). - **message** (string) - Status message (e.g., "success"). - **data** (object) - Contains push and read keys. - **pushid** (string) - Unique ID for the push notification. - **readkey** (string) - Key to retrieve the notification. #### Response Example ```json { "code": 0, "message": "success", "data": { "pushid": "12345", "readkey": "abcde" } } ``` ``` -------------------------------- ### Send Server酱 Notification in Swift Source: https://context7.com/easychen/serverchan-demo/llms.txt Native iOS and macOS implementation using URLSession for Apple platform integration. It constructs a POST request with URL-encoded form data and handles different sendkey formats. Synchronization is managed using DispatchSemaphore. ```swift import Foundation func sc_send(text: String, desp: String = "", key: String = "[SENDKEY]") -> String { let urlString: String let regex = try! NSRegularExpression(pattern: "^sctp(\d+)t", options: []) // Determine endpoint based on sendkey format if key.hasPrefix("sctp") { if let match = regex.firstMatch(in: key, options: [], range: NSRange(location: 0, length: key.utf16.count)) { let numRange = match.range(at: 1) if let numRange = Range(numRange, in: key) { let num = key[numRange] urlString = "https://\(num).push.ft07.com/send/\(key).send" } else { fatalError("Invalid key format") } } else { fatalError("Invalid key format") } } else { urlString = "https://sctapi.ftqq.com/\(key).send" } guard let url = URL(string: urlString) else { return "Invalid URL" } var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") let postdata = "text=\(text)&desp=\(desp)" request.httpBody = postdata.data(using: .utf8) let semaphore = DispatchSemaphore(value: 0) var result = "" let task = URLSession.shared.dataTask(with: request) { (data, response, error) in if let error = error { result = "Error: \(error.localizedDescription)" } else if let data = data { result = String(data: data, encoding: .utf8) ?? "" } semaphore.signal() } task.resume() semaphore.wait() return result } // Usage in iOS app let sendkey = ProcessInfo.processInfo.environment["SENDKEY"] ?? "" let response = sc_send( text: "App Launch", desp: "Version: 1.2.3\nDevice: iPhone 14\n\nUser: premium_user", key: sendkey ) print(response) ``` -------------------------------- ### Send Notification - Go Source: https://context7.com/easychen/serverchan-demo/llms.txt Implements a type-safe function for sending notifications using Go's standard net/http package. It constructs a POST request with URL-encoded form data and handles different Serverchan sendkey formats. Includes proper error checking for requests and response body reading. Dependencies include net/http, io/ioutil, net/url, regexp, and strings. Input is text, description, and sendkey. Output is the API response string and an error. ```go package main import ( "fmt" "io/ioutil" "net/http" "net/url" "regexp" "strings" "os" "log" ) func scSend(text string, desp string, key string) (string, error) { data := url.Values{} data.Set("text", text) data.Set("desp", desp) // Determine API URL based on sendkey format var apiUrl string if strings.HasPrefix(key, "sctp") { re := regexp.MustCompile(`sctp(\d+)t`) matches := re.FindStringSubmatch(key) if len(matches) > 1 { num := matches[1] apiUrl = fmt.Sprintf("https://%s.push.ft07.com/send/%s.send", num, key) } else { return "", fmt.Errorf("invalid sendkey format for sctp") } } else { apiUrl = fmt.Sprintf("https://sctapi.ftqq.com/%s.send", key) } client := &http.Client{} req, err := http.NewRequest("POST", apiUrl, strings.NewReader(data.Encode())) if err != nil { return "", err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") resp, err := client.Do(req) if err != nil { return "", err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } return string(body), nil } func main() { // Load sendkey from environment sendkey := os.Getenv("SENDKEY") // Send notification with error handling result, err := scSend("Deployment Success", "Version: 2.0.1\n\nAll tests passed", sendkey) if err != nil { log.Fatalf("Failed to send notification: %v", err) } fmt.Println("Response:", result) } ``` -------------------------------- ### Send Notification - PHP Source: https://context7.com/easychen/serverchan-demo/llms.txt Implements a simple notification function using native PHP stream contexts for HTTP POST requests. It handles different sendkey formats and sends a notification with provided text and description. Dependencies include standard PHP stream functions. Input is text, description (optional), and sendkey. Output is the response from the Serverchan API. ```php $text, 'desp' => $desp)); // Determine URL based on sendkey format if (strpos($key, 'sctp') === 0) { preg_match('/^sctp(\d+)t/', $key, $matches); $num = $matches[1]; $url = "https://{$num}.push.ft07.com/send/{$key}.send"; } else { $url = "https://sctapi.ftqq.com/{$key}.send"; } $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata )); $context = stream_context_create($opts); return file_get_contents($url, false, $context); } // Load environment variables $data = parse_ini_file('.env'); $sendkey = $data['SENDKEY']; // Send notification with error handling try { $result = sc_send('Backup Complete', "Database: ✓\nFiles: ✓\n\nTotal size: 2.5GB", $sendkey); echo "Response: " . $result; } catch (Exception $e) { error_log("Notification failed: " . $e->getMessage()); } ``` -------------------------------- ### Send Server酱 Notification with Node.js Source: https://context7.com/easychen/serverchan-demo/llms.txt Provides a Node.js function for sending Server酱 notifications asynchronously using the native fetch API. It dynamically constructs the correct endpoint URL based on the sendkey and sends data as URL-encoded form data. Includes loading sendkey from a .env file and uses async/await for promise-based error handling. ```javascript const https = require('https'); const querystring = require('querystring'); const fs = require('fs'); async function sc_send(text, desp = '', key = '[SENDKEY]') { const postData = querystring.stringify({ text, desp }); // Determine endpoint based on sendkey format const url = String(key).match(/^sctp(\d+)t/i) ? `https://${key.match(/^sctp(\d+)t/i)[1]}.push.ft07.com/send/${key}.send` : `https://sctapi.ftqq.com/${key}.send`; const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(postData) }, body: postData }); const data = await response.text(); return data; } // Load environment variables const envData = require('dotenv').parse(fs.readFileSync('.env')); const sendkey = envData.SENDKEY; // Send notification with async/await (async () => { try { const result = await sc_send('Application Error', 'Out of memory\n\nPlease check server status', sendkey); console.log('Notification sent:', result); } catch (error) { console.error('Failed to send notification:', error); } })(); ``` -------------------------------- ### Shell Script: Server Monitoring and Backup Notifications Source: https://context7.com/easychen/serverchan-demo/llms.txt Shell scripts to monitor disk usage and send backup completion notifications via ServerChan. It checks if disk usage exceeds 80% and sends an alert, or confirms successful backup completion. Requires a SENDKEY environment variable. ```shell DISK_USAGE=$(df -h / | awk 'NR==2 {print $5}') if [[ ${DISK_USAGE%?} -gt 80 ]]; then sc_send "Disk Space Warning" "Current usage: $DISK_USAGE\n\nPlease cleanup old files" "$SENDKEY" fi sc_send "Nightly Backup Complete" "Files: 1,234\nSize: 5.2GB\n\nStatus: Success" "$SENDKEY" ``` -------------------------------- ### Send Server酱 Notification with Python Source: https://context7.com/easychen/serverchan-demo/llms.txt Implements a Python function to send Server酱 notifications using the requests library. It supports automatic detection of standard or private server endpoints based on the sendkey format and handles sending JSON payloads. Includes loading sendkey from a .env file and basic error handling. ```python import os import requests import re def sc_send(sendkey, title, desp='', options=None): if options is None: options = {} # Automatic endpoint detection based on sendkey format if sendkey.startswith('sctp'): match = re.match(r'sctp(\d+)t', sendkey) if match: num = match.group(1) url = f'https://{num}.push.ft07.com/send/{sendkey}.send' else: raise ValueError('Invalid sendkey format for sctp') else: url = f'https://sctapi.ftqq.com/{sendkey}.send' params = { 'title': title, 'desp': desp, **options } headers = { 'Content-Type': 'application/json;charset=utf-8' } response = requests.post(url, json=params, headers=headers) result = response.json() return result # Load environment variables with open('.env', 'r') as f: env_data = {} for line in f: key, value = line.strip().split('=') env_data[key] = value sendkey = env_data['SENDKEY'] # Send notification with error handling try: result = sc_send(sendkey, 'Server Down Alert', 'Database connection lost\n\nTimestamp: 2024-10-26 10:30:00') print(f"Success: {result}") except Exception as e: print(f"Failed to send notification: {e}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.