Skip to content

Commit 6dea536

Browse files
kennyromanovkennyromanov
andauthored
feat (SDK-135): Функционал VoIP в официальном чат-боте на Python (#50)
* feat: The VoIP AI chatbot has been added * chore: THe linting and the documentation have been updated * fix: The issue with the cleanup has been fixed; THe cleanup process has been improved * fix: The issue with the cleanup has been fixed x2; The python bug has been worked-around --------- Co-authored-by: kennyromanov <kenni.romanov@green-api.com>
1 parent 67cd69c commit 6dea536

25 files changed

Lines changed: 3454 additions & 7 deletions

‎.github/workflows/python-package.yml‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,23 @@ jobs:
2929
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
3030
- name: Lint with ruff
3131
run: |
32-
# stop the build if there are Python syntax errors or undefined names
33-
ruff check --output-format=github --select=E9,F63,F7,F82 --target-version=py37 .
34-
# default set of ruff rules with GitHub Annotations
35-
ruff check --output-format=github --target-version=py37 .
32+
ruff check --config ruff.toml --output-format=github .
3633
- name: Test with pytest
3734
run: |
38-
pytest
35+
pytest tests --ignore=tests/calls
36+
37+
calls:
38+
name: ${{ matrix.python-version }} (VoIP)
39+
runs-on: ubuntu-24.04
40+
strategy:
41+
matrix:
42+
python-version: [ "3.11", "3.12", "3.13" ]
43+
steps:
44+
- uses: actions/checkout@v3
45+
- uses: actions/setup-python@v4
46+
with:
47+
python-version: ${{ matrix.python-version }}
48+
- name: Install optional call dependencies
49+
run: python -m pip install '.[voip]' pytest
50+
- name: Test calls and base imports
51+
run: python -m pytest tests

‎.gitignore‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,4 +157,4 @@ cython_debug/
157157
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158158
# and can be added to the global gitignore or merged into this file. For a more nuclear
159159
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
160-
#.idea/
160+
.idea/

‎README.md‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -517,6 +517,72 @@ def show_interactive_buttons_reply_handler(notification: Notification) -> None:
517517
bot.run_forever()
518518
```
519519

520+
## Optional voice calls (VoIP)
521+
522+
The `whatsapp_chatbot_python.calls` package executes one outgoing WhatsApp
523+
voice call through the GreenAPI SDK, with an OpenAI Realtime conversation,
524+
timeouts, audio playback and a best-effort MP3 recording. It requires **Python
525+
3.11+**, an authorized VoIP-capable instance and an OpenAI API key. Install the
526+
optional dependencies (or use `'.[voip]'` when installing from this checkout):
527+
528+
```shell
529+
python -m pip install 'whatsapp-chatbot-python[voip]'
530+
```
531+
532+
The extra pins the SDK and audio/provider versions used. The ordinary chatbot import does not load OpenAI, aiortc or
533+
PyAV. Call models, contracts and the FSM are available from `whatsapp_chatbot_python.calls`; import the executor
534+
explicitly from `whatsapp_chatbot_python.calls.service`.
535+
536+
### Execute one call
537+
538+
The model and voice are supplied by the application. This example performs an actual call when run with valid
539+
credentials:
540+
541+
```python
542+
import asyncio
543+
import logging
544+
import os
545+
546+
from whatsapp_chatbot_python.calls import (
547+
CallEvent, CallSession, CallStateMachine,
548+
)
549+
from whatsapp_chatbot_python.calls.service import WhatsAppCallService
550+
551+
service = WhatsAppCallService(
552+
api_url="https://api.green-api.com",
553+
id_instance=os.environ["ID_INSTANCE"],
554+
api_token_instance=os.environ["API_TOKEN_INSTANCE"],
555+
openai_api_key=os.environ["OPENAI_API_KEY"],
556+
realtime_model=os.environ["REALTIME_MODEL"],
557+
realtime_voice=os.environ["REALTIME_VOICE"],
558+
ring_timeout_seconds=30,
559+
talk_timeout_seconds=120,
560+
shutdown_timeout_seconds=10,
561+
logger=logging.getLogger("calls"),
562+
)
563+
564+
async def call_once():
565+
session = CallSession(
566+
sender_id="79123456789@c.us",
567+
chat_id="79123456789@c.us",
568+
language="ru",
569+
)
570+
fsm = CallStateMachine()
571+
fsm.apply(session, CallEvent.ENQUEUED)
572+
fsm.apply(session, CallEvent.DEQUEUED)
573+
result = await service.execute(session, fsm.apply)
574+
try:
575+
print(session.state, session.end_reason, session.error_code)
576+
if result.recording_path is not None:
577+
print("MP3:", result.recording_path)
578+
# Upload or copy the recording here, before removing it.
579+
finally:
580+
if result.recording_path is not None:
581+
result.recording_path.unlink(missing_ok=True)
582+
583+
asyncio.run(call_once())
584+
```
585+
520586
## Service methods documentation
521587

522588
[Service methods documentation](https://green-api.com/en/docs/api/)

‎docs/README.md‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,68 @@ def show_interactive_buttons_reply_handler(notification: Notification) -> None:
513513
bot.run_forever()
514514
```
515515

516+
## Голосовые звонки (необязательное дополнение VoIP)
517+
518+
Пакет `whatsapp_chatbot_python.calls` выполняет один исходящий WhatsApp-звонок: подключение через GreenAPI SDK,
519+
голосовой разговор с OpenAI Realtime, тайм-ауты, воспроизведение и запись MP3. Требуются **Python 3.11+**,
520+
авторизованный инстанс с поддержкой VoIP и ключ OpenAI.
521+
522+
```shell
523+
python -m pip install 'whatsapp-chatbot-python[voip]'
524+
```
525+
526+
Для установки из исходников используйте `python -m pip install -e '.[voip]'`. Дополнение фиксирует версии SDK, OpenAI и
527+
аудиобиблиотек. Обычный импорт чат-бота не загружает OpenAI, aiortc или PyAV.
528+
529+
### Выполнить один звонок
530+
531+
Модель и голос задаёт приложение. При запуске с действительными реквизитами этот пример совершит настоящий звонок:
532+
533+
```python
534+
import asyncio
535+
import logging
536+
import os
537+
538+
from whatsapp_chatbot_python.calls import (
539+
CallEvent, CallSession, CallStateMachine,
540+
)
541+
from whatsapp_chatbot_python.calls.service import WhatsAppCallService
542+
543+
service = WhatsAppCallService(
544+
api_url="https://api.green-api.com",
545+
id_instance=os.environ["ID_INSTANCE"],
546+
api_token_instance=os.environ["API_TOKEN_INSTANCE"],
547+
openai_api_key=os.environ["OPENAI_API_KEY"],
548+
realtime_model=os.environ["REALTIME_MODEL"],
549+
realtime_voice=os.environ["REALTIME_VOICE"],
550+
ring_timeout_seconds=30,
551+
talk_timeout_seconds=120,
552+
shutdown_timeout_seconds=10,
553+
logger=logging.getLogger("calls"),
554+
)
555+
556+
async def call_once():
557+
session = CallSession(
558+
sender_id="79123456789@c.us",
559+
chat_id="79123456789@c.us",
560+
language="ru",
561+
)
562+
fsm = CallStateMachine()
563+
fsm.apply(session, CallEvent.ENQUEUED)
564+
fsm.apply(session, CallEvent.DEQUEUED)
565+
result = await service.execute(session, fsm.apply)
566+
try:
567+
print(session.state, session.end_reason, session.error_code)
568+
if result.recording_path is not None:
569+
print("MP3:", result.recording_path)
570+
# Upload or copy the recording here, before removing it.
571+
finally:
572+
if result.recording_path is not None:
573+
result.recording_path.unlink(missing_ok=True)
574+
575+
asyncio.run(call_once())
576+
```
577+
516578
## Документация по методам сервиса
517579

518580
[Документация по методам сервиса](https://green-api.com/docs/api/)

‎ruff.toml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Match the SDK's lint policy: catch code errors without rewriting legacy style.
2+
target-version = "py39"
3+
force-exclude = true
4+
5+
[lint]
6+
select = ["E4", "E7", "E9", "F"]

‎setup.py‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
author="GREEN API",
1616
author_email="support@green-api.com",
1717
url="https://github.com/green-api/whatsapp-chatbot-python",
18-
packages=find_packages(exclude=["tests"]),
18+
packages=find_packages(include=["whatsapp_chatbot_python", "whatsapp_chatbot_python.*"]),
1919
classifiers=[
2020
"Development Status :: 5 - Production/Stable",
2121
"Environment :: Console",
@@ -44,5 +44,14 @@
4444
" (CC BY-ND 4.0)"
4545
),
4646
install_requires=["whatsapp-api-client-python>=0.0.53"],
47+
extras_require={
48+
"voip": [
49+
"whatsapp-api-client-python[voip]==0.0.55; python_version >= '3.11'",
50+
"openai==3.20.0; python_version >= '3.11'",
51+
"aiortc==1.15.0; python_version >= '3.11'",
52+
"av==17.1.0; python_version >= '3.11'",
53+
"websockets>=16,<17; python_version >= '3.11'",
54+
],
55+
},
4756
python_requires=">=3.7"
4857
)

‎tests/calls/__init__.py‎

Whitespace-only changes.

‎tests/calls/conftest.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
"""Keep base installations testable without installing the optional audio stack."""
2+
3+
import sys
4+
from importlib.util import find_spec
5+
6+
collect_ignore_glob = []
7+
if sys.version_info < (3, 11):
8+
collect_ignore_glob = ["test_*.py"]
9+
elif any(find_spec(name) is None for name in ("openai", "aiortc", "av")):
10+
collect_ignore_glob = [
11+
"test_call_service.py", "test_realtime_voice.py", "test_call_recording.py"
12+
]

0 commit comments

Comments
 (0)