Skip to content

Настройки устройства

Изменяет настройки конкретного устройства: разрешение отправки SMS, выбор SIM-карты, пользовательское название и уведомления.

Метод: PATCH
Эндпоинт: /api/ext/v1/devices/{id}/settings
Требуемое разрешение: devices:settings

Параметры пути

ПараметрТипОписание
idstring (UUID)ID устройства

Тело запроса

json
{
  "can_send_sms": true,
  "selected_sim": -1,
  "notify_low_battery": true,
  "forward_incoming_sms": false,
  "name_custom": "Офисный телефон"
}
ПолеТипОписание
can_send_smsbooleanРазрешить/запретить отправку SMS через это устройство
selected_simintegerВыбор SIM-карты для отправки (см. таблицу ниже)
notify_low_batterybooleanУведомлять о низком заряде батареи
forward_incoming_smsbooleanПередавать входящие SMS в панель управления
name_customstringСвоё название устройства (до 100 символов). Пустая строка сбрасывает на системное имя

Значения selected_sim

ЗначениеОписание
-2Использовать системную SIM по умолчанию (настройка Android)
-1Случайная из доступных SIM-карт
0Первый слот SIM-карты
1Второй слот SIM-карты
2Третий слот SIM-карты

Ответ — 200 OK

Возвращает полный объект устройства с обновлёнными настройками (такой же формат, как в списке устройств).

json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "type": "android",
  "name": "Samsung Galaxy A54",
  "name_custom": "Офисный телефон",
  "is_online": true,
  "is_charging": false,
  "battery_level": 72,
  "can_send_sms": true,
  "selected_sim": -1,
  "notify_low_battery": true,
  "forward_incoming_sms": false,
  "sim_cards": [
    { "index": 0, "name_operator": "МТС" },
    { "index": 1, "name_operator": "Билайн" }
  ],
  "created_at": "2024-01-10T08:00:00Z",
  "updated_at": "2024-01-15T12:00:00Z"
}

Ошибки

СтатусПричина
400 Bad RequestНеверный формат UUID или невалидные поля
404 Not FoundУстройство не найдено

Примеры

curl — переименовать устройство

bash
curl -X PATCH \
  "https://api.gosms.ru/api/ext/v1/devices/550e8400-e29b-41d4-a716-446655440000/settings" \
  -H "Authorization: Bearer ВАШ_КЛЮЧ" \
  -H "Content-Type: application/json" \
  -d '{
    "can_send_sms": true,
    "selected_sim": -1,
    "notify_low_battery": true,
    "forward_incoming_sms": false,
    "name_custom": "Склад #2"
  }'

curl — отключить SMS-отправку

bash
curl -X PATCH \
  "https://api.gosms.ru/api/ext/v1/devices/550e8400-e29b-41d4-a716-446655440000/settings" \
  -H "Authorization: Bearer ВАШ_КЛЮЧ" \
  -H "Content-Type: application/json" \
  -d '{
    "can_send_sms": false,
    "selected_sim": -1,
    "notify_low_battery": true,
    "forward_incoming_sms": false,
    "name_custom": ""
  }'

Python

python
import requests

def update_device_settings(device_id: str, **settings):
    """
    Обновляет настройки устройства.
    
    Параметры:
      can_send_sms: bool
      selected_sim: int (-2, -1, 0, 1, 2)
      notify_low_battery: bool
      forward_incoming_sms: bool
      name_custom: str
    """
    # Нужно передать все поля — PATCH требует полный объект настроек
    defaults = {
        "can_send_sms": True,
        "selected_sim": -1,
        "notify_low_battery": False,
        "forward_incoming_sms": False,
        "name_custom": "",
    }
    payload = {**defaults, **settings}

    response = requests.patch(
        f"https://api.gosms.ru/api/ext/v1/devices/{device_id}/settings",
        headers={
            "Authorization": "Bearer ВАШ_КЛЮЧ",
            "Content-Type": "application/json",
        },
        json=payload,
    )
    response.raise_for_status()
    return response.json()

# Назначить первую SIM и дать имя
device = update_device_settings(
    "550e8400-e29b-41d4-a716-446655440000",
    selected_sim=0,
    name_custom="МТС — офис",
    notify_low_battery=True,
)
print(f"Обновлено: {device['name_custom']}, SIM: {device['selected_sim']}")

JavaScript

javascript
async function updateDeviceSettings(deviceId, settings) {
  const response = await fetch(
    `https://api.gosms.ru/api/ext/v1/devices/${deviceId}/settings`,
    {
      method: 'PATCH',
      headers: {
        'Authorization': 'Bearer ВАШ_КЛЮЧ',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(settings),
    }
  );

  if (!response.ok) {
    const err = await response.json();
    throw new Error(err.error.message);
  }

  return response.json();
}

// Включить пересылку входящих SMS
const device = await updateDeviceSettings(
  '550e8400-e29b-41d4-a716-446655440000',
  {
    can_send_sms: true,
    selected_sim: -1,
    notify_low_battery: true,
    forward_incoming_sms: true,  // включаем пересылку
    name_custom: 'Основной',
  }
);
console.log('Настройки обновлены:', device.updated_at);

Важно: передавайте все поля

Этот эндпоинт обновляет все настройки сразу. Нельзя передать только одно поле — остальные будут сброшены в значения по умолчанию.

Рекомендуемый подход:

python
# 1. Получить текущие настройки
devices = requests.get(
    "https://api.gosms.ru/api/ext/v1/devices",
    headers={"Authorization": "Bearer ВАШ_КЛЮЧ"}
).json()

device = next(d for d in devices if d["id"] == "НУЖНЫЙ_ID")

# 2. Изменить только нужное
payload = {
    "can_send_sms": device["can_send_sms"],
    "selected_sim": device["selected_sim"],
    "notify_low_battery": device["notify_low_battery"],
    "forward_incoming_sms": device["forward_incoming_sms"],
    "name_custom": "Новое название",  # только это меняем
}

# 3. Сохранить
updated = requests.patch(
    f"https://api.gosms.ru/api/ext/v1/devices/{device['id']}/settings",
    headers={
        "Authorization": "Bearer ВАШ_КЛЮЧ",
        "Content-Type": "application/json"
    },
    json=payload,
).json()

GoSMS — управление Android-устройствами для автоматизации отправки SMS