Skip to content

Commit

Permalink
Use MySQL database and ENV variables
Browse files Browse the repository at this point in the history
Fixes #4
  • Loading branch information
Brawl345 committed Mar 8, 2022
1 parent 8f57d61 commit 3260280
Show file tree
Hide file tree
Showing 15 changed files with 849 additions and 123 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
BOT_TOKEN=123456789:abcdefghijklmnopqrstuvxwyz
MYSQL_URL=user:password@tcp(127.0.0.1:3306)/database_name?charset=utf8mb4&parseTime=True&loc=Local
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
.idea
dist/
config.json
.env
3 changes: 0 additions & 3 deletions config.example.json

This file was deleted.

10 changes: 9 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,12 @@ module github.com/Brawl345/tagesschau-eilbot

go 1.17

require gopkg.in/telebot.v3 v3.0.0
require (
github.com/go-sql-driver/mysql v1.5.0
github.com/jmoiron/sqlx v1.3.4
github.com/joho/godotenv v1.4.0
github.com/rubenv/sql-migrate v1.1.1
gopkg.in/telebot.v3 v3.0.0
)

require github.com/go-gorp/gorp/v3 v3.0.2 // indirect
616 changes: 616 additions & 0 deletions go.sum

Large diffs are not rendered by default.

34 changes: 21 additions & 13 deletions handler/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ type TagesschauResponse struct {
}

