verochka/main.go

264 lines
6.1 KiB
Go

package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"student_bot/commands"
"student_bot/date"
"student_bot/messages"
"student_bot/new_year_service"
"student_bot/parser"
"time"
weather "github.com/3crabs/go-yandex-weather-api"
tgbot "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/umputun/go-flags"
)
type Opts struct {
Token string `short:"t" long:"token" description:"Telegram api token"`
Name string `short:"n" long:"name" description:"Telegram bot name" default:"@student_verochka_bot"`
Key string `short:"k" long:"key" description:"Yandex weather API key"`
ChatID int64 `short:"c" long:"chat_id" description:"Telegram chat id"`
}
var sendMessage = false
var opts Opts
func readToken() (string, error) {
b, err := ioutil.ReadFile("token.txt")
if err != nil {
return "", err
}
str := string(b)
str = strings.ReplaceAll(str, "\n", "")
return str, nil
}
func readWeatherToken() (string, error) {
b, err := ioutil.ReadFile("token_weather.txt")
if err != nil {
return "", err
}
str := string(b)
str = strings.ReplaceAll(str, "\n", "")
return str, nil
}
func readChatID() (int64, error) {
b, err := ioutil.ReadFile("chat_id.txt")
if err != nil {
return 0, err
}
str := string(b)
str = strings.ReplaceAll(str, "\n", "")
return strconv.ParseInt(str, 10, 64)
}
func main() {
run()
}
func run() {
p := flags.NewParser(&opts, flags.PrintErrors|flags.PassDoubleDash|flags.HelpFlag)
p.SubcommandsOptional = true
if _, err := p.Parse(); err != nil {
if err.(*flags.Error).Type != flags.ErrHelp {
log.Println(errors.New("[ERROR] cli error: " + err.Error()))
}
os.Exit(2)
}
if opts.Token == "" {
token, err := readToken()
if err != nil {
panic(err)
}
opts.Token = token
}
fmt.Println(opts.Token)
if opts.Key == "" {
token, err := readWeatherToken()
if err != nil {
panic(err)
}
opts.Key = token
}
fmt.Println(opts.Key)
if opts.ChatID == 0 {
chatID, err := readChatID()
if err != nil {
panic(err)
}
opts.ChatID = chatID
}
fmt.Println(opts.ChatID)
rand.Seed(time.Now().UnixNano())
imageService, err := new_year_service.NewNewYearService()
if err != nil {
log.Panicln(err)
}
imageService = new_year_service.NewNewYearServiceLogWrapper(imageService)
bot, err := tgbot.NewBotAPI(opts.Token)
if err != nil {
log.Panicln(err)
}
u := tgbot.NewUpdate(0)
u.Timeout = 60
updates, err := bot.GetUpdatesChan(u)
if err != nil {
log.Panicln(err)
}
go func() {
http.HandleFunc("/send_today_lessons_to_chat", func(w http.ResponseWriter, r *http.Request) {
sendTodayLessonsToChat(bot, opts.ChatID, "Сегодня эти пары:")
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprintf(w, `{"result":"ok"}`)
})
http.HandleFunc("/send_tomorrow_lessons_to_chat", func(w http.ResponseWriter, r *http.Request) {
sendTomorrowLessonsToChat(bot, opts.ChatID, "Завтра эти пары:")
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprintf(w, `{"result":"ok"}`)
})
http.HandleFunc("/send_new_year_to_chat", func(w http.ResponseWriter, r *http.Request) {
sendNewYearToChat(bot, opts.ChatID, imageService)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprintf(w, `{"result":"ok"}`)
})
port := ":10001"
log.Println("Server is start up! port", port)
log.Fatal(http.ListenAndServe(port, nil))
}()
log.Println("Bot is start up!")
for update := range updates {
// empty message
if update.Message == nil {
continue
}
text := update.Message.Text
chatID := update.Message.Chat.ID
if strings.Contains(strings.ToLower(text), "спасибо") {
if sendMessage {
_, _ = bot.Send(tgbot.NewMessage(chatID, messages.ThanksMessage()))
sendMessage = false
}
continue
}
sendMessage = false
command := commands.Command(strings.Replace(text, opts.Name, "", 1))
switch command {
case commands.Start:
send(bot, tgbot.NewMessage(chatID, messages.StartMessage()))
case commands.Help:
send(bot, tgbot.NewMessage(chatID, messages.HelpMessage(chatID)))
case commands.Ping:
send(bot, tgbot.NewMessage(chatID, messages.PongMessage()))
case commands.TodayLessons:
sendTodayLessonsToChat(bot, chatID, "Сегодня, "+update.Message.From.FirstName+", эти пары:")
case commands.TomorrowLessons:
sendTomorrowLessonsToChat(bot, chatID, "Завтра, "+update.Message.From.FirstName+", эти пары:")
case commands.AllLessons:
sendAllLessonsToChat(bot, chatID, "Пока знаю про эти пары:")
case commands.Weather:
w, err := weather.GetWeatherWithCache(opts.Key, 53.346853, 83.777012, time.Hour)
if err != nil {
continue
}
send(bot, tgbot.NewMessage(chatID, messages.WeatherMessage(w)))
case commands.NewYear:
sendNewYearToChat(bot, chatID, imageService)
default:
}
}
}
func send(bot *tgbot.BotAPI, msg tgbot.Chattable) {
_, _ = bot.Send(msg)
sendMessage = true
}
func sendTodayLessonsToChat(bot *tgbot.BotAPI, chatID int64, prefix string) {
send(
bot,
tgbot.NewMessage(
chatID,
messages.LessonsMessage(
parser.ParseByDay(date.Today(0)),
prefix,
"Сегодня пар нет",
),
),
)
}
func sendTomorrowLessonsToChat(bot *tgbot.BotAPI, chatID int64, prefix string) {
send(
bot,
tgbot.NewMessage(
chatID,
messages.LessonsMessage(
parser.ParseByDay(date.Today(24*time.Hour)),
prefix,
"Завтра пар нет",
),
),
)
}
func sendAllLessonsToChat(bot *tgbot.BotAPI, chatID int64, prefix string) {
send(
bot,
tgbot.NewMessage(
chatID,
messages.LessonsMessage(
parser.ParseByDay(""),
prefix,
"Пусто",
),
),
)
}
func sendNewYearToChat(bot *tgbot.BotAPI, chatID int64, imageService new_year_service.NewYearService) {
url := imageService.GetRandomImageURL()
message := imageService.GetRandomMessage()
msg := tgbot.NewPhotoShare(chatID, url)
msg.Caption = messages.NewYearMessage(message)
send(bot, msg)
}