kick ticket initial commit
This commit is contained in:
@@ -32,7 +32,7 @@ type Server struct {
|
||||
|
||||
type Webhook struct {
|
||||
CheckingID string `json:"checking_id"`
|
||||
Pending bool `json:"pending"`
|
||||
Pending int `json:"pending"`
|
||||
Amount int64 `json:"amount"`
|
||||
Fee int64 `json:"fee"`
|
||||
Memo string `json:"memo"`
|
||||
@@ -48,7 +48,7 @@ type Webhook struct {
|
||||
|
||||
func NewServer(bot *telegram.TipBot) *Server {
|
||||
srv := &http.Server{
|
||||
Addr: internal.Configuration.Lnbits.WebhookServerUrl.Host,
|
||||
Addr: "0.0.0.0:5588",
|
||||
WriteTimeout: 15 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
}
|
||||
|
||||
@@ -5,72 +5,127 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var tickerMap cmap.ConcurrentMap
|
||||
var functionMap cmap.ConcurrentMap
|
||||
|
||||
func init() {
|
||||
tickerMap = cmap.New()
|
||||
functionMap = cmap.New()
|
||||
}
|
||||
|
||||
var defaultTickerCoolDown = time.Second * 10
|
||||
var DefaultTickerDuration = time.Second * 10
|
||||
|
||||
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
|
||||
type ResettableFunctionTicker struct {
|
||||
// ResettableFunction will reset the user state as soon as tick is delivered.
|
||||
type ResettableFunction struct {
|
||||
Ticker *time.Ticker
|
||||
Timer *time.Timer
|
||||
ResetChan chan struct{} // channel used to reset the ticker
|
||||
StopChan chan struct{} // channel used to reset the ticker
|
||||
duration time.Duration
|
||||
Started bool
|
||||
name string
|
||||
}
|
||||
type ResettableFunctionTickerOption func(*ResettableFunctionTicker)
|
||||
|
||||
type ResettableFunctionTickerOption func(*ResettableFunction)
|
||||
|
||||
func WithTicker(t *time.Ticker) ResettableFunctionTickerOption {
|
||||
return func(a *ResettableFunction) {
|
||||
a.Ticker = t
|
||||
}
|
||||
}
|
||||
func WithDuration(d time.Duration) ResettableFunctionTickerOption {
|
||||
return func(a *ResettableFunctionTicker) {
|
||||
return func(a *ResettableFunction) {
|
||||
a.duration = d
|
||||
}
|
||||
}
|
||||
func WithTimer(t *time.Timer) ResettableFunctionTickerOption {
|
||||
return func(a *ResettableFunction) {
|
||||
a.Timer = t
|
||||
}
|
||||
}
|
||||
func RemoveTicker(name string) {
|
||||
tickerMap.Remove(name)
|
||||
functionMap.Remove(name)
|
||||
}
|
||||
func GetTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
|
||||
|
||||
if t, ok := tickerMap.Get(name); ok {
|
||||
return t.(*ResettableFunctionTicker)
|
||||
func Get(name string) (*ResettableFunction, bool) {
|
||||
if t, ok := functionMap.Get(name); ok {
|
||||
return t.(*ResettableFunction), ok
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
func GetFunction(name string, option ...ResettableFunctionTickerOption) *ResettableFunction {
|
||||
if t, ok := functionMap.Get(name); ok {
|
||||
return t.(*ResettableFunction)
|
||||
} else {
|
||||
t := NewResettableFunctionTicker(name, option...)
|
||||
tickerMap.Set(name, t)
|
||||
t := NewResettableFunction(name, option...)
|
||||
functionMap.Set(name, t)
|
||||
return t
|
||||
}
|
||||
}
|
||||
func NewResettableFunctionTicker(name string, option ...ResettableFunctionTickerOption) *ResettableFunctionTicker {
|
||||
t := &ResettableFunctionTicker{
|
||||
|
||||
func NewResettableFunction(name string, option ...ResettableFunctionTickerOption) *ResettableFunction {
|
||||
t := &ResettableFunction{
|
||||
ResetChan: make(chan struct{}, 1),
|
||||
StopChan: make(chan struct{}, 1),
|
||||
name: name,
|
||||
}
|
||||
if t.duration == 0 {
|
||||
t.duration = DefaultTickerDuration
|
||||
}
|
||||
|
||||
for _, opt := range option {
|
||||
opt(t)
|
||||
}
|
||||
if t.duration == 0 {
|
||||
t.duration = defaultTickerCoolDown
|
||||
}
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *ResettableFunctionTicker) Do(f func()) {
|
||||
// Do will listen for timers and invoke functionCallback on tick.
|
||||
func (t *ResettableFunction) Do(functionCallback func()) {
|
||||
t.Started = true
|
||||
tickerMap.Set(t.name, t)
|
||||
// persist function
|
||||
functionMap.Set(t.name, t)
|
||||
go func() {
|
||||
for {
|
||||
if t.Timer != nil {
|
||||
// timer is set. checking event
|
||||
select {
|
||||
case <-t.Timer.C:
|
||||
functionCallback()
|
||||
return
|
||||
default:
|
||||
}
|
||||
}
|
||||
if t.Ticker != nil {
|
||||
// ticker is set. checking event
|
||||
select {
|
||||
case <-t.Ticker.C:
|
||||
// ticker delivered signal. do function functionCallback
|
||||
functionCallback()
|
||||
return
|
||||
default:
|
||||
}
|
||||
}
|
||||
// check stop and reset channels
|
||||
select {
|
||||
case <-t.Ticker.C:
|
||||
// ticker delivered signal. do function f
|
||||
f()
|
||||
case <-t.StopChan:
|
||||
if t.Timer != nil {
|
||||
t.Timer.Stop()
|
||||
}
|
||||
if t.Ticker != nil {
|
||||
t.Ticker.Stop()
|
||||
}
|
||||
return
|
||||
case <-t.ResetChan:
|
||||
// reset signal received. creating new ticker.
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
if t.Ticker != nil {
|
||||
t.Ticker.Reset(t.duration)
|
||||
}
|
||||
if t.Timer != nil {
|
||||
t.Timer.Reset(t.duration)
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -5,13 +5,14 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// todo -- use function.go instead!
|
||||
// var retryMap cmap.ConcurrentMap
|
||||
|
||||
// func init() {
|
||||
// retryMap = cmap.New()
|
||||
// }
|
||||
|
||||
// ResettableFunctionTicker will reset the user state as soon as tick is delivered.
|
||||
// ResettableFunction will reset the user state as soon as tick is delivered.
|
||||
type FunctionRetry struct {
|
||||
Ticker *time.Ticker
|
||||
duration time.Duration
|
||||
@@ -35,14 +36,14 @@ func NewRetryTicker(ctx context.Context, name string, option ...FunctionRetryOpt
|
||||
opt(t)
|
||||
}
|
||||
if t.duration == 0 {
|
||||
t.duration = defaultTickerCoolDown
|
||||
t.duration = DefaultTickerDuration
|
||||
}
|
||||
t.Ticker = time.NewTicker(t.duration)
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *FunctionRetry) Do(f func(), cancel_f func(), deadline_f func()) {
|
||||
tickerMap.Set(t.name, t)
|
||||
functionMap.Set(t.name, t)
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
|
||||
@@ -2,6 +2,7 @@ package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/tidwall/buntdb"
|
||||
@@ -56,6 +57,7 @@ func (db *DB) Get(object Storable) error {
|
||||
}
|
||||
err = json.Unmarshal([]byte(val), object)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -135,6 +135,7 @@ func (bot *TipBot) Start() {
|
||||
// start the telegram bot
|
||||
go bot.Telegram.Start()
|
||||
|
||||
go bot.restartPersistedTickets()
|
||||
// gracefully shutdown
|
||||
exit := make(chan os.Signal, 1) // we need to reserve to buffer size 1, so the notifier are not blocked
|
||||
// we need to catch SIGTERM and SIGSTOP
|
||||
|
||||
@@ -35,6 +35,7 @@ type Databases struct {
|
||||
}
|
||||
|
||||
const (
|
||||
JoinTicketIndex = "join-ticket:*"
|
||||
MessageOrderedByReplyToFrom = "message.reply_to_message.from.id"
|
||||
TipTooltipKeyPattern = "tip-tool-tip:*"
|
||||
)
|
||||
@@ -47,6 +48,10 @@ func createBunt(file string) *storage.DB {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
err = bunt.CreateIndex("join-ticket", JoinTicketIndex, buntdb.IndexString)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return bunt
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (bot *TipBot) fileHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
@@ -16,7 +17,7 @@ func (bot *TipBot) fileHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
if c := stateCallbackMessage[user.StateKey]; c != nil {
|
||||
// found ctx for this state
|
||||
// now looking for user state reset ticker
|
||||
ticker := runtime.GetTicker(user.ID)
|
||||
ticker := runtime.GetFunction(user.ID, runtime.WithTicker(time.NewTicker(runtime.DefaultTickerDuration)))
|
||||
if !ticker.Started {
|
||||
ticker.Do(func() {
|
||||
ResetUserState(user, bot)
|
||||
|
||||
+134
-2
@@ -5,7 +5,9 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
|
||||
@@ -22,6 +24,31 @@ import (
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
)
|
||||
|
||||
type JoinTicket struct {
|
||||
Chat *tb.Chat `json:"chat"`
|
||||
Sender *tb.User `json:"sender"`
|
||||
Message *tb.Message `json:"message"`
|
||||
CreatedTimestamp time.Time `json:"created_timestamp"`
|
||||
Ticket *Ticket `json:"ticket"`
|
||||
}
|
||||
|
||||
func (jt JoinTicket) Key() string {
|
||||
return fmt.Sprintf("join-ticket:%d_%d", jt.Chat.ID, jt.Sender.ID)
|
||||
}
|
||||
|
||||
func (jt JoinTicket) Type() EventType {
|
||||
return EventTypeTicketInvoice
|
||||
}
|
||||
|
||||
func (bot *TipBot) loadGroup(groupName string) (*Group, error) {
|
||||
group := &Group{}
|
||||
tx := bot.DB.Groups.Where("name = ? COLLATE NOCASE", groupName).First(group)
|
||||
if tx.Error != nil {
|
||||
return nil, tx.Error
|
||||
}
|
||||
return group, nil
|
||||
}
|
||||
|
||||
type Ticket struct {
|
||||
Price int64 `json:"price"`
|
||||
Memo string `json:"memo"`
|
||||
@@ -109,6 +136,9 @@ func (bot TipBot) groupHandler(ctx intercept.Context) (intercept.Context, error)
|
||||
if splits[1] == "add" {
|
||||
return bot.addGroupHandler(ctx)
|
||||
}
|
||||
if splits[1] == "ticket" {
|
||||
return bot.handleGroupTicketPayWall(ctx)
|
||||
}
|
||||
if splits[1] == "remove" {
|
||||
// todo -- implement this
|
||||
// return bot.addGroupHandler(ctx, m)
|
||||
@@ -213,6 +243,11 @@ func (bot TipBot) groupRequestJoinHandler(ctx intercept.Context) (intercept.Cont
|
||||
// groupSendPayButtonHandler is invoked if the user has enough balance so a message with a
|
||||
// pay button is sent to the user.
|
||||
func (bot *TipBot) groupSendPayButtonHandler(ctx intercept.Context, ticket TicketEvent) (intercept.Context, error) {
|
||||
confirmText, confirmationMenu := bot.getSendPayButton(ctx, ticket)
|
||||
bot.trySendMessageEditable(ctx.Message().Chat, confirmText, confirmationMenu)
|
||||
return ctx, nil
|
||||
}
|
||||
func (bot *TipBot) getSendPayButton(ctx intercept.Context, ticket TicketEvent) (string, *tb.ReplyMarkup) {
|
||||
// object that holds all information about the send payment
|
||||
// // // create inline buttons
|
||||
btnPayTicket := ticketPayConfirmationMenu.Data(Translate(ctx, "payButtonMessage"), "pay_ticket", ticket.Base.ID)
|
||||
@@ -224,8 +259,7 @@ func (bot *TipBot) groupSendPayButtonHandler(ctx intercept.Context, ticket Ticke
|
||||
if len(ticket.Group.Ticket.Memo) > 0 {
|
||||
confirmText = confirmText + fmt.Sprintf(Translate(ctx, "confirmPayAppendMemo"), str.MarkdownEscape(ticket.Group.Ticket.Memo))
|
||||
}
|
||||
bot.trySendMessageEditable(ctx.Message().Chat, confirmText, ticketPayConfirmationMenu)
|
||||
return ctx, nil
|
||||
return confirmText, ticketPayConfirmationMenu
|
||||
}
|
||||
|
||||
// groupConfirmPayButtonHandler is invoked if th user clicks the pay button.
|
||||
@@ -372,6 +406,104 @@ func (bot *TipBot) groupGetInviteLinkHandler(event Event) {
|
||||
}
|
||||
}
|
||||
|
||||
func (bot TipBot) handleGroupTicketPayWall(ctx intercept.Context) (intercept.Context, error) {
|
||||
var err error
|
||||
var cmd string
|
||||
if cmd, err = getArgumentFromCommand(ctx.Message().Text, 2); err == nil {
|
||||
switch strings.TrimSpace(strings.ToLower(cmd)) {
|
||||
case "del":
|
||||
fallthrough
|
||||
case "delete":
|
||||
fallthrough
|
||||
case "remove":
|
||||
return bot.removeGroupTicketPayWallHandler(ctx)
|
||||
default:
|
||||
return bot.addGroupTicketPayWallHandler(ctx)
|
||||
}
|
||||
}
|
||||
return ctx, err
|
||||
}
|
||||
func (bot TipBot) removeGroupTicketPayWallHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
groupName := strconv.FormatInt(ctx.Chat().ID, 10)
|
||||
tx := bot.DB.Groups.Where("id = ? COLLATE NOCASE", groupName).Delete(&Group{})
|
||||
if tx.Error != nil {
|
||||
return ctx, tx.Error
|
||||
}
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
func (bot TipBot) addGroupTicketPayWallHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
if m.Chat.Type == tb.ChatPrivate {
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddGroupHelpMessage"))
|
||||
return ctx, fmt.Errorf("not in group")
|
||||
}
|
||||
// parse command "/group add <grou_name> [<amount>]"
|
||||
splits := strings.Split(m.Text, " ")
|
||||
if len(splits) < 3 || len(m.Text) > 100 {
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupAddGroupHelpMessage"))
|
||||
return ctx, nil
|
||||
}
|
||||
groupName := strconv.FormatInt(ctx.Chat().ID, 10)
|
||||
|
||||
user := LoadUser(ctx)
|
||||
// check if the user is the owner of the group
|
||||
if !bot.isOwner(m.Chat, user.Telegram) {
|
||||
return ctx, fmt.Errorf("not owner")
|
||||
}
|
||||
|
||||
if !bot.isAdminAndCanInviteUsers(m.Chat, bot.Telegram.Me) {
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupBotIsNotAdminMessage"))
|
||||
return ctx, fmt.Errorf("bot is not admin")
|
||||
}
|
||||
|
||||
// check if the group with this name is already in db
|
||||
// only if a group with this name is owned by this user, it can be overwritten
|
||||
group := &Group{}
|
||||
tx := bot.DB.Groups.Where("id = ? COLLATE NOCASE", groupName).First(group)
|
||||
if tx.Error == nil {
|
||||
// if it is already added, check if this user is the admin
|
||||
if user.Telegram.ID != group.Owner.ID || group.ID != m.Chat.ID {
|
||||
bot.trySendMessage(m.Chat, Translate(ctx, "groupNameExists"))
|
||||
return ctx, fmt.Errorf("not owner")
|
||||
}
|
||||
}
|
||||
|
||||
amount := int64(0) // default amount is zero
|
||||
if amount_str, err := getArgumentFromCommand(m.Text, 2); err == nil {
|
||||
amount, err = GetAmount(amount_str)
|
||||
if err != nil {
|
||||
bot.trySendMessage(m.Sender, Translate(ctx, "lnurlInvalidAmountMessage"))
|
||||
return ctx, err
|
||||
}
|
||||
}
|
||||
|
||||
ticket := &Ticket{
|
||||
Price: amount,
|
||||
Memo: "Ticket for group " + groupName,
|
||||
Creator: user,
|
||||
Cut: 2,
|
||||
BaseFee: 100,
|
||||
CutCheap: 10,
|
||||
BaseFeeCheap: 10,
|
||||
}
|
||||
|
||||
group = &Group{
|
||||
Name: groupName,
|
||||
Title: m.Chat.Title,
|
||||
ID: m.Chat.ID,
|
||||
Owner: user.Telegram,
|
||||
Ticket: ticket,
|
||||
}
|
||||
|
||||
bot.DB.Groups.Save(group)
|
||||
log.Infof("[group] Ticket of %d sat added to group %s.", group.Ticket.Price, group.Name)
|
||||
msg := strings.Split(fmt.Sprintf(Translate(ctx, "groupAddedMessage"), str.MarkdownEscape(m.Chat.Title), group.Name, group.Ticket.Price, GetUserStrMd(bot.Telegram.Me), group.Name), "\n\n")[0]
|
||||
bot.trySendMessage(m.Chat, msg)
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// addGroupHandler is invoked if the user calls the "/group add" command
|
||||
func (bot TipBot) addGroupHandler(ctx intercept.Context) (intercept.Context, error) {
|
||||
m := ctx.Message()
|
||||
|
||||
@@ -498,6 +498,22 @@ func (bot TipBot) getHandler() []InterceptionWrapper {
|
||||
},
|
||||
},
|
||||
// group tickets
|
||||
{
|
||||
Endpoints: []interface{}{tb.OnUserJoined, tb.OnAddedToGroup},
|
||||
Handler: bot.handleTelegramNewMember,
|
||||
Interceptor: &Interceptor{
|
||||
Before: []intercept.Func{
|
||||
bot.localizerInterceptor,
|
||||
bot.logMessageInterceptor,
|
||||
bot.requireUserInterceptor,
|
||||
bot.lockInterceptor,
|
||||
},
|
||||
OnDefer: []intercept.Func{
|
||||
bot.unlockInterceptor,
|
||||
},
|
||||
},
|
||||
},
|
||||
// group tickets
|
||||
{
|
||||
Endpoints: []interface{}{"/group"},
|
||||
Handler: bot.groupHandler,
|
||||
|
||||
@@ -41,6 +41,7 @@ func initInvoiceEventCallbacks(bot *TipBot) {
|
||||
InvoiceCallbackGroupTicket: EventHandler{Function: bot.groupGetInviteLinkHandler, Type: EventTypeInvoice},
|
||||
InvoiceCallbackSatdressProxy: EventHandler{Function: bot.satdressProxyRelayPaymentHandler, Type: EventTypeInvoice},
|
||||
InvoiceCallbackGenerateDalle: EventHandler{Function: bot.generateDalleImages, Type: EventTypeInvoice},
|
||||
InvoiceCallbackPayGroupTicket: EventHandler{Function: bot.stopTicketTimer, Type: EventTypeInvoice},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,6 +54,7 @@ const (
|
||||
InvoiceCallbackGroupTicket
|
||||
InvoiceCallbackSatdressProxy
|
||||
InvoiceCallbackGenerateDalle
|
||||
InvoiceCallbackPayGroupTicket
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -753,7 +753,7 @@ func (bot *TipBot) addItemFileHandler(ctx intercept.Context) (intercept.Context,
|
||||
// // start a ticker to check if the user has sent more files
|
||||
// if t, ok := fileStateResetTicker.Get(shop.ID); ok {
|
||||
// // state reset ticker found. resetting ticker.
|
||||
// t.(*runtime.ResettableFunctionTicker).ResetChan <- struct{}{}
|
||||
// t.(*runtime.ResettableFunction).ResetChan <- struct{}{}
|
||||
// } else {
|
||||
// // state reset ticker not found. creating new one.
|
||||
// ticker := runtime.NewResettableFunctionTicker(runtime.WithDuration(time.Second * 5))
|
||||
|
||||
@@ -204,7 +204,7 @@ func (bot *TipBot) sendStatusMessageAndDelete(ctx intercept.Context, to tb.Recip
|
||||
id := fmt.Sprintf("shopview-delete-%d", user.Telegram.ID)
|
||||
statusMsg := bot.sendStatusMessage(ctx, to, what, options...)
|
||||
// kick off ticker to remove all messages
|
||||
ticker := runtime.GetTicker(id, runtime.WithDuration(5*time.Second))
|
||||
ticker := runtime.GetFunction(id, runtime.WithTicker(time.NewTicker(5*time.Second)), runtime.WithDuration(5*time.Second))
|
||||
if !ticker.Started {
|
||||
ticker.Do(func() {
|
||||
bot.shopViewDeleteAllStatusMsgs(ctx, user)
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/errors"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/lnbits"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/runtime"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/storage"
|
||||
"github.com/LightningTipBot/LightningTipBot/internal/telegram/intercept"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/skip2/go-qrcode"
|
||||
"github.com/tidwall/buntdb"
|
||||
tb "gopkg.in/lightningtipbot/telebot.v3"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
var defaultTicketDuration = time.Minute * 15
|
||||
|
||||
// handleTelegramNewMember is invoked when users join groups.
|
||||
// handler will create a new invoice and send it to the group chat.
|
||||
// a ticket callback timer function is stored in the blunt db.
|
||||
func (bot *TipBot) handleTelegramNewMember(ctx intercept.Context) (intercept.Context, error) {
|
||||
id := strconv.FormatInt(ctx.Chat().ID, 10)
|
||||
group, err := bot.loadGroup(id)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
if !bot.isAdmin(ctx.Chat(), bot.Telegram.Me) {
|
||||
fmt.Println("[TICKET] no admin")
|
||||
return ctx, fmt.Errorf("no admin rights")
|
||||
}
|
||||
user := LoadUser(ctx)
|
||||
ownerUser, err := GetUser(group.Owner, *bot)
|
||||
|
||||
ticket := JoinTicket{Sender: ctx.Sender(),
|
||||
Chat: ctx.Chat(),
|
||||
|
||||
Ticket: group.Ticket}
|
||||
|
||||
/* err = bot.Bunt.Get(&ticket)
|
||||
if err != nil {
|
||||
if err.Error() != "not found" {
|
||||
return ctx, err
|
||||
}
|
||||
}*/
|
||||
|
||||
// group owner creates invoice
|
||||
invoice, err := ownerUser.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: ticket.Ticket.Price,
|
||||
Memo: ticket.Ticket.Memo,
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[handleTelegramNewMember] Could not create an invoice: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// create qr code
|
||||
qr, err := qrcode.Encode(invoice.PaymentRequest, qrcode.Medium, 256)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// send the owner invoice to chat
|
||||
|
||||
ticketEvent := TicketEvent{
|
||||
InvoiceEvent: &InvoiceEvent{
|
||||
Base: storage.New(storage.ID(id)),
|
||||
Invoice: &Invoice{PaymentHash: invoice.PaymentHash,
|
||||
PaymentRequest: invoice.PaymentRequest,
|
||||
Amount: ticket.Ticket.Price,
|
||||
Memo: ticket.Ticket.Memo},
|
||||
Payer: user,
|
||||
Chat: ctx.Chat(),
|
||||
Callback: InvoiceCallbackPayGroupTicket,
|
||||
CallbackData: "",
|
||||
LanguageCode: ctx.Value("publicLanguageCode").(string),
|
||||
},
|
||||
Group: group,
|
||||
Base: storage.New(storage.ID(id)),
|
||||
}
|
||||
captionText := fmt.Sprintf("⚠️ %s, this group requires that you pay %d sat to be able to join.\n\nYou have 15 minutes to do it or you'll be kicked and banned for one day", GetUserStrMd(ctx.Message().Sender), ticket.Ticket.Price)
|
||||
entryMessage := &tb.Photo{
|
||||
File: tb.File{FileReader: bytes.NewReader(qr)},
|
||||
Caption: captionText}
|
||||
|
||||
// // if the user has enough balance, we send him a payment button
|
||||
balance, err := bot.GetUserBalance(user)
|
||||
if err != nil {
|
||||
errmsg := fmt.Sprintf("[/group] Error: Could not get user balance: %s", err.Error())
|
||||
log.Errorln(errmsg)
|
||||
bot.trySendMessage(ctx.Message().Sender, Translate(ctx, "errorTryLaterMessage"))
|
||||
return ctx, errors.New(errors.GetBalanceError, err)
|
||||
}
|
||||
var msg *tb.Message
|
||||
if balance >= group.Ticket.Price {
|
||||
confirm, menu := bot.getSendPayButton(ctx, ticketEvent)
|
||||
msg = bot.trySendMessageEditable(ctx.Chat(), fmt.Sprintf("%s\n%s", entryMessage.Caption, confirm), menu)
|
||||
} else {
|
||||
entryMessage.Caption = fmt.Sprintf("%s\n`%s`", entryMessage.Caption, invoice.PaymentRequest)
|
||||
msg = bot.trySendMessageEditable(ctx.Chat(), entryMessage)
|
||||
}
|
||||
ticketEvent.Message = msg
|
||||
ticket.Message = msg
|
||||
ticket.CreatedTimestamp = time.Now()
|
||||
err = bot.Bunt.Set(&ticket)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
// save invoice struct for later use
|
||||
err = ticketEvent.Set(&ticketEvent, bot.Bunt)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
err = ticketEvent.InvoiceEvent.Set(ticketEvent.InvoiceEvent, bot.Bunt)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
bot.startTicketCallbackFunctionTimer(ticket)
|
||||
fmt.Println(ctx.Message())
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
// stopTicketTimer will load the timer function based on the event.
|
||||
// should stop the ticker timer function and remove ticket from bluntDB.
|
||||
func (bot *TipBot) stopTicketTimer(event Event) {
|
||||
ev := event.(*InvoiceEvent)
|
||||
ticket := JoinTicket{Sender: ev.Payer.Telegram, Chat: ev.Chat}
|
||||
err := bot.Bunt.Get(&ticket)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
me, err := GetUser(bot.Telegram.Me, *bot)
|
||||
invoice, err := me.Wallet.Invoice(
|
||||
lnbits.InvoiceParams{
|
||||
Out: false,
|
||||
Amount: ticket.Ticket.Cut,
|
||||
Memo: ticket.Ticket.Memo,
|
||||
Webhook: internal.Configuration.Lnbits.WebhookServer},
|
||||
bot.Client)
|
||||
ticket.Ticket.Creator.Wallet.Pay(lnbits.PaymentParams{Bolt11: invoice.PaymentRequest, Out: true}, bot.Client)
|
||||
d := time.Until(time.Now().Add(defaultTicketDuration))
|
||||
bot.tryDeleteMessage(ev.Message)
|
||||
t := runtime.GetFunction(ticket.Key(), runtime.WithDuration(d))
|
||||
t.StopChan <- struct{}{}
|
||||
err = bot.Bunt.Delete(ticket.Key(), &ticket)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
}
|
||||
|
||||
// startTicketCallbackFunctionTimer will start a ticket which will ban users if the timer runs out.
|
||||
func (bot *TipBot) startTicketCallbackFunctionTimer(ticket JoinTicket) {
|
||||
// check if ticket is already expired
|
||||
if ticket.CreatedTimestamp.Add(defaultTicketDuration).Before(time.Now()) {
|
||||
return
|
||||
}
|
||||
// ticket is valid. create duration until kick
|
||||
ticketDuration := time.Until(ticket.CreatedTimestamp.Add(defaultTicketDuration))
|
||||
// create function timer
|
||||
t := runtime.NewResettableFunction(ticket.Key(),
|
||||
runtime.WithTimer(time.NewTimer(ticketDuration)))
|
||||
// run the ticket callback function
|
||||
t.Do(func() {
|
||||
// ticket expired
|
||||
member, err := bot.Telegram.ChatMemberOf(ticket.Chat, ticket.Sender)
|
||||
if err != nil {
|
||||
log.Errorln("🧨 could not fetch / ban chat member")
|
||||
return
|
||||
}
|
||||
// ban user
|
||||
err = bot.Telegram.Ban(ticket.Chat, member)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
err = bot.Bunt.Delete(ticket.Key(), &ticket)
|
||||
if err != nil {
|
||||
log.Errorln(err)
|
||||
}
|
||||
bot.tryDeleteMessage(ticket.Message)
|
||||
})
|
||||
}
|
||||
|
||||
func (bot *TipBot) restartPersistedTickets() {
|
||||
bot.Bunt.View(func(tx *buntdb.Tx) error {
|
||||
err := tx.Ascend("join-ticket", func(key, value string) bool {
|
||||
ticket := JoinTicket{}
|
||||
json.Unmarshal([]byte(value), &ticket)
|
||||
bot.startTicketCallbackFunctionTimer(ticket)
|
||||
return true // continue iteration
|
||||
})
|
||||
return err
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user