func (h Handler) OnTimer() {
if h.Config.Debug {
if isDebugMode() {
log.Println("Checking for breaking news")
}

Expand All @@ -39,7 +39,6 @@ func (h Handler) OnTimer() {
}

func (h Handler) check() error {

resp, err := http.Get(ApiUrl)
if err != nil {
return err
Expand All @@ -62,7 +61,7 @@ func (h Handler) check() error {
}

if result.BreakingNews.Id == "" {
if h.Config.Debug {
if isDebugMode() {
log.Println("No breaking news found")
}
return nil
Expand All @@ -72,15 +71,19 @@ func (h Handler) check() error {
return errors.New("invalid breaking news")
}

if h.Config.LastEntry == result.BreakingNews.Id {
if h.Config.Debug {
lastEntry, err := h.DB.System.GetLastEntry()
if err != nil {
return fmt.Errorf("error while getting last entry: %w", err)
}

if lastEntry == result.BreakingNews.Id {
if isDebugMode() {
log.Println("Already notified of this breaking news")
}
return nil
}

log.Println("New breaking news found")
h.Config.LastEntry = result.BreakingNews.Id

sb := strings.Builder{}

Expand All @@ -98,7 +101,12 @@ func (h Handler) check() error {
groupText := "#EIL: " + sb.String()
privateText := sb.String() + textLink

for _, subscriber := range h.Config.Subscribers {
subscribers, err := h.DB.Subscribers.GetAll()
if err != nil {
return fmt.Errorf("error while getting subscribers: %w", err)
}

for _, subscriber := range subscribers {
if subscriber < 0 { // Group
_, err = h.Bot.Send(telebot.ChatID(subscriber), groupText, &telebot.SendOptions{
DisableWebPagePreview: true,
Expand All @@ -112,21 +120,21 @@ func (h Handler) check() error {
if err != nil {
if errors.Is(err, telebot.ErrChatNotFound) {
log.Printf("Chat %d not found, will be deleted", subscriber)
h.Config.RemoveSubscriber(subscriber)
h.DB.Subscribers.Delete(subscriber)
} else if errors.Is(err, telebot.ErrGroupMigrated) {
log.Printf("Chat %d migrated to new group", subscriber)
h.Config.RemoveSubscriber(subscriber)
h.Config.AddSubscriber(err.(*telebot.GroupError).MigratedTo)
h.DB.Subscribers.Delete(subscriber)
h.DB.Subscribers.Create(err.(*telebot.GroupError).MigratedTo)
} else {
log.Println(err)
}

}

}

err = h.Config.Save()
err = h.DB.System.SetLastEntry(result.BreakingNews.Id)
if err != nil {
return fmt.Errorf("failed writing config: %w", err)
return fmt.Errorf("failed writing last entry to DB: %w", err)
}

return nil
Expand Down
6 changes: 6 additions & 0 deletions handler/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package handler
import (
"gopkg.in/telebot.v3"
"log"
"os"
)

var defaultSendOptions = &telebot.SendOptions{
Expand All @@ -11,6 +12,11 @@ var defaultSendOptions = &telebot.SendOptions{
ParseMode: telebot.ModeHTML,
}

func isDebugMode() bool {
_, exists := os.LookupEnv("TAGESSCHAU_EILBOT_DEBUG")
return exists
}

func isGroupAdmin(bot *telebot.Bot, chatId, userId int64) bool {
data, err := bot.ChatMemberOf(telebot.ChatID(chatId), telebot.ChatID(userId))

Expand Down
4 changes: 2 additions & 2 deletions handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ import (
)

type Handler struct {
Bot *telebot.Bot
Config *storage.Config
Bot *telebot.Bot
DB *storage.DB
}
43 changes: 22 additions & 21 deletions handler/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package handler
import (
"gopkg.in/telebot.v3"
"log"
"strings"
)

func (h Handler) OnStart(c telebot.Context) error {
Expand All @@ -13,33 +14,33 @@ func (h Handler) OnStart(c telebot.Context) error {
}

chatId := c.Chat().ID
sb := strings.Builder{}

var text string
err := h.Config.AddSubscriber(chatId)
exists, _ := h.DB.Subscribers.Exists(chatId)
if exists {
sb.WriteString("<b>✅ Du erhältst bereits Eilmeldungen.</b>\n")
sb.WriteString("Nutze /stop zum Deabonnieren.")
return c.Send(sb.String(), defaultSendOptions)
}

err := h.DB.Subscribers.Create(chatId)
if err != nil {
text = "<b>✅ Du erhältst bereits Eilmeldungen.</b>\n"
text += "Nutze /stop zum Deabonnieren."
} else {
log.Println("New subscriber:", chatId)
err := h.Config.Save()
log.Println(err)
return c.Send("❌ Beim Abonnieren ist ein Fehler aufgetreten.", defaultSendOptions)
}

if err != nil {
log.Println("Failed writing config:", err)
return c.Send("❌ Beim Abonnieren ist ein Fehler aufgetreten.", defaultSendOptions)
}
log.Println("New subscriber:", chatId)

text = "<b>✅ Du erhältst jetzt neue Eilmeldungen!</b>\n"
text += "Nutze /stop, um keine Eilmeldungen mehr zu erhalten.\n"
text += "Für neue Tagesschau-Artikel, abonniere den @TagesschauDE-Kanal.\n\n"
sb.WriteString("<b>✅ Du erhältst jetzt neue Eilmeldungen!</b>\n")
sb.WriteString("Nutze /stop, um keine Eilmeldungen mehr zu erhalten.\n")
sb.WriteString("Für neue Tagesschau-Artikel, abonniere den @TagesschauDE-Kanal.\n\n")

text += "<b>ACHTUNG:</b> "
if c.Chat().Type == telebot.ChatPrivate {
text += "Wenn du den Bot blockierst, musst du die Eilmeldungen erneut abonnieren!"
} else {
text += "Wenn du den Bot aus der Gruppe entfernst, musst du die Eilmeldungen erneut abonnieren!"
}
sb.WriteString("<b>ACHTUNG:</b> ")
if c.Chat().Type == telebot.ChatPrivate {
sb.WriteString("Wenn du den Bot blockierst, musst du die Eilmeldungen erneut abonnieren!")
} else {
sb.WriteString("Wenn du den Bot aus der Gruppe entfernst, musst du die Eilmeldungen erneut abonnieren!")
}

return c.Send(text, defaultSendOptions)
return c.Send(sb.String(), defaultSendOptions)
}
35 changes: 17 additions & 18 deletions handler/stop.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package handler
import (
"gopkg.in/telebot.v3"
"log"
"strings"
)

func (h Handler) OnStop(c telebot.Context) error {
Expand All @@ -13,27 +14,25 @@ func (h Handler) OnStop(c telebot.Context) error {
}

chatId := c.Chat().ID
sb := strings.Builder{}

var text string

err := h.Config.RemoveSubscriber(chatId)

if err == nil {
log.Println("Removed subscription:", chatId)
err := h.Config.Save()

if err != nil {
log.Println("Failed writing config:", err)
return c.Send("❌ Beim Deabonnieren ist ein Fehler aufgetreten.", defaultSendOptions)
}
exists, _ := h.DB.Subscribers.Exists(chatId)
if !exists {
sb.WriteString("<b>❌ Eilmeldungen wurden noch nicht abonniert.</b>\n")
sb.WriteString("Nutze /start zum Abonnieren.")
return c.Send(sb.String(), defaultSendOptions)
}

text = "<b>✅ Du erhältst jetzt keine Eilmeldungen mehr.</b>\n"
text += "Nutze /start, um wieder Eilmeldungen zu erhalten.\n"
} else {
text = "<b>❌ Eilmeldungen wurden noch nicht abonniert.</b>\n"
text += "Nutze /start zum Abonnieren."
err := h.DB.Subscribers.Delete(chatId)
if err != nil {
log.Println(err)
return c.Send("❌ Beim Deabonnieren ist ein Fehler aufgetreten.", defaultSendOptions)
}

return c.Send(text, defaultSendOptions)
log.Println("Removed subscription:", chatId)

sb.WriteString("<b>✅ Du erhältst jetzt keine Eilmeldungen mehr.</b>\n")
sb.WriteString("Nutze /start, um wieder Eilmeldungen zu erhalten.\n")

return c.Send(sb.String(), defaultSendOptions)
}
27 changes: 20 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,52 @@ package main
import (
"github.com/Brawl345/tagesschau-eilbot/handler"
"github.com/Brawl345/tagesschau-eilbot/storage"
_ "github.com/joho/godotenv/autoload"
"log"
"os"
"time"

"gopkg.in/telebot.v3"
)

func main() {
var config = &storage.Config{}
err := config.Load()
db, err := storage.Open(os.Getenv("TAGESSCHAU_EILBOT_MYSQL_URL"))
if err != nil {
log.Fatal(err)
}

if err := db.Ping(); err != nil {
log.Fatal(err)
}

log.Println("Database connection established")

n, err := db.Migrate()
if err != nil {
log.Fatalln(err)
}
if n > 0 {
log.Printf("Applied %d migration(s)", n)
}

pref := telebot.Settings{
Token: config.Token,
Token: os.Getenv("TAGESSCHAU_EILBOT_TOKEN"),
Poller: &telebot.LongPoller{Timeout: 10 * time.Second},
}

bot, err := telebot.NewBot(pref)
if err != nil {
log.Fatalln(err)
return
}

log.Printf("Logged in as @%s (%d)", bot.Me.Username, bot.Me.ID)

h := handler.Handler{
Bot: bot,
Config: config,
Bot: bot,
DB: db,
}

time.AfterFunc(10*time.Second, h.OnTimer)
time.AfterFunc(5*time.Second, h.OnTimer)

bot.Handle("/help", h.OnHelp)
bot.Handle("/hilfe", h.OnHelp)
Expand Down
20 changes: 20 additions & 0 deletions storage/migrations/0001-init.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
-- +migrate Up

CREATE TABLE IF NOT EXISTS `subscribers`
(
`id` bigint(20) NOT NULL,
`created_at` datetime NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;

CREATE TABLE IF NOT EXISTS `system`
(
`key` VARCHAR(20) NOT NULL,
`value` VARCHAR(255) NOT NULL,
PRIMARY KEY (`key`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4;

INSERT INTO `system` (`key`, `value`)
VALUES ('last_entry', '');
Loading

0 comments on commit 3260280

Please sign in to comment.