Created
January 18, 2016 02:49
-
-
Save gourytch/139f220f2322d9708afd to your computer and use it in GitHub Desktop.
small telegram bot example for golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// test new bot api | |
// start it as: | |
// gourbot "token:forBot" | |
// or | |
// BOT_TOKEN="token:forBot" gourbot | |
// | |
package main | |
import ( | |
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" | |
"log" | |
"os" | |
) | |
func GetToken() string { | |
if len(os.Args) > 1 { | |
log.Println("got token from command line arg") | |
return os.Args[1] | |
} | |
v := os.Getenv("BOT_TOKEN") | |
if v != "" { | |
log.Println("got token from envvar") | |
return v | |
} | |
log.Fatal("token not set. set it as commandline arg or in BOT_TOKEN envvar") | |
return "" | |
} | |
func main() { | |
log.Println("create bot api") | |
bot, err := tgbotapi.NewBotAPI(GetToken()) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
log.Println("connection established, get my id") | |
user, err := bot.GetMe() | |
if err != nil { | |
log.Fatalln(err) | |
} | |
log.Printf("My user record: %#v", user) | |
log.Println("create channel for updates") | |
updates_config := tgbotapi.NewUpdate(0) | |
updates_config.Timeout = 60 | |
updates, err := bot.GetUpdatesChan(updates_config) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
log.Println("channel created. handle updates trough channel") | |
for { | |
update, ok := <-updates | |
if !ok { | |
log.Println("connection lost") | |
break | |
} | |
log.Printf("got %#v", update) | |
if bot.IsMessageToMe(update.Message) { | |
log.Println("it is an message for me!") | |
reply := tgbotapi.NewMessage(update.Message.Chat.ID, | |
update.Message.From.String() + | |
", I hear you and your message: " + | |
update.Message.Text) | |
reply.ReplyToMessageID = update.Message.MessageID | |
log.Println("send reply") | |
m2, err := bot.Send(reply) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
log.Printf("send result: %#v", m2) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment