# Чтение из Google таблицы

**Задача:** Получить цену на услуги из прайс-листа.

<figure><img src="/files/gm19bhmaIxOEumSLuaQ5" alt=""><figcaption><p>Прайслист</p></figcaption></figure>

Имеется ИИ-агент **"Мастер маникюра"**.

Напишем простенький промпт

{% code overflow="wrap" %}

```
Ты мастер маникюра Роза 🦋

Шаг за шагом выясни:
1. Тип услуги — используй read_data_from_google_sheet, чтобы проверить, есть ли такая услуга.
2. Время записи — используй get_available_start_times_by_datetime_range.
3. Имя и номер телефона.

Будь дружелюбной, используй эмодзи, шути, дари клиенту хорошее настроение 💅✨
```

{% endcode %}

Создайте функцию `read_data_from_google_sheet` (Чтение из гугл таблиц)

<figure><img src="/files/sVfY9JnmINfqLhiYTlfu" alt=""><figcaption></figcaption></figure>

Добавьте параметр функции для поиска: `service_name` - тип услуги.

<figure><img src="/files/XOSNsqzZ5VGcuhxZy273" alt=""><figcaption></figcaption></figure>

**Сделайте его листовым** (выпадающий список) и укажите названия всех услуг из таблицы, а также два значения: `Да` и `Нет` (для поиска по столбцу "Акция").

Перед следующим шагом найдите ваш JSON ключ полученный на шаге [Подготовка Google аккаунта и получение ключа для интеграции](#podgotovka-google-akkaunta-i-poluchenie-klyucha-dlya-integracii)

Включите **Python Script** и замените код в поле "Код Функции" на код ниже

```python
scope = [
    'https://www.googleapis.com/auth/spreadsheets',
    'https://www.googleapis.com/auth/drive'
]
debug("Область доступа определена")

# Данные сервисного аккаунта в формате JSON
json_data =  {
        "type": "service_account",
        "project_id": "your_project_id",
        "private_key_id": "your_private_key_id",
        "private_key": "-----BEGIN PRIVATE KEY-----\nyour_private_key\n-----END PRIVATE KEY-----\n",
        "client_email": "your_service_account_email",
        "client_id": "your_client_id",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_x509_cert_url": "your_client_cert_url"
}
debug("JSON данные сервисного аккаунта подготовлены")
def search_in_sheet(query):
    # Получаем ServiceAccountCredentials из структуры словаря
    debug("Получаем ServiceAccountCredentials")
    ServiceAccountCredentials = oauth2client['service_account']['ServiceAccountCredentials']
    
    # Создаем учетные данные из JSON
    debug("Создаем учетные данные")
    creds = ServiceAccountCredentials.from_json_keyfile_dict(json_data, scope)
    
    # Авторизуемся в Google Sheets
    debug("Авторизация в Google Sheets")
    client = gspread.authorize(creds)
    
    # 1. Открытие таблицы
    
    debug(f"Открываем таблицу {table_name}")
    sheet = client.open(table_name).sheet1
    
      
    # 2. ЧТЕНИЕ данных из таблицы
    debug("ЧТЕНИЕ: Получаем данные из таблицы")
    
    debug("Получаем все данные")
    all_values = sheet.get_all_values()
    headers = all_values[0]

    results = []
    for row in all_values[1:]:  # Пропускаем заголовки
        for cell in row:
            if query.lower() in str(cell).lower():
                results.append(row)
                break  # если хотя бы одна ячейка подходит — добавляем строку и переходим к следующей

    return results

table_name = 'Имя Вашей Таблицы' #тут прописываем имя таблицы
query = args.get("service_name", "")
found_rows = search_in_sheet(query)

result = {'status': 'success',
        'read': {
               'data': found_rows  # Все найденные строки строки
        }}
```

{% hint style="warning" %}
Обратите внимание что в переменной json\_data надо вставить данные из вашего JSON ключа, а в переменной table\_name надо прописать имя вашей таблицы.
{% endhint %}

Код надо подготовить. Из файла с ключом скопируйте все что между фигурными скобочками и вставьте в json\_data переменную

<figure><img src="/files/t6rQg1GOJZ0d9N7rS1xu" alt=""><figcaption></figcaption></figure>

Не забудьте прописать имя вашей таблицы

```python
table_name = 'Имя Вашей Таблицы' #тут прописываем имя таблицы
```

Тестирование:

Нажмите **"Тестировать Код"**, выберите в параметрах `service_name` значение `Да`, запустите тест.

<figure><img src="/files/MiEwmkPOBpRvWBpc9ehO" alt=""><figcaption></figcaption></figure>

Проверьте результат:

<figure><img src="/files/nRNl1u8XBwowa67yUM2i" alt=""><figcaption></figcaption></figure>

Протестируйте в диалоге:

<figure><img src="/files/LU45TaZRoVmBlMKxfPq2" alt=""><figcaption></figcaption></figure>

ИИ-Агент анализирует полученную информацию и выдаёт ответ на основе данных из таблицы

<figure><img src="/files/tDmcamapUukCfHlY2GSn" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.nextbot.ru/functional/functions/sending-result/python/podklyuchenie-i-rabota-s-google-tablicam/chtenie-iz-google-tablicy.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
