goboter/telegram/bot.go
2020-10-28 15:34:51 +01:00

115 lines
2.8 KiB
Go

package telegram
import (
"context"
"fmt"
"github.com/pkg/errors"
"udico.de/uditaren/cure"
)
type Bot struct {
// TODO: check if this is really required, since we also hold the key in the api caller
key string
api *cure.Endpoint
// Remember to call Poll, or Listen
Updates chan *Update
updateid int64
}
func New(apikey, useragent string) *Bot {
ret := &Bot{
key: apikey,
api: cure.New(fmt.Sprintf("https://api.telegram.org/bot%v", apikey)),
Updates: make(chan *Update),
}
ret.api.UserAgent = useragent
return ret
}
// Basically a ping at the telegram API.
// Gets information about the Bot user.
func (b *Bot) Me() (*User, error) {
call := b.api.Get("/getMe")
ret := &UserResponse{}
err := call.Fire(context.Background(), ret)
if !err.Ok() {
return nil, err.Error()
}
if !ret.Ok {
e := ret.Description
if ret.ErrorCode > 0 {
e = fmt.Sprintf("%v [code: %v]", e, ret.ErrorCode)
}
return nil, errors.New(e)
}
return ret.Result, err.Error()
}
func (b *Bot) GetUpdates(ctx context.Context, offset, limit, timeout int64) ([]*Update, error) {
call := b.api.Get("/getUpdates")
call.Parameters["offset"] = fmt.Sprintf("%v", offset)
call.Parameters["limit"] = fmt.Sprintf("%v", limit)
call.Parameters["timeout"] = fmt.Sprintf("%v", timeout)
ret := &UpdateResponse{}
err := call.Fire(ctx, ret)
if !err.Ok() {
return nil, err.Error()
}
if !ret.Ok {
e := ret.Description
if ret.ErrorCode > 0 {
e = fmt.Sprintf("%v [code: %v]", e, ret.ErrorCode)
}
return nil, errors.New(e)
}
return ret.Result, err.Error()
}
func (b *Bot) SendMessage(chatid int64, message string, replyto int64) (*Message, error) {
call := b.api.PostForm("/sendMessage")
//prm := &SendMessageParams{
// ChatId: chatid,
// Text: message,
// ReplyToMessageId: replyto,
//}
//call.Param(prm)
call.Parameters["chat_id"] = fmt.Sprintf("%v", chatid)
call.Parameters["text"] = message
call.Parameters["parse_mode"] = "MarkdownV2"
ret := &MessageResponse{}
err := call.Fire(context.Background(), ret)
if !err.Ok() {
return nil, err.Error()
}
if !ret.Ok {
e := ret.Description
if ret.ErrorCode > 0 {
e = fmt.Sprintf("%v [code: %v]", e, ret.ErrorCode)
}
return nil, errors.New(e)
}
return ret.Result, err.Error()
}
func (b *Bot) EditMessageText(chatid int64, messageid int64, message string) (*Message, error) {
call := b.api.PostForm( "/editMessageText")
call.Parameters["chat_id"] = fmt.Sprintf("%v", chatid)
call.Parameters["message_id"] = fmt.Sprintf("%v", messageid)
call.Parameters["parse_mode"] = "MarkdownV2"
call.Parameters["text"] = message
ret := &MessageResponse{}
err := call.Fire(context.Background(), ret)
if !err.Ok() {
return nil, err.Error()
}
if !ret.Ok {
e := ret.Description
if ret.ErrorCode > 0 {
e = fmt.Sprintf("%v [code: %v]", e, ret.ErrorCode)
}
return nil, errors.New(e)
}
return ret.Result, err.Error()
}