Skip to content

Commit

Permalink
Merge pull request #1 from mail-ru-im/master
Browse files Browse the repository at this point in the history
Update from upstream
  • Loading branch information
gldmtr authored Aug 1, 2024
2 parents 8ea3849 + 4d4de6b commit ffa7320
Show file tree
Hide file tree
Showing 11 changed files with 168 additions and 68 deletions.
20 changes: 0 additions & 20 deletions .circleci/config.yml

This file was deleted.

35 changes: 35 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# This workflow will build a golang project
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go

name: Go

on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]

jobs:


build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.21'

- name: Lint
run: make lint

- name: Test
run: make test

- name: Upload coverage to Codecov
uses: codecov/codecov-action@v4
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
files: cover.out
23 changes: 23 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Contribute
## Pull request
Если вы решили впервые стать контрибьютером и помочь развитию open-source проекта, этот пункт для вас.
1) Делается fork основного репозитория
2) git clone https://github.com/ваш-логин/bot-golang.git
3) Локальное изменение
4) Сделайте ребейз на remote master ветку
5) git push origin <ваш-логин>
6) В удаленном репозитории нажать _compare&pull request_

Также рекомендуем ознакомиться с подробной инструкцией для контрибьютеров - <a href="https://github.com/firstcontributions/first-contributions">README.md</a>

## Tests
1) Если добавляется новая функциональность, то покрывайте ее тестами
2) Следите за тем, чтобы тесты успешно выполнялись в PR перед мержем.

## Merge
Ветка будет смержена в мастер, когда:
1) Все пайплайны пройдут успешно
2) Новая функциональность будет покрыта тестами

После выполнения всех пунктов один из сотрудников проверит в ближайшее время PR и смержит его.

42 changes: 17 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
<img src="https://github.com/mail-ru-im/bot-python/blob/master/logo.png" width="100" height="100">
<img src="logo_bot.png" width="100" height="100">

