1 python发送bark消息到服务器

bark的官方文档:https://bark.day.app/#/tutorial 上提到,我们可以通过get、post等多种方式发送bark消息到服务器,比如post

curl -X "POST" "https://api.day.app/your_key" \
     -H 'Content-Type: application/json; charset=utf-8' \
     -d $'{
  "body": "Test Bark Server",
  "title": "Test Title",
  "badge": 1,
  "sound": "minuet",
  "icon": "https://day.app/assets/images/avatar.jpg",
  "group": "test",
  "url": "https://mritd.com"
}'

更多的请求参数可以参考bark官方文档。

我们在python中使用request库可实现发送消息到bark服务器

import os
import requests

BARK_SERVER_URL = 'https://你的bark服务器地址/你的key/'  #这里写你的bark服务器地址

class BarkNotify:
    def __init__(self, bark_server_url=None):
        if bark_server_url is None:
            self.bark_server_url = BARK_SERVER_URL
        else:
            self.bark_server_url = bark_server_url

    def send_bark_notification(self, message, title=None, badge=1, sound="minuet", icon=None, group=None, url=None):
        """
        Send a notification to the server using Bark.

        Parameters:
        - server_url (str): The URL of the Bark server.
        - message (str): The message to send.
        - title (str, optional): The title of the message. Defaults to None.
        - badge (int, optional): The badge number to display. Defaults to 1.
        - sound (str, optional): The sound to play. Defaults to "minuet".
        - icon (str, optional): The URL of the icon image. Defaults to None.
        - group (str, optional): The group name. Defaults to None.
        - url (str, optional): The URL to open when the notification is clicked. Defaults to None.
        """
        payload = {
            'body': message,
            'title': title,
            'badge': badge,
            'sound': sound,
            'icon': icon,
            'group': group,
            'url': url,
        }
        # Removing keys with None values
        payload = {key: value for key, value in payload.items() if value is not None}

        headers = {
            'Content-Type': 'application/json; charset=utf-8'
        }

        response = requests.post(self.bark_server_url, json=payload, headers=headers)
        if response.status_code == 200:
            print("Notification sent successfully!")
        else:
            print(f"Failed to send notification. Status code: {response.status_code}")
            print(f"Response: {response.text}")

if __name__ == '__main__':
    message = "Test Bark Server"
    title = "Test Title"
    badge = 1
    sound = "minuet"
    icon = "https://day.app/assets/images/avatar.jpg"
    group = "test"
    url = "https://stubbornhuang.com"

    bark_notify = BarkNotify()
    bark_notify.send_bark_notification(message, title, badge, sound, icon, group, url)

运行程序即可在手机端看到消息推送。