Added dict with additional cards

This commit is contained in:
Artyom Belousov 2021-02-03 19:09:08 +03:00
parent 181f3bc0aa
commit 88ea431a27
26 changed files with 232 additions and 35 deletions

94
internal/vk/handlers.go Normal file
View file

@ -0,0 +1,94 @@
package vk
import (
"errors"
"log"
"net/http"
"os"
"strings"
"github.com/gin-gonic/gin"
"gitlab.com/flygrounder/go-mtg-vk/internal/caching"
"gitlab.com/flygrounder/go-mtg-vk/internal/cardsinfo"
)
var dictPath = "./assets/additional_cards.json"
func HandleMessage(c *gin.Context) {
var req MessageRequest
_ = c.BindJSON(&req)
if req.Secret != SecretKey {
return
}
switch req.Type {
case "confirmation":
handleConfirmation(c, &req)
case "message_new":
go handleSearch(&req)
c.String(http.StatusOK, "ok")
}
}
func handleSearch(req *MessageRequest) {
defer func() {
if r := recover(); r != nil {
log.Printf("[error] Search panicked. Exception info: %s", r)
}
}()
cardName, err := getCardNameByCommand(req.Object.Body)
if err != nil {
Message(req.Object.UserId, "Некорректная команда")
log.Printf("[info] Not correct command. Message: %s user input: %s", err.Error(), req.Object.Body)
} else if cardName == "" {
Message(req.Object.UserId, "Карта не найдена")
log.Printf("[info] Could not find card. User input: %s", req.Object.Body)
} else {
message, err := GetMessage(cardName)
if err != nil {
Message(req.Object.UserId, "Цены временно недоступны, попробуйте позже")
log.Printf("[error] Could not find SCG prices. Message: %s card name: %s", err.Error(), cardName)
return
}
Message(req.Object.UserId, message)
}
}
func GetMessage(cardName string) (string, error) {
client := caching.GetClient()
val, err := client.Get(cardName)
if err != nil {
prices, err := cardsinfo.GetPrices(cardName)
if err != nil {
return "", err
}
message := cardsinfo.FormatCardPrices(cardName, prices)
client.Set(cardName, message)
return message, nil
}
return val, nil
}
func getCardNameByCommand(command string) (string, error) {
var name string
switch {
case strings.HasPrefix(command, "!s"):
split := strings.Split(command, " ")
if len(split) < 3 {
return "", errors.New("wrong command")
}
set := split[1]
number := split[2]
name = cardsinfo.GetNameByCardId(set, number)
default:
dict, _ := os.Open(dictPath)
name = cardsinfo.GetOriginalName(command, dict)
}
return name, nil
}
func handleConfirmation(c *gin.Context, req *MessageRequest) {
if (req.Type == "confirmation") && (req.GroupId == GroupId) {
c.String(http.StatusOK, ConfirmationString)
}
}

37
internal/vk/message.go Normal file
View file

@ -0,0 +1,37 @@
package vk
import (
"encoding/json"
"io/ioutil"
"log"
"math/rand"
"net/http"
"net/url"
"strconv"
"strings"
)
const SendMessageUrl = "https://api.vk.com/method/messages.send"
func Message(userId int64, message string) {
randomId := rand.Int63()
params := []string{
"access_token=" + Token,
"peer_id=" + strconv.FormatInt(userId, 10),
"message=" + url.QueryEscape(message),
"v=5.95",
"random_id=" + strconv.FormatInt(randomId, 10),
}
paramString := strings.Join(params, "&")
resp, err := http.Get(SendMessageUrl + "?" + paramString)
if err != nil || resp.StatusCode != http.StatusOK {
log.Printf("[error] Could not send message. User: %d", userId)
return
}
responseBytes, _ := ioutil.ReadAll(resp.Body)
var response SendMessageResponse
_ = json.Unmarshal(responseBytes, &response)
if response.Error.ErrorCode != 0 {
log.Printf("[error] Message was not sent. User: %d error message: %s", userId, response.Error.ErrorMsg)
}
}

11
internal/vk/secrets.go Normal file
View file

@ -0,0 +1,11 @@
package vk
import (
"os"
"strconv"
)
var Token = os.Getenv("VK_TOKEN")
var SecretKey = os.Getenv("VK_SECRET_KEY")
var GroupId, _ = strconv.ParseInt(os.Getenv("VK_GROUP_ID"), 10, 64)
var ConfirmationString = os.Getenv("VK_CONFIRMATION_STRING")

22
internal/vk/structs.go Normal file
View file

@ -0,0 +1,22 @@
package vk
type MessageRequest struct {
Type string `json:"type"`
GroupId int64 `json:"group_id"`
Object UserMessage `json:"object"`
Secret string `json:"secret"`
}
type UserMessage struct {
Body string `json:"text"`
UserId int64 `json:"peer_id"`
}
type SendMessageResponse struct {
Error ErrorResponse `json:"error"`
}
type ErrorResponse struct {
ErrorCode int `json:"error_code"`
ErrorMsg string `json:"error_msg"`
}