> For the complete documentation index, see [llms.txt](https://doc.nextbot.ru/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://doc.nextbot.ru/functional/functions/sending-result/python/podklyuchenie-i-rabota-s-google-tablicam/zapis-v-google-tablicu.md).

# Запись в Google Таблицу

**Задача:** получить имя и номер телефона пользователя и сохранить их в таблицу.

**Шаг 1.** Имеется простой агент "Секретарь".

<figure><img src="https://2593311972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fef2EBU68XAlye1NtG8DF%2Fuploads%2FANScOoxm601Q4pxaavJC%2Fimage.png?alt=media&amp;token=74195602-7e31-4722-884d-c4dff6369e03" alt=""><figcaption></figcaption></figure>

**Системный промпт:**

{% code overflow="wrap" %}

```
Ты виртуальный секретарь, 
Спроси имя и номер телефона, после этого вызови функцию save_record_to_google_sheet
```

{% endcode %}

**Шаг 2.** В разделе **Функции** обязательно включите (если выключено) использование функций.

Создайте функцию `save_record_to_google_sheet` с описанием *"Сохранить запись в Google Таблице"*.

Добавьте два параметра: `name` и `phone_number`.

<figure><img src="https://2593311972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fef2EBU68XAlye1NtG8DF%2Fuploads%2FiyBAkEVD76ryZBCznsaH%2Fimage.png?alt=media&amp;token=97c076a7-1b32-401f-96c6-fed341b2a5f4" alt=""><figcaption></figcaption></figure>

**Шаг 3.** Найдите ваш JSON-ключ, полученный на этапе [Подготовка Google аккаунта и получение ключа для интеграции](/functional/functions/sending-result/python/podklyuchenie-i-rabota-s-google-tablicam.md)

Прокрутите страницу вниз и включите **Python Script**.

<figure><img src="https://2593311972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fef2EBU68XAlye1NtG8DF%2Fuploads%2FkQbsvrOUJXM8Zk2w6zAh%2F%7B2F7C1469-67A1-46D4-A9DC-68903BBCC233%7D.png?alt=media&amp;token=50b9fe74-78b3-450d-a4ff-f28cbab64404" alt=""><figcaption></figcaption></figure>

**Шаг 4.** Удалите текущий код и вставьте подготовленный код:

```python
def write_to_google_sheet():
    scope = [
        'https://www.googleapis.com/auth/spreadsheets',
        'https://www.googleapis.com/auth/drive'
    ]

    # Надо заменить данные на ваш 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"
}
    # Получаем ServiceAccountCredentials из структуры словаря
    debug("Получаем ServiceAccountCredentials")
    ServiceAccountCredentials = oauth2client['service_account']['ServiceAccountCredentials']
    # Авторизация
    creds = ServiceAccountCredentials.from_json_keyfile_dict(json_data, scope)
    client = gspread.authorize(creds)

    # Открытие таблицы
    sheet = client.open(table_name).sheet1
    data_to_append = [args.get("name", ""), args.get("phone_number", "")]
    
    # Запись данных
    sheet.append_row(data_to_append)
    global result
    result = {
            'status': 'success',
            'write': {
                'message': 'Данные успешно записаны',
                'data': data_to_append
            }
    }
table_name = 'Имя Вашей Таблицы' #тут прописываем имя таблицы
result ={}
write_to_google_sheet()


```

{% hint style="warning" %}
Обязательно вставьте свои данные в `json_data` и укажите актуальное имя таблицы в `table_name`.
{% endhint %}

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

<figure><img src="https://2593311972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fef2EBU68XAlye1NtG8DF%2Fuploads%2FouHzub91Rr8GWGZYz2bG%2Fimage.png?alt=media&amp;token=2d96bc7c-0ed1-4114-8467-521f9eb3120a" alt=""><figcaption></figcaption></figure>

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

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

**Пример таблицы:**\
Таблица "Contacts" с двумя колонками: "Имя" и "Номер телефона".

![](https://2593311972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fef2EBU68XAlye1NtG8DF%2Fuploads%2F7eGC9AmXgiVGd9Lec8TC%2Fimage.png?alt=media\&token=d35f5b34-88b9-4fab-af80-24c962321eef)

**Тест:**

<figure><img src="https://2593311972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fef2EBU68XAlye1NtG8DF%2Fuploads%2F6PD0bphr0oM5UyV9bxkY%2Fimage.png?alt=media&amp;token=8d84ddfb-16d3-4e57-ad01-698c3dc4f3df" alt="" width="375"><figcaption></figcaption></figure>

Оставьте в полях `name` и `phone_number` значения `test_value` , нажмите "Запустить тест"— и убедитесь, что запись появилась в таблице.

<figure><img src="https://2593311972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fef2EBU68XAlye1NtG8DF%2Fuploads%2FvMP1UxMbxkdfUJ6etRXM%2Fimage.png?alt=media&amp;token=edacd907-73a0-43ab-804a-896a2a7a3a55" alt=""><figcaption></figcaption></figure>

Можно проверить работу из диалога

<figure><img src="https://2593311972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fef2EBU68XAlye1NtG8DF%2Fuploads%2F6ZIHFdCAVGcmU8KfjBwa%2Fimage.png?alt=media&amp;token=d7576430-58ad-4942-83fa-b3ec137417df" alt=""><figcaption></figcaption></figure>

Убедитесь что, что запись появилась в таблице.

<figure><img src="https://2593311972-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fef2EBU68XAlye1NtG8DF%2Fuploads%2FlwuAAFDzi2GOuNuMOLV3%2Fimage.png?alt=media&amp;token=45eb4298-6d94-4996-9ca3-d8de76003760" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://doc.nextbot.ru/functional/functions/sending-result/python/podklyuchenie-i-rabota-s-google-tablicam/zapis-v-google-tablicu.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
