-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 6f5f714
Showing
22 changed files
with
3,608 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
.DS_Store |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2019 Artem Zakharov | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
# alice [](https://godoc.org/github.com/azzzak/alice) [](https://goreportcard.com/report/github.com/azzzak/alice) | ||
|
||
Библиотека для создания навыков, расширяющих функциональность голосового помощника [Алиса](https://alice.yandex.ru). Упрощает разработку навыков, оставляя возможность тонкой настройки. Преимущества библиотеки: | ||
|
||
- объединение методов в цепочки при конструировании ответа | ||
- вспомогательные методы для оживления диалога | ||
- автоответ на служебные ping-пакеты | ||
|
||
## Установка или обновление | ||
|
||
`go get -u github.com/azzzak/alice` | ||
|
||
## Пример | ||
|
||
Простейший навык — говорит "привет", после чего повторяет каждую реплику пользователя. | ||
|
||
```Go | ||
package main | ||
|
||
import "github.com/azzzak/alice" | ||
|
||
func main() { | ||
updates := alice.ListenForWebhook("/hook") | ||
go http.ListenAndServe(":3000", nil) | ||
|
||
updates.Loop(func(k alice.Kit) *alice.Response { | ||
req, resp := k.Init() | ||
if req.IsNewSession() { | ||
return resp.Text("привет") | ||
} | ||
return resp.Text(req.OriginalUtterance()) | ||
}) | ||
} | ||
``` | ||
|
||
Детальный разбор примера смотрите в [руководстве](manual/README.md). | ||
|
||
## Цепочки методов | ||
|
||
Позволяют конструировать ответ со всеми возможностями, которые предлагает Алиса: кнопки, картинки и звуки. | ||
|
||
**Пример.** Ответ с текстом и TTS с паузой и звуком из библиотеки Алисы: | ||
|
||
```Go | ||
resp.Text("творог"). | ||
TTS("твор+ог"). | ||
Pause(3). | ||
Sound(sounds.Harp1) | ||
``` | ||
|
||
**Пример.** Ответ со случайно выбранной строкой и двумя кнопками: | ||
|
||
```Go | ||
resp.RandomText("привет", "алоха"). | ||
Button("хай", "", false). | ||
Button("отстань", "", false) | ||
``` | ||
|
||
**Пример.** При любом _num_ ответ остается согласованным: | ||
|
||
```Go | ||
resp.Text(fmt.Sprintf("%d %s пива %s на столе", num, | ||
alice.Plural(num, "бутылка", "бутылки", "бутылок"), | ||
alice.Plural(num, "стояла", "стояли", "стояло")). | ||
Sound(sounds.ThingsGlass1) | ||
``` | ||
|
||
## Навыки на базе библиотеки | ||
|
||
[](https://dialogs.yandex.ru/store/skills/16ff4b52-poleznyj-zhdu) \ | ||
[**Полезный Ждун**](https://dialogs.yandex.ru/store/skills/16ff4b52-poleznyj-zhdu) | ||
|
||
Присылайте свои навыки на azzzak@yandex.ru |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,199 @@ | ||
package alice | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"log" | ||
"math/rand" | ||
"net/http" | ||
"net/http/httputil" | ||
"sync" | ||
"time" | ||
) | ||
|
||
func init() { | ||
rand.Seed(time.Now().UnixNano()) | ||
} | ||
|
||
// Kit структура для передачи данных в главный цикл. | ||
type Kit struct { | ||
Req *Request | ||
Resp *Response | ||
// Ctx позволяет получить сигнал об истечении периода ожидания ответа. | ||
Ctx context.Context | ||
|
||
c chan<- *Response | ||
} | ||
|
||
// Init получает входящий пакет и заготовку исходящего из данных запроса. | ||
func (k Kit) Init() (*Request, *Response) { | ||
return k.Req, k.Resp | ||
} | ||
|
||
// Options структура с настройками. | ||
type Options struct { | ||
AutoPong bool | ||
Timeout time.Duration | ||
Debug bool | ||
} | ||
|
||
// AutoPong автоматический ответ на технические сообщения ping, проверяющие работоспособность навыка. По умолчанию включено. | ||
func AutoPong(b bool) func(*Options) { | ||
return func(opts *Options) { | ||
opts.AutoPong = b | ||
} | ||
} | ||
|
||
// Timeout таймаут обработки запроса в миллисекундах. По истечении запрос перестает обрабатываться и навык отправляет ошибку. Значение по умолчанию 3000 мс — официальное время ожидания ответа навыка. | ||
func Timeout(t int) func(*Options) { | ||
return func(opts *Options) { | ||
if t < 1 { | ||
log.Fatalln("Timeout must be positive integer") | ||
} | ||
opts.Timeout = time.Duration(t) | ||
} | ||
} | ||
|
||
// Debug показывает в консоле содержимое входящих и исходящих пакетов. По умолчанию отключено. | ||
func Debug(b bool) func(*Options) { | ||
return func(opts *Options) { | ||
opts.Debug = b | ||
} | ||
} | ||
|
||
// Stream канал, передающий данные в основной цикл. | ||
type Stream <-chan Kit | ||
|
||
// Handler сигнатура функции, передаваемой методу Loop(). | ||
type Handler func(k Kit) *Response | ||
|
||
// Loop отвечает за работу главного цикла. | ||
func (updates Stream) Loop(f Handler) { | ||
for kit := range updates { | ||
go func(k Kit) { | ||
k.c <- f(k) | ||
close(k.c) | ||
}(kit) | ||
} | ||
} | ||
|
||
// ListenForWebhook регистрирует обработчик входящих пакетов. | ||
func ListenForWebhook(hook string, opts ...func(*Options)) Stream { | ||
conf := Options{ | ||
AutoPong: true, | ||
Timeout: 3000, | ||
Debug: false, | ||
} | ||
for _, opt := range opts { | ||
opt(&conf) | ||
} | ||
|
||
stream := make(chan Kit, 1) | ||
http.HandleFunc(hook, webhook(conf, stream)) | ||
|
||
return stream | ||
} | ||
|
||
func webhook(conf Options, stream chan<- Kit) http.HandlerFunc { | ||
reqPool := sync.Pool{ | ||
New: func() interface{} { | ||
return new(Request) | ||
}, | ||
} | ||
|
||
respPool := sync.Pool{ | ||
New: func() interface{} { | ||
return new(Response) | ||
}, | ||
} | ||
|
||
return func(w http.ResponseWriter, r *http.Request) { | ||
defer r.Body.Close() | ||
|
||
ctx, cancel := context.WithTimeout(r.Context(), conf.Timeout*time.Millisecond) | ||
defer cancel() | ||
|
||
if conf.Debug { | ||
requestDump, err := httputil.DumpRequest(r, true) | ||
if err != nil { | ||
log.Println(err) | ||
} | ||
fmt.Println(string(requestDump)) | ||
} | ||
|
||
req := reqPool.Get().(*Request) | ||
defer reqPool.Put(req) | ||
|
||
decoder := json.NewDecoder(r.Body) | ||
if err := decoder.Decode(req.clean()); err != nil { | ||
log.Println(err) | ||
w.WriteHeader(http.StatusBadRequest) | ||
return | ||
} | ||
|
||
resp := respPool.Get().(*Response) | ||
resp.clean().prepareResponse(req) | ||
defer respPool.Put(resp) | ||
|
||
if conf.AutoPong { | ||
if req.Type() == SimpleUtterance && req.Text() == "ping" { | ||
if md, err := json.Marshal(resp.Text("pong")); err == nil { | ||
w.Header().Set("Content-Type", "application/json") | ||
w.Write(md) | ||
return | ||
} | ||
w.WriteHeader(http.StatusInternalServerError) | ||
return | ||
} | ||
} | ||
|
||
back := make(chan *Response) | ||
stream <- Kit{ | ||
Req: req, | ||
Resp: resp, | ||
Ctx: ctx, | ||
|
||
c: back, | ||
} | ||
|
||
var response *Response | ||
select { | ||
case <-ctx.Done(): | ||
log.Println(ctx.Err()) | ||
w.WriteHeader(http.StatusInternalServerError) | ||
return | ||
case response = <-back: | ||
} | ||
|
||
b, err := json.Marshal(response) | ||
if err != nil { | ||
log.Println(err) | ||
w.WriteHeader(http.StatusInternalServerError) | ||
return | ||
} | ||
|
||
if conf.Debug { | ||
fmt.Printf("\n%s\n\n", string(b)) | ||
} | ||
|
||
w.Header().Set("Content-Type", "application/json") | ||
w.Write(b) | ||
} | ||
} | ||
|
||
// Plural помогает согласовать слово с числительным. | ||
func Plural(n int, singular, plural1, plural2 string) string { | ||
switch n % 100 { | ||
case 11, 12, 13, 14: | ||
return plural2 | ||
} | ||
switch n % 10 { | ||
case 0, 5, 6, 7, 8, 9: | ||
return plural2 | ||
case 1: | ||
return singular | ||
default: | ||
return plural1 | ||
} | ||
} |
Oops, something went wrong.