| 1 | package telegram |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | "io" |
| 7 | "os" |
| 8 | "os/signal" |
| 9 | "slices" |
| 10 | "strconv" |
| 11 | |
| 12 | "github.com/nicholas-fedor/shoutrrr/pkg/format" |
| 13 | "github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 14 | "github.com/nicholas-fedor/shoutrrr/pkg/util/generator" |
| 15 | ) |
| 16 | |
| 17 | // Generator facilitates Telegram-specific URL generation via user interaction. |
| 18 | type Generator struct { |
| 19 | userDialog *generator.UserDialog |
| 20 | client *Client |
| 21 | chats []string |
| 22 | chatNames []string |
| 23 | chatTypes []string |
| 24 | done bool |
| 25 | botName string |
| 26 | Reader io.Reader |
| 27 | Writer io.Writer |
| 28 | } |
| 29 | |
| 30 | // UpdatesLimit defines the number of updates to retrieve per API call. |
| 31 | const ( |
| 32 | UpdatesLimit = 10 // Number of updates to retrieve per call |
| 33 | UpdatesTimeout = 120 // Timeout in seconds for long polling |
| 34 | ) |
| 35 | |
| 36 | // ErrNoChatsSelected indicates that no chats were selected during generation. |
| 37 | var ( |
| 38 | ErrNoChatsSelected = errors.New("no chats were selected") |
| 39 | ) |
| 40 | |
| 41 | // Generate creates a Telegram Shoutrrr configuration from user dialog input. |
| 42 | func (g *Generator) Generate( |
| 43 | _ types.Service, |
| 44 | props map[string]string, |
| 45 | _ []string, |
| 46 | ) (types.ServiceConfig, error) { |
| 47 | var config Config |
| 48 | |
| 49 | if g.Reader == nil { |
| 50 | g.Reader = os.Stdin |
| 51 | } |
| 52 | |
| 53 | if g.Writer == nil { |
| 54 | g.Writer = os.Stdout |
| 55 | } |
| 56 | |
| 57 | g.userDialog = generator.NewUserDialog(g.Reader, g.Writer, props) |
| 58 | userDialog := g.userDialog |
| 59 | |
| 60 | userDialog.Writelnf( |
| 61 | "To start we need your bot token. If you haven't created a bot yet, you can use this link:", |
| 62 | ) |
| 63 | userDialog.Writelnf(" %v", format.ColorizeLink("https://t.me/botfather?start")) |
| 64 | userDialog.Writelnf("") |
| 65 | |
| 66 | token := userDialog.QueryString( |
| 67 | "Enter your bot token:", |
| 68 | generator.ValidateFormat(IsTokenValid), |
| 69 | "token", |
| 70 | ) |
| 71 | |
| 72 | userDialog.Writelnf("Fetching bot info...") |
| 73 | |
| 74 | g.client = &Client{ |
| 75 | token: token, |
| 76 | httpClient: nil, |
| 77 | } |
| 78 | |
| 79 | botInfo, err := g.client.GetBotInfo() |
| 80 | if err != nil { |
| 81 | return &Config{}, err |
| 82 | } |
| 83 | |
| 84 | g.botName = botInfo.Username |
| 85 | |
| 86 | userDialog.Writelnf("") |
| 87 | userDialog.Writelnf( |
| 88 | "Okay! %v will listen for any messages in PMs and group chats it is invited to.", |
| 89 | format.ColorizeString("@", g.botName), |
| 90 | ) |
| 91 | |
| 92 | g.done = false |
| 93 | lastUpdate := 0 |
| 94 | |
| 95 | signals := make(chan os.Signal, 1) |
| 96 | |
| 97 | // Subscribe to system signals for graceful shutdown |
| 98 | signal.Notify(signals, os.Interrupt) |
| 99 | |
| 100 | for !g.done { |
| 101 | userDialog.Writelnf("Waiting for messages to arrive...") |
| 102 | |
| 103 | updates, err := g.client.GetUpdates( |
| 104 | lastUpdate, |
| 105 | UpdatesLimit, |
| 106 | UpdatesTimeout, |
| 107 | nil, |
| 108 | ) |
| 109 | if err != nil { |
| 110 | panic(err) |
| 111 | } |
| 112 | |
| 113 | // If no updates were retrieved, prompt user to continue |
| 114 | promptDone := len(updates) == 0 |
| 115 | |
| 116 | for _, update := range updates { |
| 117 | lastUpdate = update.UpdateID + 1 |
| 118 | |
| 119 | switch { |
| 120 | case update.Message != nil || update.ChannelPost != nil: |
| 121 | message := update.Message |
| 122 | if update.ChannelPost != nil { |
| 123 | message = update.ChannelPost |
| 124 | } |
| 125 | |
| 126 | chat := message.Chat |
| 127 | |
| 128 | source := message.Chat.Name() |
| 129 | if message.From != nil { |
| 130 | source = "@" + message.From.Username |
| 131 | } |
| 132 | |
| 133 | userDialog.Writelnf("Got Message '%v' from %v in %v chat %v", |
| 134 | format.ColorizeString(message.Text), |
| 135 | format.ColorizeProp(source), |
| 136 | format.ColorizeEnum(chat.Type), |
| 137 | format.ColorizeNumber(chat.ID)) |
| 138 | userDialog.Writelnf(g.addChat(chat)) |
| 139 | // Another chat was added, prompt user to continue |
| 140 | promptDone = true |
| 141 | |
| 142 | case update.ChatMemberUpdate != nil: |
| 143 | cmu := update.ChatMemberUpdate |
| 144 | oldStatus := cmu.OldChatMember.Status |
| 145 | newStatus := cmu.NewChatMember.Status |
| 146 | userDialog.Writelnf( |
| 147 | "Got a bot chat member update for %v, status was changed from %v to %v", |
| 148 | format.ColorizeProp(cmu.Chat.Name()), |
| 149 | format.ColorizeEnum(oldStatus), |
| 150 | format.ColorizeEnum(newStatus), |
| 151 | ) |
| 152 | |
| 153 | default: |
| 154 | userDialog.Writelnf("Got unknown Update. Ignored!") |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | if promptDone { |
| 159 | userDialog.Writelnf("") |
| 160 | |
| 161 | g.done = !userDialog.QueryBool( |
| 162 | fmt.Sprintf("Got %v chat ID(s) so far. Want to add some more?", |
| 163 | format.ColorizeNumber(len(g.chats))), |
| 164 | "", |
| 165 | ) |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | userDialog.Writelnf("") |
| 170 | userDialog.Writelnf("Cleaning up the bot session...") |
| 171 | |
| 172 | // Notify API that we got the updates |
| 173 | if _, err = g.client.GetUpdates(lastUpdate, 0, 0, nil); err != nil { |
| 174 | g.userDialog.Writelnf( |
| 175 | "Failed to mark last updates as received: %v", |
| 176 | format.ColorizeError(err), |
| 177 | ) |
| 178 | } |
| 179 | |
| 180 | if len(g.chats) < 1 { |
| 181 | return nil, ErrNoChatsSelected |
| 182 | } |
| 183 | |
| 184 | userDialog.Writelnf("Selected chats:") |
| 185 | |
| 186 | for i, id := range g.chats { |
| 187 | name := g.chatNames[i] |
| 188 | chatType := g.chatTypes[i] |
| 189 | userDialog.Writelnf( |
| 190 | " %v (%v) %v", |
| 191 | format.ColorizeNumber(id), |
| 192 | format.ColorizeEnum(chatType), |
| 193 | format.ColorizeString(name), |
| 194 | ) |
| 195 | } |
| 196 | |
| 197 | userDialog.Writelnf("") |
| 198 | |
| 199 | config = Config{ |
| 200 | Notification: true, |
| 201 | Token: token, |
| 202 | Chats: g.chats, |
| 203 | } |
| 204 | |
| 205 | return &config, nil |
| 206 | } |
| 207 | |
| 208 | // addChat adds a chat to the generator's list if it’s not already present. |
| 209 | func (g *Generator) addChat(chat *Chat) string { |
| 210 | chatID := strconv.FormatInt(chat.ID, 10) |
| 211 | name := chat.Name() |
| 212 | |
| 213 | if slices.Contains(g.chats, chatID) { |
| 214 | return fmt.Sprintf("chat %v is already selected!", format.ColorizeString(name)) |
| 215 | } |
| 216 | |
| 217 | g.chats = append(g.chats, chatID) |
| 218 | g.chatNames = append(g.chatNames, name) |
| 219 | g.chatTypes = append(g.chatTypes, chat.Type) |
| 220 | |
| 221 | return fmt.Sprintf("Added new chat %v!", format.ColorizeString(name)) |
| 222 | } |