verochka/main.go

264 lines
6.0 KiB
Go
Raw Normal View History

2022-03-05 18:02:55 +00:00
package main
import (
"errors"
2022-04-24 17:46:48 +00:00
"fmt"
"io/ioutil"
2022-03-05 18:02:55 +00:00
"log"
"math/rand"
2022-09-04 15:32:58 +00:00
"net/http"
2022-03-05 18:02:55 +00:00
"os"
"strconv"
2022-03-05 18:02:55 +00:00
"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"`
2022-03-05 18:02:55 +00:00
}
var sendMessage = false
var opts Opts
2022-04-24 17:46:48 +00:00
func readToken() (string, error) {
b, err := ioutil.ReadFile("token.txt")
if err != nil {
return "", err
}
str := string(b)
str = strings.ReplaceAll(str, "\n", "")
2022-04-24 17:46:48 +00:00
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", "")
2022-04-24 17:46:48 +00:00
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)
}
2022-03-05 18:02:55 +00:00
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)
}
2022-04-24 17:46:48 +00:00
if opts.Token == "" {
token, err := readToken()
if err != nil {
panic(err)
}
opts.Token = token
2022-04-24 17:46:48 +00:00
}
fmt.Println(opts.Token)
if opts.Key == "" {
token, err := readWeatherToken()
if err != nil {
panic(err)
}
opts.Key = token
2022-04-24 17:46:48 +00:00
}
fmt.Println(opts.Key)
if opts.ChatID == 0 {
chatID, err := readChatID()
if err != nil {
panic(err)
}
opts.ChatID = chatID
}
fmt.Println(opts.ChatID)
2022-04-24 17:46:48 +00:00
rand.Seed(time.Now().UnixNano())
2022-03-05 18:02:55 +00:00
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)
}
2022-09-04 15:32:58 +00:00
go func() {
http.HandleFunc("/send_today_lessons_to_chat", func(w http.ResponseWriter, r *http.Request) {
sendTodayLessonsToChat(bot, opts.ChatID, "Сегодня эти пары:")
2022-09-04 15:32:58 +00:00
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprintf(w, `{"result":"ok"}`)
})
2022-09-11 10:26:28 +00:00
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"}`)
})
2022-11-26 09:59:35 +00:00
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"}`)
})
2022-09-04 15:32:58 +00:00
port := ":10001"
log.Println("Server is start up! port", port)
log.Fatal(http.ListenAndServe(port, nil))
}()
2022-03-05 18:02:55 +00:00
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
2022-03-05 18:02:55 +00:00
if strings.Contains(strings.ToLower(text), "спасибо") {
if sendMessage {
_, _ = bot.Send(tgbot.NewMessage(chatID, messages.ThanksMessage()))
2022-03-05 18:02:55 +00:00
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()))
2022-03-05 18:02:55 +00:00
case commands.Help:
send(bot, tgbot.NewMessage(chatID, messages.HelpMessage(chatID)))
2022-03-05 18:02:55 +00:00
case commands.Ping:
send(bot, tgbot.NewMessage(chatID, messages.PongMessage()))
2022-03-05 18:02:55 +00:00
case commands.TodayLessons:
sendTodayLessonsToChat(bot, chatID, "Сегодня, "+update.Message.From.FirstName+", эти пары:")
2022-03-05 18:02:55 +00:00
case commands.TomorrowLessons:
2022-09-11 10:26:28 +00:00
sendTomorrowLessonsToChat(bot, chatID, "Завтра, "+update.Message.From.FirstName+", эти пары:")
2022-03-05 18:02:55 +00:00
2023-01-10 19:00:07 +00:00
case commands.AllLessons:
2023-02-10 08:51:04 +00:00
sendAllLessonsToChat(bot, chatID, "Пока знаю про эти пары:")
2023-01-10 19:00:07 +00:00
2022-03-05 18:02:55 +00:00
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)))
2022-03-05 18:02:55 +00:00
case commands.NewYear:
2022-11-26 09:59:35 +00:00
sendNewYearToChat(bot, chatID, imageService)
2022-03-05 18:02:55 +00:00
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,
2022-09-11 10:26:28 +00:00
tgbot.NewMessage(
chatID,
messages.LessonsMessage(
2023-01-10 19:00:07 +00:00
parser.ParseByDay(date.Today(0)),
prefix,
"Сегодня пар нет",
),
),
)
}
2022-09-11 10:26:28 +00:00
func sendTomorrowLessonsToChat(bot *tgbot.BotAPI, chatID int64, prefix string) {
send(
bot,
tgbot.NewMessage(
chatID,
messages.LessonsMessage(
2023-01-10 19:00:07 +00:00
parser.ParseByDay(date.Today(24*time.Hour)),
2022-09-11 10:26:28 +00:00
prefix,
"Завтра пар нет",
),
),
)
}
2022-11-26 09:59:35 +00:00
2023-01-10 19:00:07 +00:00
func sendAllLessonsToChat(bot *tgbot.BotAPI, chatID int64, prefix string) {
send(
bot,
tgbot.NewMessage(
chatID,
messages.LessonsMessage(
parser.ParseByDay(""),
prefix,
"Пусто",
),
),
)
}
2022-11-26 09:59:35 +00:00
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)
}