Skip to content

Instantly share code, notes, and snippets.

@Pitasi
Created July 31, 2016 13:06
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 Pitasi/5e127825ab9538191617686b693fc41f to your computer and use it in GitHub Desktop.
Save Pitasi/5e127825ab9538191617686b693fc41f to your computer and use it in GitHub Desktop.
Skeleton for Telegram bots written in Go
/* https://pitasi.space/creare-un-piccolo-bot-di-telegram-usando-go/ */
package main
import (
"log"
"regexp"
"gopkg.in/telegram-bot-api.v4"
)
/* CONFIG STUFF */
var token = "TOKEN_TELEGRAM"
var supported_commands = map[string]func(m *tgbotapi.Message) {
"/ciao": ciao_handler,
//"/miocomando": comando_handler,
}
/* HANDLERS */
/* ESEMPIO
func comando_handler(m *tgbotapi.Message) {
* Attributi del messaggio:
id messaggio -> m.MessageID
id utente -> m.From.ID
testo completo del messaggio -> m.Text
id chat in cui è stato mandato -> m.Chat.ID
<- approfondimenti nella pagina della libreria: ->
<- https://github.com/go-telegram-bot-api/telegram-bot-api ->
* Creare un messaggio:
msg := tgbotapi.NewMessage(id della chat dove mandarlo, testo del messaggio)
* Inviare un messaggio:
bot.Send(msg)
}
*/
func ciao_handler(m *tgbotapi.Message) {
msg := tgbotapi.NewMessage(m.Chat.ID, "Heilà :)")
msg.ReplyToMessageID = m.MessageID
bot.Send(msg)
}
/* don't edit down here if you don't know what you are doing :D */
var r, _ = regexp.Compile("/([a-z0-9]+)")
var bot, err = tgbotapi.NewBotAPI(token)
/* AUX FUNCTIONS */
func is_command(s string) bool {
return s[0] == '/'
}
func get_command(s string) string {
return r.FindString(s)
}
/* MAIN CODE */
func process_message(m *tgbotapi.Message) {
// Controllo che il messaggio sia testuale e inizi con /
if (m.Text != "" && is_command(m.Text)) {
// Loggo il messaggio
log.Printf("[%s] %s", m.From.UserName, m.Text)
// Ricavo il nome del comando
command := get_command(m.Text)
// Cerco l'handler
f, found := supported_commands[command]
// Controllo se l'handler esiste e lo attivo altrimenti scarto
if found {
f(m)
} else {
return
}
}
}
func main() {
if err != nil {
log.Panic(err)
}
// decommentare per avere dei log più ricchi
// bot.Debug = true
log.Printf("Authorized on account %s", bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, _ := bot.GetUpdatesChan(u)
for update := range updates {
if update.Message == nil {
continue
}
process_message(update.Message)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment