Skip to content

Commit

Permalink
chore: refactor telegram commands (#79)
Browse files Browse the repository at this point in the history
  • Loading branch information
freak12techno authored Jul 27, 2024
1 parent f08b0e9 commit 7c74858
Show file tree
Hide file tree
Showing 6 changed files with 107 additions and 63 deletions.
26 changes: 11 additions & 15 deletions pkg/reporters/telegram/get_aliases.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,24 @@ import (
tele "gopkg.in/telebot.v3"
)

func (reporter *Reporter) HandleGetAliases(c tele.Context) error {
reporter.Logger.Info().
Str("sender", c.Sender().Username).
Str("text", c.Text()).
Msg("Got get aliases query")

reporter.MetricsManager.LogReporterQuery(reporter.Name(), constants.ReporterQueryGetAliases)
func (reporter *Reporter) GetGetAliasesCommand() Command {
return Command{
Name: "help",
Query: constants.ReporterQueryGetAliases,
Execute: reporter.HandleGetAliases,
}
}

func (reporter *Reporter) HandleGetAliases(c tele.Context) (string, error) {
if !reporter.AliasManager.Enabled() {
return reporter.BotReply(c, "Aliases manager not enabled!")
return "Aliases manager not enabled!", fmt.Errorf("aliases manager not enabled")
}

subscription, found := reporter.DataFetcher.FindSubscriptionByReporter(reporter.Name())
if !found {
return reporter.BotReply(c, "This reporter is not linked to any subscription!")
return "This reporter is not linked to any subscription!", fmt.Errorf("no subscriptions")
}

aliases := reporter.AliasManager.GetAliasesLinks(subscription.Name)
template, err := reporter.Render("Aliases", aliases)
if err != nil {
return reporter.BotReply(c, fmt.Sprintf("Error displaying aliases: %s", err))
}

return reporter.BotReply(c, template)
return reporter.Render("Aliases", aliases)
}
20 changes: 8 additions & 12 deletions pkg/reporters/telegram/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,14 @@ import (
tele "gopkg.in/telebot.v3"
)

func (reporter *Reporter) HandleHelp(c tele.Context) error {
reporter.Logger.Info().
Str("sender", c.Sender().Username).
Str("text", c.Text()).
Msg("Got help query")

reporter.MetricsManager.LogReporterQuery(reporter.Name(), constants.ReporterQueryHelp)

template, err := reporter.Render("Help", reporter.Version)
if err != nil {
return err
func (reporter *Reporter) GetHelpCommand() Command {
return Command{
Name: "help",
Query: constants.ReporterQueryHelp,
Execute: reporter.HandleHelp,
}
}

return reporter.BotReply(c, template)
func (reporter *Reporter) HandleHelp(c tele.Context) (string, error) {
return reporter.Render("Help", reporter.Version)
}
25 changes: 11 additions & 14 deletions pkg/reporters/telegram/list_nodes_status.go
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
package telegram

import (
"fmt"
"main/pkg/constants"
"main/pkg/types"

tele "gopkg.in/telebot.v3"
)

func (reporter *Reporter) HandleListNodesStatus(c tele.Context) error {
reporter.Logger.Info().
Str("sender", c.Sender().Username).
Str("text", c.Text()).
Msg("Got status query")

reporter.MetricsManager.LogReporterQuery(reporter.Name(), constants.ReporterQueryNodesStatus)
func (reporter *Reporter) GetListNodesCommand() Command {
return Command{
Name: "help",
Query: constants.ReporterQueryNodesStatus,
Execute: reporter.HandleListNodesStatus,
}
}

func (reporter *Reporter) HandleListNodesStatus(c tele.Context) (string, error) {
chains := reporter.DataFetcher.FindChainsByReporter(reporter.Name())
if len(chains) == 0 {
return reporter.BotReply(c, "This reporter is not linked to any chains!")
return "This reporter is not linked to any chains!", fmt.Errorf("no chains linked")
}

statuses := map[string]map[string]types.TendermintRPCStatus{}
Expand All @@ -33,10 +35,5 @@ func (reporter *Reporter) HandleListNodesStatus(c tele.Context) error {
}
}

template, err := reporter.Render("Status", statuses)
if err != nil {
return err
}

return reporter.BotReply(c, template)
return reporter.Render("Status", statuses)
}
32 changes: 16 additions & 16 deletions pkg/reporters/telegram/set_alias.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,22 @@ import (
tele "gopkg.in/telebot.v3"
)

func (reporter *Reporter) HandleSetAlias(c tele.Context) error {
reporter.Logger.Info().
Str("sender", c.Sender().Username).
Str("text", c.Text()).
Msg("Got set alias query")

reporter.MetricsManager.LogReporterQuery(reporter.Name(), constants.ReporterQuerySetAlias)
func (reporter *Reporter) GetSetAliasCommand() Command {
return Command{
Name: "help",
Query: constants.ReporterQuerySetAlias,
Execute: reporter.HandleSetAlias,
MinArgs: 3,
Usage: "Usage: %s <chain> <address> <alias>",
}
}

func (reporter *Reporter) HandleSetAlias(c tele.Context) (string, error) {
if !reporter.AliasManager.Enabled() {
return reporter.BotReply(c, "Aliases manager not enabled")
return "Aliases manager not enabled!", fmt.Errorf("aliases manager not enabled")
}

args := strings.SplitAfterN(c.Text(), " ", 4)
if len(args) < 4 {
return reporter.BotReply(c, fmt.Sprintf("Usage: %s <chain> <address> <alias>", args[0]))
}

chain, address, alias := args[1], args[2], args[3]
chain = strings.TrimSpace(chain)
Expand All @@ -32,21 +32,21 @@ func (reporter *Reporter) HandleSetAlias(c tele.Context) error {

chainFound := reporter.Config.Chains.FindByName(chain)
if chainFound == nil {
return reporter.BotReply(c, fmt.Sprintf("Chain %s is not found in config!", chain))
return fmt.Sprintf("Chain %s is not found in config!", chain), fmt.Errorf("chain not found")
}

subscription, found := reporter.DataFetcher.FindSubscriptionByReporter(reporter.Name())
if !found {
return reporter.BotReply(c, "This reporter is not linked to any subscription!")
return "This reporter is not linked to any subscription!", fmt.Errorf("no subscriptions")
}

if err := reporter.AliasManager.Set(subscription.Name, chain, address, alias); err != nil {
return reporter.BotReply(c, fmt.Sprintf("Error saving alias: %s", err))
return fmt.Sprintf("Error saving alias: %s", err), err
}

return reporter.BotReply(c, fmt.Sprintf(
return fmt.Sprintf(
"Saved alias: %s -> <code>%s</code>",
reporter.SerializeLink(chainFound.GetWalletLink(address)),
alias,
))
), nil
}
52 changes: 46 additions & 6 deletions pkg/reporters/telegram/telegram.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package telegram

import (
"bytes"
"errors"
"fmt"
"html"
"html/template"
Expand All @@ -10,6 +11,7 @@ import (
"main/pkg/metrics"
"main/pkg/types"
"main/pkg/types/amount"
"strings"
"time"

"github.com/dustin/go-humanize"
Expand Down Expand Up @@ -95,15 +97,53 @@ func (reporter *Reporter) Init() {
bot.Use(middleware.Whitelist(reporter.Admins...))
}

bot.Handle("/help", reporter.HandleHelp)
bot.Handle("/start", reporter.HandleHelp)
bot.Handle("/status", reporter.HandleListNodesStatus)
bot.Handle("/alias", reporter.HandleSetAlias)
bot.Handle("/aliases", reporter.HandleGetAliases)
reporter.AddCommand("/help", bot, reporter.GetHelpCommand())
reporter.AddCommand("/start", bot, reporter.GetHelpCommand())
reporter.AddCommand("/status", bot, reporter.GetListNodesCommand())
reporter.AddCommand("/alias", bot, reporter.GetSetAliasCommand())
reporter.AddCommand("/aliases", bot, reporter.GetGetAliasesCommand())

reporter.TelegramBot = bot
go reporter.TelegramBot.Start()
}

func (reporter *Reporter) AddCommand(query string, bot *tele.Bot, command Command) {
bot.Handle(query, func(c tele.Context) error {
reporter.Logger.Info().
Str("sender", c.Sender().Username).
Str("text", c.Text()).
Str("command", command.Name).
Msg("Got query")

reporter.MetricsManager.LogReporterQuery(reporter.Name(), command.Query)

args := strings.Split(c.Text(), " ")

if len(args)-1 < command.MinArgs {
if err := reporter.BotReply(c, html.EscapeString(fmt.Sprintf(command.Usage, args[0]))); err != nil {
return err
}

return errors.New("invalid invocation")
}

result, err := command.Execute(c)
if err != nil {
reporter.Logger.Error().
Err(err).
Str("command", command.Name).
Msg("Error processing command")
if result != "" {
return reporter.BotReply(c, result)
} else {
return reporter.BotReply(c, "Internal error!")
}
}

return reporter.BotReply(c, result)
})
}

func (reporter *Reporter) GetTemplate(name string) (*template.Template, error) {
if cachedTemplate, ok := reporter.Templates[name]; ok {
reporter.Logger.Trace().Str("type", name).Msg("Using cached template")
Expand Down Expand Up @@ -225,7 +265,7 @@ func (reporter *Reporter) BotReply(c tele.Context, msg string) error {
messages := utils.SplitStringIntoChunks(msg, MaxMessageSize)

for _, message := range messages {
if err := c.Reply(message, tele.ModeHTML); err != nil {
if err := c.Reply(message, tele.ModeHTML, tele.NoPreview); err != nil {
reporter.Logger.Error().Err(err).Msg("Could not send Telegram message")
return err
}
Expand Down
15 changes: 15 additions & 0 deletions pkg/reporters/telegram/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package telegram

import (
"main/pkg/constants"

tele "gopkg.in/telebot.v3"
)

type Command struct {
Name string
MinArgs int
Usage string
Query constants.ReporterQuery
Execute func(c tele.Context) (string, error)
}

0 comments on commit 7c74858

Please sign in to comment.