This is an old revision of the document!
# curl http://localhost:8088/ari/asterisk/ping?api_key=asterisk:asterisk
{"ping":"pong" ...
превращаем бота в агента (agent_rand_hello.py):
gate# git -C /etc/ status gate# git -C /etc/ log
gate# git -C /etc/ diff gate# git -C /etc/ add -v . gate# git -C /etc/ commit -m "dhcp confgured"
gate:/etc# code resolv.conf code ex1.bash #!/ ... for i ...
gate# apt install xxd
import os
import requests
# Вставьте сюда ваши данные
YANDEX_API_KEY = "..." # API-ключ сервисного аккаунта
FOLDER_ID = "b1gg4j6ru4esprat3uu7" # ID каталога в Yandex Cloud
URL = "https://llm.api.cloud.yandex.net/foundationModels/v1/completion"
def get_ai_response(user_message: str) -> str:
headers = {
"Authorization": f"Api-Key {YANDEX_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"modelUri": f"gpt://{FOLDER_ID}/yandexgpt/latest",
"completionOptions": {
"stream": False,
"temperature": 0.7,
"maxTokens": "200"
},
"messages": [
{"role": "user", "text": user_message}
]
}
resp = requests.post(URL, json=payload, headers=headers, timeout=30)
resp.raise_for_status()
data = resp.json()
# Yandex GPT возвращает список вариантов; берём первый
return data["result"]["alternatives"][0]["message"]["text"]
if __name__ == "__main__":
print("Чат-бот с Yandex GPT (введите 'выход' для завершения)")
while True:
user_input = input("Вы: ")
if user_input.lower() in ("выход", "quit", "exit"):
break
try:
ai_reply = get_ai_response(user_input)
print("Бот:", ai_reply)
except Exception as e:
print("Ошибка:", e)
# pip install aiohttp asyncio
import asyncio
import json
import aiohttp
# Параметры подключения (из вашего curl-примера)
ARI_HOST = "localhost"
ARI_PORT = 8088
ARI_USER = "asterisk"
ARI_PASS = "asterisk"
APP_NAME = "my-first-app"
WS_URL = f"ws://{ARI_HOST}:{ARI_PORT}/ari/events?app={APP_NAME}&api_key={ARI_USER}:{ARI_PASS}"
REST_URL = f"http://{ARI_HOST}:{ARI_PORT}/ari"
async def main():
async with aiohttp.ClientSession() as session:
# Проверяем, что Asterisk жив (как ваш curl-ping)
async with session.get(
f"{REST_URL}/asterisk/ping?api_key={ARI_USER}:{ARI_PASS}"
) as resp:
if resp.status != 200:
print(f"Не удалось подключиться к ARI: HTTP {resp.status}")
return
print("Asterisk ARI доступен, подключаемся к WebSocket…")
# Подписка на события приложения my-first-app
async with session.ws_connect(WS_URL) as ws:
print(f"WebSocket открыт. Приложение «{APP_NAME}» слушает события.")
print("Позвоните на экстеншен с Stasis(my-first-app) и нажимайте клавиши.\n")
async for msg in ws:
if msg.type != aiohttp.WSMsgType.TEXT:
continue
event = json.loads(msg.data)
etype = event.get("type")
if etype == "StasisStart":
channel = event["channel"]
print(f"[Звонок поступил] {channel['name']} (id: {channel['id']})")
elif etype == "ChannelDtmfReceived":
digit = event.get("digit", "?")
channel = event.get("channel", {})
name = channel.get("name", "?")
duration = event.get("duration_ms", 0)
print(f" Нажато: «{digit}» (канал: {name}, длительность: {duration} мс)")
elif etype == "StasisEnd":
channel = event["channel"]
print(f"[Звонок завершён] {channel['name']}")
# Можно uncomment для отладки — увидите все события:
# else:
# print(f" (событие: {etype})")
if __name__ == "__main__":
asyncio.run(main())
root# mkdir -p /var/spool/asterisk/recording/ chown -R asterisk:asterisk /var/spool/asterisk/recording/ chmod -R 775 /var/spool/asterisk/recording/ pip install websocket-client requests
import json
import requests
import websocket
# --- Настройки подключения (аналогичны curl из вопроса) ---
ARI_URL = "http://localhost:8088/ari"
WS_URL = "ws://localhost:8088/ari/events?app=my-first-app&api_key=asterisk:asterisk"
AUTH = ("asterisk", "asterisk")
# Состояние каждого канала: "recording" или "playing"
channels: dict[str, str] = {}
def start_recording(cid: str):
"""Запустить запись речи звонящего (макс 5 сек, пауза 2 сек — стоп)."""
channels[cid] = "recording"
requests.post(f"{ARI_URL}/channels/{cid}/record", auth=AUTH, params={
"name": f"echo-{cid}",
"format": "wav",
"maxDurationSeconds": 5,
"maxSilenceSeconds": 2,
"beep": "true",
})
def on_message(ws, message):
event = json.loads(message)
etype = event.get("type")
if etype == "StasisStart":
cid = event["channel"]["id"]
print(f"→ Звонок от {event['channel']['name']}")
requests.post(f"{ARI_URL}/channels/{cid}/answer", auth=AUTH)
start_recording(cid)
elif etype == "RecordingFinished":
cid = event["recording"]["target_uri"].removeprefix("channel:")
if cid in channels:
print(" Запись готова, воспроизвожу…")
channels[cid] = "playing"
requests.post(f"{ARI_URL}/channels/{cid}/play", auth=AUTH, params={
"media": f"recording:echo-{cid}",
})
elif etype == "PlaybackFinished":
cid = event["playback"]["target_uri"].removeprefix("channel:")
if cid in channels and channels[cid] == "playing":
print(" Воспроизведение окончено, снова запись…")
start_recording(cid)
elif etype == "StasisEnd":
cid = event["channel"]["id"]
channels.pop(cid, None)
print(f"← Звонок завершён: {event['channel']['name']}")
if __name__ == "__main__":
print("Echo-приложение 'my-first-app' запущено. Ожидание звонков…")
ws = websocket.WebSocketApp(WS_URL, on_message=on_message)
ws.run_forever()