Go tgbot 轮询返回命令

7 min read
bot, err := tgbotapi.NewBotAPI(Token)
u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	updates := bot.GetUpdatesChan(u)

	for update := range updates {
		if update.Message == nil { // ignore any non-Message updates
			continue
		}

		if !update.Message.IsCommand() { // ignore any non-command Messages
			continue
		}

		// Create a new MessageConfig. We don't have text yet,
		// so we leave it empty.
		msg := tgbotapi.NewMessage(update.Message.Chat.ID, "")

		// Extract the command from the Message.
		switch update.Message.Command() {
		case "start":
			result := &model.User{}
			database.Db.Find(result, "chat_id = ?", update.Message.Chat.ID)
			if result.ChatID == 0 {
				database.Db.Create(&model.User{
					ChatID: update.Message.Chat.ID,
				})
				msg.Text = "Thank you for subscribing, please wait for the next update"
			} else {
				msg.Text = "your id is " + fmt.Sprintf("%d", update.Message.Chat.ID) + " already subscribed! please wait for the next update"
			}

		case "hi":
			msg.Text = "Hi :)"
		case "status":
			msg.Text = "I'm ok."
		default:
			msg.Text = "I don't know that command"
		}

		if _, err := bot.Send(msg); err != nil {
			log.Panic(err)
		}
	}