# Golang interface for Mail.ru Instant Messengers bot API
![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)
[![CircleCI](https://circleci.com/gh/mail-ru-im/bot-golang.svg?style=svg)](https://circleci.com/gh/mail-ru-im/bot-golang)
# VK Teams Bot API for Golang
[![Go](https://github.com/mail-ru-im/bot-golang/actions/workflows/go.yml/badge.svg)](https://github.com/mail-ru-im/bot-golang/actions/workflows/go.yml)
[![codecov](https://codecov.io/github/mail-ru-im/bot-golang/graph/badge.svg?token=0HX8DY24SR)](https://codecov.io/github/mail-ru-im/bot-golang)
[![go.dev reference](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat)](https://pkg.go.dev/github.com/mail-ru-im/bot-golang)
![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)

- *Brand new Bot API!*

- *Zero-configuration library*

- *Simple and clear interface*
### [<img src="logo_msg.png" width="16"> VK Teams API Specification](https://teams.vk.com/botapi/)

## API specification:
### [<img src="https://icq.com/cached/img/landing/icon_and_192.png" width="15"> ICQ New ](https://icq.com/botapi/)
### [<img src="https://is3-ssl.mzstatic.com/image/thumb/Purple123/v4/e8/4f/1b/e84f1b57-206f-7750-ac5a-27f93ff4a0d8/icons-bundle.png/460x0w.png" width="16"> Myteam ](https://myteam.mail.ru/botapi/)
## Getting started

### [<img src="https://agent.mail.ru/img/agent2014/common/2x/button_logo.png" width="16"> Agent Mail.ru](https://agent.mail.ru/botapi/)
* Create your own bot by sending the _/newbot_ command to _Metabot_ and follow the instructions.
>Note: a bot can only reply after the user has added it to his contact list, or if the user was the first to start a dialogue.
* You can configure the domain that hosts your VK Teams server. When instantiating the Bot class, add the address of your domain.
* An example of how to use the framework can be seen in _example/main.go_

## Install
```bash
Expand All @@ -24,8 +22,7 @@ go get github.com/mail-ru-im/bot-golang

## Usage

Create your own bot by sending the /newbot command to Metabot and follow the instructions.

Create your own bot by sending the /newbot command to _Metabot_ and follow the instructions.
Note a bot can only reply after the user has added it to his contacts list, or if the user was the first to start a dialogue.

### Create your bot
Expand All @@ -41,7 +38,7 @@ func main() {
log.Println("wrong token")
}

message := bot.NewTextMessage("[email protected]", "text")
message := bot.NewTextMessage("[email protected]", "text")
message.Send()
}
```
Expand All @@ -51,18 +48,13 @@ func main() {
You can create, edit and reply to messages like a piece of cake.

```go
message := bot.NewTextMessage("[email protected]", "text")
message := bot.NewTextMessage("[email protected]", "text")
message.Send()

fmt.Println(message.MsgID)

message.Text = "new text"

message.Edit()
// AWESOME!

message.Reply("hey, what did you write before???")
// SO HOT!
message.Reply("I changed my text")
```

### Subscribe events
Expand All @@ -73,7 +65,7 @@ Get all updates from the channel. Use context for cancellation.
ctx, finish := context.WithCancel(context.Background())
updates := bot.GetUpdatesChannel(ctx)
for update := range updates {
// your awesome logic here
// your logic here
}
```

Expand All @@ -83,7 +75,7 @@ You don't need this.
But if you do, you can override bot's API URL:

```go
bot := botgolang.NewBot(BOT_TOKEN, botgolang.BotApiURL("https://agent.mail.ru/bot/v1"))
bot := botgolang.NewBot(BOT_TOKEN, botgolang.BotApiURL("https://vkteams.com/bot/v1"))
```
And debug all api requests and responses:

Expand Down
40 changes: 40 additions & 0 deletions api_mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,43 @@ func (h *MockHandler) GetEvents(w http.ResponseWriter) {
}
}

func (h *MockHandler) SelfGet(w http.ResponseWriter, r *http.Request) {

encoder := json.NewEncoder(w)

if r.FormValue("chatId") == "" {
err := encoder.Encode(&Response{
OK: false,
Description: "Missing required parameter 'chatId'",
})

if err != nil {
h.logger.WithFields(logrus.Fields{
"err": err,
}).Error("cannot encode json")
}
}

chats_getInfo := `{
"about": "about user",
"firstName": "User",
"language": "en",
"lastName": "Userov",
"photo": [
{
"url": "https://rapi.myteaminternal/avatar/get?targetSn=test@test&size=1024"
}
],
"type": "private",
"ok": true
}`

_, err := w.Write([]byte(chats_getInfo))
if err != nil {
h.logger.Fatal("failed to write events")
}
}

func (h *MockHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch {
case r.FormValue("token") == "":
Expand All @@ -269,6 +306,9 @@ func (h *MockHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
case r.URL.Path == "/events/get":
h.GetEvents(w)
return
case r.URL.Path == "/self/get":
h.SelfGet(w, r)
return
default:
encoder := json.NewEncoder(w)
err := encoder.Encode(&Response{
Expand Down
5 changes: 2 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
Expand Down Expand Up @@ -60,7 +59,7 @@ func (c *Client) DoWithContext(ctx context.Context, path string, params url.Valu
}

req.Header.Set("Content-Type", multipartWriter.FormDataContentType())
req.Body = ioutil.NopCloser(buffer)
req.Body = io.NopCloser(buffer)
req.Method = http.MethodPost
}

Expand All @@ -84,7 +83,7 @@ func (c *Client) DoWithContext(ctx context.Context, path string, params url.Valu
}
}()

responseBody, err := ioutil.ReadAll(resp.Body)
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
c.logger.WithFields(logrus.Fields{
"err": err,
Expand Down
26 changes: 25 additions & 1 deletion client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func TestClient_Do_OK(t *testing.T) {

client := Client{
baseURL: testServer.URL,
token: "test",
token: "test_token",
client: http.DefaultClient,
logger: &logrus.Logger{},
}
Expand Down Expand Up @@ -288,3 +288,27 @@ func TestClient_GetEvents_OK(t *testing.T) {
require.NoError(err)
assert.Equal(events, expected)
}

func TestClient_GetInfo_OK(t *testing.T) {
require := require.New(t)
assert := assert.New(t)
testServer := httptest.NewServer(&MockHandler{})
defer func() { testServer.Close() }()

client := Client{
baseURL: testServer.URL,
token: "test_token",
client: http.DefaultClient,
logger: &logrus.Logger{},
}

info, err := client.GetChatInfo("id_1234")
require.NoError(err)
assert.NotEmpty(info.ID)
}

func TestClient_GetInfo_Error(t *testing.T) {
require := require.New(t)

require.NoError(nil)
}
20 changes: 13 additions & 7 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
module github.com/gldmtr/bot-golang

go 1.13
go 1.20

require (
github.com/hako/durafmt v0.0.0-20190612201238-650ed9f29a84
github.com/hako/durafmt v0.0.0-20210608085754-5c1018a4e16b
github.com/mailru/easyjson v0.7.7
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.7.0
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect
github.com/sirupsen/logrus v1.8.1
github.com/stretchr/testify v1.7.0
golang.org/x/sys v0.0.0-20211013075003-97ac67df715c // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/sys v0.18.0 // indirect
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
gopkg.in/yaml.v3 v3.0.0 // indirect
)
25 changes: 13 additions & 12 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,31 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/hako/durafmt v0.0.0-20190612201238-650ed9f29a84 h1:RvcDqcKLua4b/jtXez7ZVe9s6Iq5N6ujVevqY4FBQmM=
github.com/hako/durafmt v0.0.0-20190612201238-650ed9f29a84/go.mod h1:5Scbynm8dF1XAPwIwkGPqzkM/shndPm79Jd1003hTjE=
github.com/hako/durafmt v0.0.0-20210608085754-5c1018a4e16b h1:wDUNC2eKiL35DbLvsDhiblTUXHxcOPwQSCzi7xpQUN4=
github.com/hako/durafmt v0.0.0-20210608085754-5c1018a4e16b/go.mod h1:VzxiSdG6j1pi7rwGm/xYI5RbtpBgM8sARDXlvEvxlu0=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e h1:hB2xlXdHp/pmPZq0y3QnmWAArdw9PqbmotexnWx/FU8=
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20211013075003-97ac67df715c h1:taxlMj0D/1sOAuv/CbSD+MMDof2vbyPTqz5FNYKpXt8=
golang.org/x/sys v0.0.0-20211013075003-97ac67df715c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0 h1:hjy8E9ON/egN1tAYqKb61G10WtihqetD4sz2H+8nIeA=
gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Binary file added logo_bot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added logo_msg.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit ffa7320

Please sign in to comment.