Skip to content

Instantly share code, notes, and snippets.

@Cibernomadas
Created May 20, 2018 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cibernomadas/7f7f40f0deeff85426b9e18a1ce333d4 to your computer and use it in GitHub Desktop.
Save Cibernomadas/7f7f40f0deeff85426b9e18a1ce333d4 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"regexp"
"strconv"
"strings"
"gopkg.in/telegram-bot-api.v4"
)
var CMDLIST = [...]string{"start", "suma", "resta", "multi", "div"}
var OPCMD = [...]string{"suma", "resta", "multi", "div"}
var STARTCMD = "start"
func main() {
bot, err := tgbotapi.NewBotAPI("** bot token **")
if err != nil {
log.Panic(err)
}
bot.Debug = true
log.Printf("Authorized on account %s", bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := bot.GetUpdatesChan(u)
for update := range updates {
if update.Message == nil {
continue
}
if update.Message.IsCommand() {
var args []string
var a, b int
var af, bf float64
var decimal bool
var err error
if esComandoValido(update.Message.Command()) {
if cmd, ok := esComandoCalc(update.Message.Command()); ok {
// Realizar operaciones de la calculadora
var txt string
args = normalizaCadena(update.Message.CommandArguments())
a, b, err = validaArgumentosInt(args)
if err != nil {
af, bf, err = validaArgumentosFloat(args)
if err != nil {
txt = "Los operandos proporcionados no son validos"
enviarMensaje(bot, update.Message.Chat.ID, update.Message.MessageID, txt)
break
}
decimal = true
} else {
decimal = false
}
if decimal {
switch cmd {
case "suma":
txt = fmt.Sprintf("%f", af+bf)
case "resta":
txt = fmt.Sprintf("%f", af-bf)
case "multi":
txt = fmt.Sprintf("%f", af*bf)
case "div":
if bf == 0 {
txt = "No es posible dividir un número por cero"
} else {
txt = fmt.Sprintf("%f", af/bf)
}
}
} else {
switch cmd {
case "suma":
txt = fmt.Sprintf("%d", a+b)
case "resta":
txt = fmt.Sprintf("%d", a-b)
case "multi":
txt = fmt.Sprintf("%d", a*b)
case "div":
if b == 0 {
txt = "No es posible dividir un número por cero"
} else {
txt = fmt.Sprintf("%d", a/b)
}
}
}
enviarMensaje(bot, update.Message.Chat.ID, update.Message.MessageID, txt)
} else if esComandoInicio(update.Message.Command()) {
// Mostrar mensaje de inicio
txt := `
¡¡Hola!! Bienvenido a la calculadora de cibernómadas.
Esta calculadora permite 4 operaciones básicas, suma, resta, multiplicación y división.
Para usar la calculadora usa los siguientes comandos con sus respectivos argumentos.
/suma <numA> <numB>, ej. /suma 1 2
/resta <numA> <numB>, ej. /resta 1 2
/mult <numA> <numB>, ej. /mult 1 2
/div <numA> <numB>, ej. /div 1 2`
enviarMensaje(bot, update.Message.Chat.ID, update.Message.MessageID, txt)
}
}
}
}
}
func normalizaCadena(arg string) []string {
re := regexp.MustCompile(" +")
aux := re.ReplaceAllString(arg, " ")
return strings.Split(aux, " ")
}
func validaArgumentosInt(args []string) (int, int, error) {
var a, b int
if len(args) == 2 {
a, err := strconv.Atoi(args[0])
if err != nil {
return a, b, err
}
b, err := strconv.Atoi(args[1])
if err != nil {
return a, b, err
}
return a, b, err
}
return a, b, fmt.Errorf("Número de argumentos no valido")
}
func validaArgumentosFloat(args []string) (float64, float64, error) {
var a, b float64
if len(args) == 2 {
a, err := strconv.ParseFloat(args[0], 64)
if err != nil {
return a, b, err
}
b, err := strconv.ParseFloat(args[1], 64)
if err != nil {
return a, b, err
}
return a, b, err
}
return a, b, fmt.Errorf("Número de argumentos no valido")
}
func esComandoValido(cmd string) bool {
for _, c := range CMDLIST {
if c == cmd {
return true
}
}
return false
}
func esComandoCalc(cmd string) (string, bool) {
for _, c := range OPCMD {
if c == cmd {
return cmd, true
}
}
return "", false
}
func esComandoInicio(cmd string) bool {
return cmd == STARTCMD
}
func enviarMensaje(b *tgbotapi.BotAPI, chat int64, id int, txt string) {
msg := tgbotapi.NewMessage(chat, txt)
msg.ReplyToMessageID = id
b.Send(msg)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment