Compare commits

...

26 commits
master ... v3

Author SHA1 Message Date
4b9e6283cf minor docker compose changes 2024-06-03 22:41:42 +02:00
cf0ce42636 gofmt 2024-06-03 22:40:17 +02:00
3f3e75a5be Remove yourls 2024-06-03 21:14:31 +02:00
watn3y
02c9f2af6b logging changes 2023-12-29 07:54:27 +01:00
watn3y
be0cc403b9 go fmt 2023-12-29 05:34:41 +01:00
watn3y
5c8c0eb69c go fmt 2023-12-29 05:28:34 +01:00
watn3y
cd14452f31 go mod 2023-12-29 05:24:48 +01:00
watn3y
6375fe5af1 A bunch of Changes
Docker is broken as of now, will fix later
2023-12-29 05:15:23 +01:00
watn3y
1a6953900c various improvements 2023-12-29 02:35:52 +01:00
watn3y
d5272262da rename module 2023-12-29 00:25:33 +01:00
watn3y
257ed6f82b remove duplicate 2023-12-28 23:52:26 +01:00
watn3y
1c24e0a0f6 Update .gitignore 2023-12-28 23:48:12 +01:00
watn3y
d4fd21d98e Added config generator 2023-12-28 23:46:52 +01:00
watn3y
dbb7552fe3 remove unneeded files 2023-12-28 23:15:06 +01:00
watn3y
8b52cecdb2 go mod 2023-12-28 23:12:20 +01:00
watn3y
72e3122e26 i want to die and sleep 2023-10-27 05:39:34 +00:00
watn3y
cf8b6164f0 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG 2023-10-27 05:14:37 +00:00
watn3y
56ae7a27bf FUCK musl, glibc is my friend now 2023-10-27 05:09:59 +00:00
watn3y
e199bbbca4 yeah i forgot to push the important files 2023-10-27 04:36:48 +00:00
watn3y
b72615db63 New Docker build system 2023-10-27 00:53:18 +00:00
watn3y
08c84f57d3 Minor fix 2023-10-27 01:20:32 +02:00
watn3y
7d4c9c5ab9 added proper logging to most of the code 2023-09-07 03:24:31 +02:00
watn3y
65c6020e49 update go mods 2023-09-06 19:39:48 +02:00
watn3y
622dd3c16a add todolist 2023-09-06 19:33:55 +02:00
watn3y
caa8e41d21 add html redirect from / 2023-09-06 18:55:53 +02:00
watn3y
92607f5275 remove nhentai feature 2023-09-06 18:47:12 +02:00
41 changed files with 691 additions and 511 deletions

2
.gitignore vendored
View file

@ -108,4 +108,4 @@ fabric.properties
# CUSTOM # CUSTOM
config.toml data/

8
.idea/.gitignore vendored
View file

@ -1,8 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View file

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/bloaterbot.iml" filepath="$PROJECT_DIR$/.idea/bloaterbot.iml" />
</modules>
</component>
</project>

View file

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

View file

@ -1,29 +1,44 @@
# syntax=docker/dockerfile:1 ## syntax=docker/dockerfile:1
FROM golang:1.20-alpine #build container
FROM golang:1.21-alpine3.18 as build
WORKDIR /tmp/build WORKDIR /tmp/build
#install update system and install packages ARG TARGETPLATFORM TARGETOS TARGETARCH BUILDOS BUILDARCH
RUN apk update RUN apk update
RUN apk upgrade --available RUN apk upgrade --available
RUN apk add alpine-sdk ffmpeg python3 py3-pip RUN apk add alpine-sdk
#install yt-dlp
RUN pip3 install yt-dlp
#build bloaterbot #build bloaterbot
COPY . . COPY . .
RUN go mod download RUN go mod download
RUN mkdir /app RUN mkdir /tmp/build/output
ARG CGO_ENABLED=0
RUN go build -o /tmp/build/output/bloaterbot
#final container
FROM alpine:3.18
#update system and install packages
RUN apk update
RUN apk upgrade --available
RUN apk add --no-cache ffmpeg python3 py3-pip
RUN pip3 install --upgrade yt-dlp
ARG CGO_ENABLED=1
ENV COMMIT=${COMMIT} ENV COMMIT=${COMMIT}
RUN go build -o /app/bloaterbot
WORKDIR /app WORKDIR /app
RUN rm -rf /tmp/build COPY --from=build /tmp/build/output/bloaterbot /app/bloaterbot
COPY bloater.webp /app
CMD [ "/app/bloaterbot" ]
COPY bloater.webp /app/bloater.webp
COPY entrypoint.sh /app/entrypoint.sh
RUN chmod -x /app/entrypoint.sh
CMD ["/bin/ash", "/app/entrypoint.sh"]

15
TODO.md Normal file
View file

@ -0,0 +1,15 @@
//TODO
- Improve logging
- differentiate between debug and non-debug logs
- Separate download backend into multiple functions
- make YouTube and http backend
- maybe http upload backend
- add nenefoot feature
- integrate nenefoot into db
- add nene details
- user, time, codec, etc
- seperate sql from gaypoints
- prepare SQL queries in functions and send them to sql
- move SQL logs from sql to other
-

41
bot.go
View file

@ -1,29 +1,46 @@
package main package main
import ( import (
"log"
"time" "time"
"watn3y/bloaterbotv3/botIO"
"watn3y/bloaterbotv3/commands" "github.com/rs/zerolog/log"
"watn3y/bloaterbotv3/commands/notify" "watn3y.de/bloaterbot/botIO"
"watn3y/bloaterbotv3/text" "watn3y.de/bloaterbot/commands"
"watn3y.de/bloaterbot/commands/notify"
"watn3y.de/bloaterbot/inline/nenefoot"
"watn3y.de/bloaterbot/text"
) )
func bot() { func bot() {
updates, bot := botIO.Authenticate() updates, bot := botIO.Authenticate()
go notify.NotifyHandler(bot) go notify.NotifyHandler(bot)
now := time.Now().UTC()
for update := range updates { for update := range updates {
if update.Message == nil || update.Message.Time().UTC().Unix() < now.UTC().Unix() { log.Trace().Interface("update", update).Msg("Received update")
if update.InlineQuery != nil && update.Message == nil {
nenefoot.Nenefoot(update, bot)
continue continue
} }
log.Printf("[bot] Recieved Message: [%s] %s", update.Message.From.FirstName, update.Message.Text)
if update.Message.IsCommand() { if update.Message != nil && update.Message.Text != "" {
commands.Commands(update, bot) if update.Message.Time().UTC().Unix() < time.Now().UTC().Unix() {
} else { continue
text.Matcher(update, bot) }
log.Info().Int64("ChatID", update.Message.Chat.ID).Int64("UserID", update.Message.From.ID).Str("Text", update.Message.Text).Msg("Recieved Message")
if update.Message.IsCommand() {
commands.Commands(update, bot)
} else {
text.Matcher(update, bot)
continue
}
} }
log.Trace().Interface("update", update).Msg("Unable to parse update")
} }
} }

View file

@ -2,23 +2,24 @@ package botIO
import ( import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"log" "github.com/rs/zerolog/log"
"watn3y/bloaterbotv3/config" "watn3y.de/bloaterbot/config"
) )
func Authenticate() (tgbotapi.UpdatesChannel, *tgbotapi.BotAPI) { func Authenticate() (tgbotapi.UpdatesChannel, *tgbotapi.BotAPI) {
b, err := tgbotapi.NewBotAPI(config.BotConfig.APIToken) bot, err := tgbotapi.NewBotAPI(config.BotConfig.APIToken)
if err != nil { if err != nil {
log.Panicf("Failed to connect Bot to Telegram: %v\n", err) log.Panic().Err(err).Msg("Failed to authorize bot")
} }
b.Debug = config.BotConfig.DebugMode bot.Debug = config.BotConfig.DebugMode
u := tgbotapi.NewUpdate(0) updates := tgbotapi.NewUpdate(0)
u.Timeout = 60 updates.Timeout = 60
log.Printf("[bot] Authorized on account %s", b.Self.UserName)
return b.GetUpdatesChan(u), b log.Info().Int64("ID", bot.Self.ID).Str("username", bot.Self.UserName).Msg("Successfully authorized bot")
return bot.GetUpdatesChan(updates), bot
} }

View file

@ -1,12 +1,18 @@
package botIO package botIO
import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" import (
"github.com/rs/zerolog/log"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
func GetUserByID(userToGet tgbotapi.ChatConfigWithUser, bot *tgbotapi.BotAPI) (error bool, member tgbotapi.ChatMember) { func GetUserByID(userToGet tgbotapi.ChatConfigWithUser, bot *tgbotapi.BotAPI) (error bool, member tgbotapi.ChatMember) {
member, err := bot.GetChatMember(tgbotapi.GetChatMemberConfig{ChatConfigWithUser: userToGet}) member, err := bot.GetChatMember(tgbotapi.GetChatMemberConfig{ChatConfigWithUser: userToGet})
if err != nil { if err != nil {
log.Error().Err(err).Msg("Unable to get info for user")
return true, member return true, member
} }
log.Debug().Interface("member", member).Msg("Got Info for user")
return false, member return false, member
} }

View file

@ -2,55 +2,70 @@ package botIO
import ( import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"log" "github.com/rs/zerolog/log"
) )
func SendMessage(message tgbotapi.MessageConfig, bot *tgbotapi.BotAPI) (result tgbotapi.Message) { func SendMessage(message tgbotapi.MessageConfig, bot *tgbotapi.BotAPI) (result tgbotapi.Message) {
result, err := bot.Send(message) result, err := bot.Send(message)
if err != nil { if err != nil {
log.Printf("Failed to send message: %v\n", err) log.Error().Err(err).Msg("Failed to send message")
return return
} }
log.Printf("[bot] Sent Message: %s", message.Text)
log.Info().Int64("chat", result.Chat.ID).Str("msg", result.Text).Msg("Sent message")
log.Debug().Interface("msg", result).Msg("")
return result return result
} }
func EditMessage(message tgbotapi.EditMessageTextConfig, bot *tgbotapi.BotAPI) (result tgbotapi.Message) { func EditMessage(message tgbotapi.EditMessageTextConfig, bot *tgbotapi.BotAPI) (result tgbotapi.Message) {
result, err := bot.Send(message) result, err := bot.Send(message)
if err != nil { if err != nil {
log.Printf("Failed to send message: %v\n", err) log.Error().Err(err).Msg("Failed to edit message")
return return
} }
log.Printf("[bot] Edited Message: %s", message.Text)
log.Info().Int64("chat", result.Chat.ID).Str("msg", result.Text).Msg("Edited message")
log.Debug().Interface("msg", result).Msg("")
return result return result
} }
func SendVideo(message tgbotapi.VideoConfig, bot *tgbotapi.BotAPI) (result tgbotapi.Message) { func SendVideo(message tgbotapi.VideoConfig, bot *tgbotapi.BotAPI) (result tgbotapi.Message) {
result, err := bot.Send(message) result, err := bot.Send(message)
if err != nil { if err != nil {
log.Printf("Failed to send message: %v\n", err) log.Error().Err(err).Msg("Failed to send video")
return return
} }
log.Printf("[bot] Sent Video: %s", message.File)
log.Info().Int64("chat", result.Chat.ID).Msg("Sent video")
log.Debug().Interface("video", result).Msg("")
return result return result
} }
func SendPhoto(message tgbotapi.PhotoConfig, bot *tgbotapi.BotAPI) (result tgbotapi.Message) { func SendPhoto(message tgbotapi.PhotoConfig, bot *tgbotapi.BotAPI) (result tgbotapi.Message) {
result, err := bot.Send(message) result, err := bot.Send(message)
if err != nil { if err != nil {
log.Printf("Failed to send message: %v\n", err) log.Error().Err(err).Msg("Failed to send photo")
return return
} }
log.Printf("[bot] Sent Photo: %s", message.File)
log.Info().Int64("chat", result.Chat.ID).Msg("Sent photo")
log.Debug().Interface("photo", result).Msg("")
return result return result
} }
func SendSticker(sticker tgbotapi.StickerConfig, bot *tgbotapi.BotAPI) (result tgbotapi.Message) { func SendSticker(message tgbotapi.StickerConfig, bot *tgbotapi.BotAPI) (result tgbotapi.Message) {
result, err := bot.Send(sticker) result, err := bot.Send(message)
if err != nil { if err != nil {
log.Printf("Failed to send Sticker: %v\n", err) log.Error().Err(err).Msg("Failed to send sticker")
return return
} }
log.Printf("[bot] Sent Sticker")
log.Info().Int64("chat", result.Chat.ID).Msg("Sent sticker")
log.Debug().Interface("sticker", result).Msg("")
return result return result
} }

8
build.sh Normal file → Executable file
View file

@ -1,4 +1,8 @@
###!/usr/bin/env bash ###!/usr/bin/env bash
HASH=$(git log -1 --pretty=%h) read -p 'Tag: ' tag
docker build -t bloaterbot:latest -t bloaterbot:$HASH --build-arg=COMMIT=$(git log -1 --pretty=%h) .
docker build --no-cache --tag bloaterbot:$(git log -1 --pretty=%h) --tag bloaterbot:$tag --build-arg=COMMIT=$(git log -1 --pretty=%h) .

View file

@ -1,44 +1,59 @@
package commands package commands
import ( import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"log"
"os" "os"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"watn3y/bloaterbotv3/botIO"
"watn3y/bloaterbotv3/commands/download" "watn3y.de/bloaterbot/botIO"
"watn3y/bloaterbotv3/commands/gaypoints" "watn3y.de/bloaterbot/commands/download"
"watn3y/bloaterbotv3/commands/notify" "watn3y.de/bloaterbot/commands/gaypoints"
"watn3y/bloaterbotv3/config" "watn3y.de/bloaterbot/commands/notify"
"watn3y.de/bloaterbot/commonlogic"
"watn3y.de/bloaterbot/config"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/rs/zerolog/log"
) )
func Commands(update tgbotapi.Update, bot *tgbotapi.BotAPI) { func Commands(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
cmd := strings.ToLower(update.Message.Command()) cmd := strings.ToLower(update.Message.Command())
log.Trace().Str("cmd", cmd).Msg("Matching command")
switch cmd { switch cmd {
case "shutup": case "shutup":
shutup(update, bot) go shutup(update, bot)
break
case "shut": case "shut":
shutup(update, bot) go shutup(update, bot)
break
case "gp": case "gp":
gaypoints.GetGP(update, bot) gaypoints.GetGP(update, bot)
break
case "addgp": case "addgp":
gaypoints.SetGP(update, bot) gaypoints.SetGP(update, bot)
break
case "subtractgp": case "subtractgp":
gaypoints.SetGP(update, bot) gaypoints.SetGP(update, bot)
break
case "remindme": case "remindme":
notify.Reminder(update, bot) notify.Reminder(update, bot)
break
case "download": case "download":
go download.Download(update, bot) go download.Download(update, bot)
break
case "dl": case "dl":
go download.Download(update, bot) go download.Download(update, bot)
break
case "help": case "help":
help(update, bot) help(update, bot)
break
case "info": case "info":
info(update, bot) info(update, bot)
break
} }
} }
@ -46,7 +61,7 @@ func shutup(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
config.BotConfig.Shutup[update.Message.Chat.ID] = time.Now().UTC() config.BotConfig.Shutup[update.Message.Chat.ID] = time.Now().UTC()
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Shutting up") msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Shutting up")
log.Println("Shutting up for Chat: " + strconv.FormatInt(update.Message.Chat.ID, 10)) log.Info().Int64("chat", update.Message.Chat.ID).Msg("Shutting up")
botIO.SendMessage(msg, bot) botIO.SendMessage(msg, bot)
@ -77,12 +92,13 @@ func info(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
if commit == "" { if commit == "" {
commit = "not available" commit = "not available"
} }
info, _ := os.Stat("./bloater.db")
dbSizeInKiloBytes := info.Size() / 1000
textInfo := "<b>" + me.FirstName + "</b>" + "\n\n" + textInfo := "<b>" + me.FirstName + "</b>" + "\n\n" +
"<b>Commit:</b> " + "<code>" + commit + "</code>" + "\n" + "<b>Commit:</b> " + "<code>" + commit + "</code>" + "\n" +
"<b>DB Size:</b> " + "<code>" + strconv.FormatInt(dbSizeInKiloBytes, 10) + "KB" + "</code>" "<b>DB Size:</b> " + "\n" +
"gaypoints.db: " + "<code>" + strconv.FormatInt(commonlogic.GetFileSize("data/db/gaypoints.db"), 10) + " Bytes" + "</code>" + "\n" +
"notify.db: " + "<code>" + strconv.FormatInt(commonlogic.GetFileSize("data/db/notify.db"), 10) + " Bytes" + "</code>" + "\n" +
"nenefoot.db: " + "<code>" + strconv.FormatInt(commonlogic.GetFileSize("data/db/nenefoot.db"), 10) + " Bytes" + "</code>" + "\n"
message := tgbotapi.MessageConfig{ message := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},

View file

@ -2,44 +2,46 @@ package download
import ( import (
"errors" "errors"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" log2 "log"
"io"
"log"
"math/rand" "math/rand"
"net/http"
"net/url" "net/url"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strconv"
"strings" "strings"
"time" "time"
"watn3y/bloaterbotv3/botIO"
"watn3y/bloaterbotv3/commonlogic" "watn3y.de/bloaterbot/botIO"
"watn3y/bloaterbotv3/config" "watn3y.de/bloaterbot/commonlogic"
"watn3y.de/bloaterbot/config"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/rs/zerolog/log"
) )
// TODO logging
// TODO error handling
// TODO rewrite
func Download(update tgbotapi.Update, bot *tgbotapi.BotAPI) { func Download(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
log.Println("[download] Downloading URL " + update.Message.CommandArguments() + " for " + strconv.FormatInt(update.Message.From.ID, 10) + " in chat " + strconv.FormatInt(update.Message.Chat.ID, 10)) log.Debug().Int64("chat", update.Message.Chat.ID).Int64("user", update.Message.From.ID).Msg("starting download")
commandArgs := strings.Fields(update.Message.CommandArguments()) commandArgs := strings.Fields(update.Message.CommandArguments())
msg := tgbotapi.MessageConfig{ msg := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},
Text: "Downloading your media...", Text: "Downloading your YouTube Video...",
} }
workingMessage := botIO.SendMessage(msg, bot) workingMessage := botIO.SendMessage(msg, bot)
if len(commandArgs) >= 1 && matchURL(commandArgs[0]) != "" { if len(commandArgs) >= 1 && matchURL(commandArgs[0]) != "" {
//TODO distinguish
//service := matchURL(commandArgs[0])
} else { } else {
log.Println("[download] Failed to download URL " + update.Message.CommandArguments() + " NO URL") log.Error().Int64("chat", update.Message.Chat.ID).Int64("user", update.Message.From.ID).Str("args", update.Message.CommandArguments()).Msg("Failed to download YouTube Video. Empty args")
message := tgbotapi.EditMessageTextConfig{ message := tgbotapi.EditMessageTextConfig{
BaseEdit: tgbotapi.BaseEdit{ChatID: workingMessage.Chat.ID, MessageID: workingMessage.MessageID}, BaseEdit: tgbotapi.BaseEdit{ChatID: workingMessage.Chat.ID, MessageID: workingMessage.MessageID},
Text: "Please specify a valid YouTube URL to download something.", Text: "Please specify a valid YouTube URL.",
} }
botIO.EditMessage(message, bot) botIO.EditMessage(message, bot)
return return
@ -58,10 +60,10 @@ func Download(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
return return
} }
files, err := os.ReadDir("./videos/" + downloadTarget) files, err := os.ReadDir("data/videos/" + downloadTarget)
if err != nil { if err != nil {
log.Println("[download] Failed to process URL "+update.Message.CommandArguments(), " FAILED TO READ DIRECTORY: ", err.Error()) log.Error().Err(err).Msg("failed to download. unable to read target directory")
message := tgbotapi.EditMessageTextConfig{ message := tgbotapi.EditMessageTextConfig{
BaseEdit: tgbotapi.BaseEdit{ChatID: workingMessage.Chat.ID, MessageID: workingMessage.MessageID}, BaseEdit: tgbotapi.BaseEdit{ChatID: workingMessage.Chat.ID, MessageID: workingMessage.MessageID},
@ -72,7 +74,7 @@ func Download(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
} }
if len(files) > 1 { if len(files) > 1 {
log.Println("[download] Failed to process URL "+update.Message.CommandArguments(), " TOO MANY FILES") log.Error().Err(err).Msg("failed to download. too many files")
message := tgbotapi.EditMessageTextConfig{ message := tgbotapi.EditMessageTextConfig{
BaseEdit: tgbotapi.BaseEdit{ChatID: workingMessage.Chat.ID, MessageID: workingMessage.MessageID}, BaseEdit: tgbotapi.BaseEdit{ChatID: workingMessage.Chat.ID, MessageID: workingMessage.MessageID},
Text: "Something went wrong while downloading your media :(", Text: "Something went wrong while downloading your media :(",
@ -88,10 +90,10 @@ func Download(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
botIO.EditMessage(message, bot) botIO.EditMessage(message, bot)
serveMedia(update, bot, downloadTarget, files[0].Name()) serveMedia(update, bot, downloadTarget, files[0].Name())
log.Println("[download] Served URL " + update.Message.CommandArguments() + " for " + strconv.FormatInt(update.Message.From.ID, 10) + " in chat " + strconv.FormatInt(update.Message.Chat.ID, 10)) log.Debug().Str("URL", update.Message.CommandArguments()).Int64("user", update.Message.From.ID).Int64("chat", update.Message.Chat.ID).Msg("Served Video")
time.Sleep(5 * time.Second)
time.Sleep(10 * time.Second)
log.Info().Msg("downloaded file")
bot.Send(tgbotapi.NewDeleteMessage(workingMessage.Chat.ID, workingMessage.MessageID)) bot.Send(tgbotapi.NewDeleteMessage(workingMessage.Chat.ID, workingMessage.MessageID))
} }
@ -108,7 +110,7 @@ func randomString(n int) string {
func runYTDL(URL string, targetDir string) (success bool) { func runYTDL(URL string, targetDir string) (success bool) {
cmd := exec.Command("yt-dlp", "-f", "bv*[ext=mp4]+ba[ext=m4a] / bv*+ba/b", "--no-playlist", "-o", "videos/"+targetDir+"/"+"%(title)s.%(ext)s", "--write-thumbnail", "--convert-thumbnails", "jpg", "-o", "thumbnail:videos/"+targetDir+"thumb"+"/"+"%(title)s.%(ext)s", URL) cmd := exec.Command("yt-dlp", "-f", "bv*[ext=mp4]+ba[ext=m4a] / bv*+ba/b", "--no-playlist", "-o", "data/videos/"+targetDir+"/"+"%(title)s.%(ext)s", "--write-thumbnail", "--convert-thumbnails", "jpg", "-o", "thumbnail:data/videos/"+targetDir+"thumb"+"/"+"%(title)s.%(ext)s", URL)
out, err := cmd.CombinedOutput() out, err := cmd.CombinedOutput()
var ( var (
@ -117,19 +119,19 @@ func runYTDL(URL string, targetDir string) (success bool) {
) )
if errors.As(err, &ee) { if errors.As(err, &ee) {
log.Println("[download.ytdl] Failed to download URL "+URL, " NON ZERO EXIT CODE: ", ee.ExitCode()) log2.Println("[download.ytdl] Failed to download URL "+URL, " NON ZERO EXIT CODE: ", ee.ExitCode())
success = false success = false
} else if errors.As(err, &pe) { } else if errors.As(err, &pe) {
log.Println("[download.ytdl] Failed to download URL "+URL, " OS PATH ERROR: ", pe.Error()) log2.Println("[download.ytdl] Failed to download URL "+URL, " OS PATH ERROR: ", pe.Error())
success = false success = false
} else if err != nil { } else if err != nil {
log.Println("[download.ytdl] Failed to download URL "+URL, " GENERAL ERROR: ", err.Error()) log2.Println("[download.ytdl] Failed to download URL "+URL, " GENERAL ERROR: ", err.Error())
success = false success = false
} else { } else {
log.Println("[download.ytdl] Downloaded URL " + URL) log2.Println("[download.ytdl] Downloaded URL " + URL)
success = true success = true
} }
@ -143,8 +145,8 @@ func runYTDL(URL string, targetDir string) (success bool) {
func matchURL(URL string) (matchedURL string) { func matchURL(URL string) (matchedURL string) {
parsedURL, err := url.Parse(URL) parsedURL, err := url.Parse(URL)
if err != nil { if err != nil {
log.Fatal(err) log.Err(err).Msg("Failed to parse URL")
return ""
} }
var domainRegex = regexp.MustCompile(`(youtube\.com$)|(youtu\.be$)`) var domainRegex = regexp.MustCompile(`(youtube\.com$)|(youtu\.be$)`)
@ -159,32 +161,13 @@ func matchURL(URL string) (matchedURL string) {
} }
func shortURL(URL string) (shorturl string) {
resp, err := http.Get(config.BotConfig.Download.Yourls.APIPath + "?signature=" + config.BotConfig.Download.Yourls.Signature + "&action=shorturl&format=simple&url=" + URL)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
return string(body)
}
func serveMedia(update tgbotapi.Update, bot *tgbotapi.BotAPI, randomNoise string, file string) { func serveMedia(update tgbotapi.Update, bot *tgbotapi.BotAPI, randomNoise string, file string) {
fsPath := "./videos/" + randomNoise + "/" + file fsPath := "data/videos/" + randomNoise + "/" + file
fsThumbPath := "./videos/" + randomNoise + "thumb" + "/" + strings.TrimSuffix(file, "mp4") + "jpg" fsThumbPath := "data/videos/" + randomNoise + "thumb" + "/" + strings.TrimSuffix(file, "mp4") + "jpg"
fExt := filepath.Ext(fsPath) fExt := filepath.Ext(fsPath)
imageTypes := []string{".jpg", ".jpeg", ".png"} imageTypes := []string{".jpg", ".jpeg", ".png"}
shortURL := shortURL(url.PathEscape(config.BotConfig.Download.Prefix + "/" + randomNoise + "/" + url.PathEscape(file)))
fsPathStat, _ := os.Stat(fsPath) fsPathStat, _ := os.Stat(fsPath)
if fsPathStat.Size() >= 52428800 { if fsPathStat.Size() >= 52428800 {
@ -195,7 +178,7 @@ func serveMedia(update tgbotapi.Update, bot *tgbotapi.BotAPI, randomNoise string
vid := tgbotapi.VideoConfig{ vid := tgbotapi.VideoConfig{
BaseFile: tgbotapi.BaseFile{BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, File: tgbotapi.FilePath(fsPath)}, BaseFile: tgbotapi.BaseFile{BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, File: tgbotapi.FilePath(fsPath)},
Thumb: tgbotapi.FilePath(fsThumbPath), Thumb: tgbotapi.FilePath(fsThumbPath),
Caption: shortURL, Caption: config.BotConfig.Download.Prefix + "/" + randomNoise + "/" + url.PathEscape(file),
SupportsStreaming: true, SupportsStreaming: true,
} }
if _, err := os.Stat(fsThumbPath); err != nil { if _, err := os.Stat(fsThumbPath); err != nil {
@ -206,7 +189,7 @@ func serveMedia(update tgbotapi.Update, bot *tgbotapi.BotAPI, randomNoise string
} else if commonlogic.ContainsString(imageTypes, fExt) { } else if commonlogic.ContainsString(imageTypes, fExt) {
pic := tgbotapi.PhotoConfig{ pic := tgbotapi.PhotoConfig{
BaseFile: tgbotapi.BaseFile{BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, File: tgbotapi.FilePath(fsPath)}, BaseFile: tgbotapi.BaseFile{BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, File: tgbotapi.FilePath(fsPath)},
Caption: shortURL, Caption: config.BotConfig.Download.Prefix + "/" + randomNoise + "/" + url.PathEscape(file),
} }
botIO.SendPhoto(pic, bot) botIO.SendPhoto(pic, bot)
} else { } else {
@ -214,7 +197,7 @@ func serveMedia(update tgbotapi.Update, bot *tgbotapi.BotAPI, randomNoise string
BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},
DisableWebPagePreview: false, DisableWebPagePreview: false,
ParseMode: "html", ParseMode: "html",
Text: shortURL, Text: config.BotConfig.Download.Prefix + "/" + randomNoise + "/" + url.PathEscape(file),
} }
botIO.SendMessage(message, bot) botIO.SendMessage(message, bot)
} }

View file

@ -1,23 +1,29 @@
package gaypoints package gaypoints
import ( import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"log"
"strconv" "strconv"
"strings" "strings"
"watn3y/bloaterbotv3/botIO"
"watn3y/bloaterbotv3/commonlogic" "watn3y.de/bloaterbot/botIO"
"watn3y/bloaterbotv3/config" "watn3y.de/bloaterbot/commonlogic"
"watn3y.de/bloaterbot/config"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/rs/zerolog/log"
) )
func GetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) { func GetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
log.Trace().Int64("ChatID", update.Message.Chat.ID).Msg(("Getting Gaypoints"))
if !commonlogic.ContainsInt64(config.BotConfig.GayPoints.EnabledChats, update.Message.Chat.ID) { if !commonlogic.ContainsInt64(config.BotConfig.GayPoints.EnabledChats, update.Message.Chat.ID) {
log.Debug().Int64("chat", update.Message.Chat.ID).Ints64("enabledChats", config.BotConfig.GayPoints.EnabledChats).Msg("Not getting Gaypoints, Chat not enabled")
return return
} }
if update.Message.ReplyToMessage != nil { if update.Message.ReplyToMessage != nil {
log.Println("[gaypoints] Looking for gaypoints for user " + strconv.FormatInt(update.Message.ReplyToMessage.From.ID, 10) + " in chat " + strconv.FormatInt(update.Message.Chat.ID, 10)) log.Trace().Msg("ReplyToMessage not empty, getting Gaypoints for individual user")
points := sqlGetGP(update.Message.Chat.ID, update.Message.ReplyToMessage.From.ID) points := sqlGetGP(update.Message.Chat.ID, update.Message.ReplyToMessage.From.ID)
errorGettingUser, currentUser := botIO.GetUserByID(tgbotapi.ChatConfigWithUser{ChatID: update.Message.Chat.ID, UserID: update.Message.ReplyToMessage.From.ID}, bot) errorGettingUser, currentUser := botIO.GetUserByID(tgbotapi.ChatConfigWithUser{ChatID: update.Message.Chat.ID, UserID: update.Message.ReplyToMessage.From.ID}, bot)
@ -27,10 +33,17 @@ func GetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
if currentUser.User.UserName != "" { if currentUser.User.UserName != "" {
currentName = currentUser.User.UserName currentName = currentUser.User.UserName
} }
messagetext = `<a href="` + `tg://user?id=` + strconv.FormatInt(update.Message.ReplyToMessage.From.ID, 10) + `">` + currentName + `</a>` + ` currently has ` + `<b>` + strconv.FormatInt(points, 10) + `</b>` + ` gaypoints` + "\n" log.Debug().Int64("user", update.Message.ReplyToMessage.From.ID).Int64("chat", update.Message.Chat.ID).Int64("gp", points).Msg("got details for user")
if points == -1 {
messagetext = `<a href="` + `tg://user?id=` + strconv.FormatInt(update.Message.ReplyToMessage.From.ID, 10) + `">` + currentName + `</a>` + ` currently has no gaypoints` + "\n"
} else {
messagetext = `<a href="` + `tg://user?id=` + strconv.FormatInt(update.Message.ReplyToMessage.From.ID, 10) + `">` + currentName + `</a>` + ` currently has ` + `<b>` + strconv.FormatInt(points, 10) + `</b>` + ` gaypoints` + "\n"
}
} else { } else {
messagetext = "Something went wrong :(" log.Error().Int64("user", update.Message.ReplyToMessage.From.ID).Int64("chat", update.Message.Chat.ID).Msg("Error getting Details for User")
messagetext = "Something went wrong :( Forward me a message from the user and try again. This might fix it."
} }
message := tgbotapi.MessageConfig{ message := tgbotapi.MessageConfig{
@ -43,20 +56,22 @@ func GetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
botIO.SendMessage(message, bot) botIO.SendMessage(message, bot)
return return
} }
log.Debug().Msg("ReplyToMessage is empty, getting Gaypoints for whole chat")
log.Println("[gaypoints] Looking for gaypoints for chat " + strconv.FormatInt(update.Message.Chat.ID, 10))
gps := sqlGetAllGP(update.Message.Chat.ID) gps := sqlGetAllGP(update.Message.Chat.ID)
var messagetext string var messagetext string
for _, gaypointInfo := range gps { for _, gaypointInfo := range gps {
errorGettingUser, currentUser := botIO.GetUserByID(tgbotapi.ChatConfigWithUser{ChatID: update.Message.Chat.ID, UserID: gaypointInfo.userID}, bot) errorGettingUser, currentUser := botIO.GetUserByID(tgbotapi.ChatConfigWithUser{ChatID: update.Message.Chat.ID, UserID: gaypointInfo.userID}, bot)
if errorGettingUser { if errorGettingUser {
log.Error().Int64("user", update.Message.ReplyToMessage.From.ID).Int64("chat", update.Message.Chat.ID).Msg("Error getting Details for User")
continue continue
} }
currentName := currentUser.User.FirstName currentName := currentUser.User.FirstName
if currentUser.User.UserName != "" { if currentUser.User.UserName != "" {
currentName = currentUser.User.UserName currentName = currentUser.User.UserName
} }
text := `<a href="` + `tg://user?id=` + strconv.FormatInt(gaypointInfo.userID, 10) + `">` + currentName + `</a>` + ` currently has ` + `<b>` + strconv.FormatInt(gaypointInfo.gaypoints, 10) + `</b>` + ` gaypoints` + "\n" text := `<a href="` + `tg://user?id=` + strconv.FormatInt(gaypointInfo.userID, 10) + `">` + currentName + `</a>` + ` currently has ` + `<b>` + strconv.FormatInt(gaypointInfo.gaypoints, 10) + `</b>` + ` gaypoints` + "\n"
messagetext = messagetext + text messagetext = messagetext + text
@ -74,15 +89,19 @@ func GetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
} }
func SetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) { func SetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
log.Debug().Int64("chat", update.Message.Chat.ID).Str("text", update.Message.Text).Msg("setting gaypoints")
if !commonlogic.ContainsInt64(config.BotConfig.GayPoints.EnabledChats, update.Message.Chat.ID) { if !commonlogic.ContainsInt64(config.BotConfig.GayPoints.EnabledChats, update.Message.Chat.ID) {
log.Debug().Int64("chat", update.Message.Chat.ID).Ints64("enabledChats", config.BotConfig.GayPoints.EnabledChats).Msg("not setting gaypoints, chat not enabled")
return return
} }
if !commonlogic.ContainsInt64(config.BotConfig.GayPoints.ModifyUsers, update.Message.From.ID) { if !commonlogic.ContainsInt64(config.BotConfig.GayPoints.ModifyUsers, update.Message.From.ID) {
log.Debug().Int64("chat", update.Message.Chat.ID).Ints64("enabledChats", config.BotConfig.GayPoints.ModifyUsers).Msg("not setting gaypoints, user not authorised")
sticker := tgbotapi.StickerConfig{BaseFile: tgbotapi.BaseFile{ sticker := tgbotapi.StickerConfig{BaseFile: tgbotapi.BaseFile{
BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},
File: tgbotapi.FilePath("bloater.webp"), File: tgbotapi.FilePath("data/bloater.webp"),
}} }}
botIO.SendSticker(sticker, bot) botIO.SendSticker(sticker, bot)
return return
@ -98,41 +117,41 @@ func SetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
} else { } else {
arg = "" arg = ""
} }
log.Println("[gaypoints] Trying to modify gaypoints for user " + strconv.FormatInt(update.Message.ReplyToMessage.From.ID, 10) + " in chat " + strconv.FormatInt(update.Message.Chat.ID, 10))
if update.Message.ReplyToMessage == nil { if update.Message.ReplyToMessage == nil {
log.Error().Int64("chat", update.Message.Chat.ID).Msg("failed to set gaypoints for user, ReplyToMessage not present")
message := tgbotapi.MessageConfig{ message := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},
ParseMode: "html", ParseMode: "html",
DisableWebPagePreview: false, DisableWebPagePreview: false,
Text: "Please reply to a message to set gaypoints", Text: "Please reply to a message to set gaypoints",
} }
log.Println("[gaypoints] Failed to set gaypoints for user " + strconv.FormatInt(update.Message.ReplyToMessage.From.ID, 10) + " in chat " + strconv.FormatInt(update.Message.Chat.ID, 10))
botIO.SendMessage(message, bot) botIO.SendMessage(message, bot)
return return
} }
if arg == "" { if arg == "" {
log.Error().Int64("chat", update.Message.Chat.ID).Msg("failed to set gaypoints for user, empty value")
message := tgbotapi.MessageConfig{ message := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},
ParseMode: "html", ParseMode: "html",
DisableWebPagePreview: false, DisableWebPagePreview: false,
Text: "Please specify a valid gaypoint value", Text: "Please specify a valid gaypoint value. Your current value seems to be empty.",
} }
log.Println("[gaypoints] Failed to set gaypoints for user " + strconv.FormatInt(update.Message.ReplyToMessage.From.ID, 10) + " in chat " + strconv.FormatInt(update.Message.Chat.ID, 10))
botIO.SendMessage(message, bot) botIO.SendMessage(message, bot)
return return
} }
newPoints, err := strconv.ParseInt(arg, 10, 64) newPoints, err := strconv.ParseInt(arg, 10, 64)
if err != nil || newPoints <= 0 { if err != nil || newPoints <= 0 {
log.Error().Int64("chat", update.Message.Chat.ID).Msg("failed to set gaypoints for user, invalid value or value <= 0")
message := tgbotapi.MessageConfig{ message := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},
ParseMode: "html", ParseMode: "html",
DisableWebPagePreview: false, DisableWebPagePreview: false,
Text: "Please specify a valid gaypoint value", Text: "Please specify a valid gaypoint value. Your current value was either too low or I was not able to parse it correctly.",
} }
log.Println("[gaypoints] Failed to set gaypoints for user " + strconv.FormatInt(update.Message.ReplyToMessage.From.ID, 10) + " in chat " + strconv.FormatInt(update.Message.Chat.ID, 10))
botIO.SendMessage(message, bot) botIO.SendMessage(message, bot)
return return
} }
@ -142,7 +161,7 @@ func SetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
if cmd == "addgp" { if cmd == "addgp" {
currentPoints = sqlGetGP(update.Message.Chat.ID, update.Message.ReplyToMessage.From.ID) currentPoints = sqlGetGP(update.Message.Chat.ID, update.Message.ReplyToMessage.From.ID)
if currentPoints <= -1 { if currentPoints <= 0 {
finalgp = newPoints finalgp = newPoints
} else { } else {
finalgp = currentPoints + newPoints finalgp = currentPoints + newPoints
@ -150,15 +169,15 @@ func SetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
} }
if cmd == "subtractgp" { if cmd == "subtractgp" {
log.Error().Int64("chat", update.Message.Chat.ID).Msg("failed to set gaypoints for user, new value is < 0")
currentPoints = sqlGetGP(update.Message.Chat.ID, update.Message.ReplyToMessage.From.ID) currentPoints = sqlGetGP(update.Message.Chat.ID, update.Message.ReplyToMessage.From.ID)
if currentPoints <= 0 { if currentPoints-newPoints < 0 {
message := tgbotapi.MessageConfig{ message := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},
ParseMode: "html",
DisableWebPagePreview: false, DisableWebPagePreview: false,
Text: "Please specify a valid gaypoint value", Text: "Please specify a valid gaypoint value. After subtracting your current value from the users current gaypoints, they would have < 0 gaypoints. This is not allowed.",
} }
log.Println("[gaypoints] Failed to subtrackt gaypoints for user " + strconv.FormatInt(update.Message.ReplyToMessage.From.ID, 10) + " in chat " + strconv.FormatInt(update.Message.Chat.ID, 10))
botIO.SendMessage(message, bot) botIO.SendMessage(message, bot)
return return
} else { } else {
@ -174,11 +193,11 @@ func SetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
if currentUser.User.UserName != "" { if currentUser.User.UserName != "" {
currentName = currentUser.User.UserName currentName = currentUser.User.UserName
} }
log.Debug().Int64("user", update.Message.ReplyToMessage.From.ID).Int64("chat", update.Message.Chat.ID).Msg("got details for user")
messagetext = `<a href="` + `tg://user?id=` + strconv.FormatInt(update.Message.ReplyToMessage.From.ID, 10) + `">` + currentName + `</a>` + ` now has ` + `<b>` + strconv.FormatInt(finalgp, 10) + `</b>` + ` gaypoints` + "\n" messagetext = `<a href="` + `tg://user?id=` + strconv.FormatInt(update.Message.ReplyToMessage.From.ID, 10) + `">` + currentName + `</a>` + ` now has ` + `<b>` + strconv.FormatInt(finalgp, 10) + `</b>` + ` gaypoints` + "\n"
} else { } else {
messagetext = "Something went wrong :(" log.Error().Int64("user", update.Message.ReplyToMessage.From.ID).Int64("chat", update.Message.Chat.ID).Msg("error getting details for user")
log.Println("[gaypoints] Failed to change gaypoints " + strconv.FormatInt(update.Message.ReplyToMessage.From.ID, 10) + " in chat " + strconv.FormatInt(update.Message.Chat.ID, 10) + " from " + strconv.FormatInt(currentPoints, 10) + " to " + strconv.FormatInt(finalgp, 10)) messagetext = "Something went wrong :( Forward me a message from the user and try again. This might fix it."
return return
} }
@ -189,7 +208,7 @@ func SetGP(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
Text: messagetext, Text: messagetext,
} }
log.Println("[gaypoints] Changing gaypoints " + strconv.FormatInt(update.Message.ReplyToMessage.From.ID, 10) + " in chat " + strconv.FormatInt(update.Message.Chat.ID, 10) + " from " + strconv.FormatInt(currentPoints, 10) + " to " + strconv.FormatInt(finalgp, 10)) log.Info().Int64("oldGP", currentPoints).Int64("newGP", finalgp).Int64("user", update.Message.ReplyToMessage.From.ID).Int64("chat", update.Message.Chat.ID).Int64("changedBy", update.Message.From.ID).Msg("Set Gaypoints")
sqlSetGP(update.Message.Chat.ID, update.Message.ReplyToMessage.From.ID, finalgp) sqlSetGP(update.Message.Chat.ID, update.Message.ReplyToMessage.From.ID, finalgp)
botIO.SendMessage(message, bot) botIO.SendMessage(message, bot)

View file

@ -2,9 +2,8 @@ package gaypoints
import ( import (
"database/sql" "database/sql"
_ "github.com/mattn/go-sqlite3" "github.com/rs/zerolog/log"
"log" _ "modernc.org/sqlite"
"strconv"
) )
var gpSelectUser *sql.Stmt var gpSelectUser *sql.Stmt
@ -16,7 +15,8 @@ var gpSet *sql.Stmt
func sqlGetAllGP(chatid int64) (gaypoints []gaypointShortDetails) { func sqlGetAllGP(chatid int64) (gaypoints []gaypointShortDetails) {
rows, err := gpSelectChat.Query(chatid) rows, err := gpSelectChat.Query(chatid)
if err != nil { if err != nil {
log.Panicf("Failed to query gaypoints: %v\n", err) log.Error().Err(err).Msg("Failed to execute SQL Query. Can't get gaypoints for chat")
return
} }
var c int64 var c int64
@ -29,10 +29,12 @@ func sqlGetAllGP(chatid int64) (gaypoints []gaypointShortDetails) {
gaypoints: b, gaypoints: b,
}) })
default: default:
log.Panicf("Failed to query gaypoints: %v\n", err) log.Error().Err(err).Msg("Failed to parse SQL Result. Can't get gaypoints for chat")
return
} }
log.Println("[gaypoints.sql] Got gaypoints for " + strconv.FormatInt(c, 10) + " in chat " + strconv.FormatInt(chatid, 10) + ". Value is " + strconv.FormatInt(b, 10))
log.Trace().Int64("ChatID", chatid).Interface("GP", gaypoints).Msg(("SQL: got SQL for Chat"))
} }
return gaypoints return gaypoints
@ -48,50 +50,52 @@ func sqlGetGP(chatid int64, userid int64) (gaypoints int64) {
case nil: case nil:
break break
default: default:
log.Panicf("Failed to query gaypoints: %v\n", err) log.Error().Err(err).Msg("Failed to execute SQL Query. Can't get gaypoints for User")
return
} }
log.Println("[gaypoints.sql] Got gaypoints for " + strconv.FormatInt(userid, 10) + " in chat " + strconv.FormatInt(chatid, 10) + ". Value is " + strconv.FormatInt(gaypoints, 10)) log.Trace().Int64("ChatID", chatid).Int64("UserID", userid).Interface("GP", gaypoints).Msg(("SQL: got SQL for User"))
return gaypoints return gaypoints
} }
func sqlSetGP(chatid int64, userid int64, gaypoints int64) { func sqlSetGP(chatid int64, userid int64, gaypoints int64) {
_, err := gpSet.Exec(chatid, userid, gaypoints) _, err := gpSet.Exec(chatid, userid, gaypoints)
if err != nil { if err != nil {
log.Panicf("Failed to set gaypoints: %v\n", err) log.Error().Err(err).Msg("Failed to execute SQL Query. Can't set gaypoints for User")
return
} }
log.Println("[gaypoints.sql] Set gaypoints for " + strconv.FormatInt(userid, 10) + " in chat " + strconv.FormatInt(chatid, 10) + " to " + strconv.FormatInt(gaypoints, 10)) log.Info().Int64("ChatID", chatid).Int64("UserID", userid).Interface("GP", gaypoints).Msg(("SQL: set SQL for User"))
} }
func InitDB() { func InitDB() {
const dbPath string = "./bloater.db" const dbPath string = "data/db/gaypoints.db"
db, err := sql.Open("sqlite3", dbPath) db, err := sql.Open("sqlite", dbPath)
if err != nil { if err != nil {
log.Panicf("Failed to open sqlite database: %v\n", err) log.Panic().Err(err).Msg("failed to open sqlite database")
} }
_, err = db.Exec("CREATE TABLE IF NOT EXISTS gaypoints (chatid bigint, userid bigint,gaypoints bigint,UNIQUE(chatid,userid))") _, err = db.Exec("CREATE TABLE IF NOT EXISTS gaypoints (chatid bigint, userid bigint,gaypoints bigint,UNIQUE(chatid,userid))")
if err != nil { if err != nil {
log.Panicf("Failed to create table: %v\n", err) log.Panic().Err(err).Msg("failed to create table")
} }
log.Println("[gaypoints.sql] Created sqlite table in database at " + dbPath)
gpSelectUser, err = db.Prepare("SELECT gaypoints FROM gaypoints WHERE chatid = ? AND userid = ?") gpSelectUser, err = db.Prepare("SELECT gaypoints FROM gaypoints WHERE chatid = ? AND userid = ?")
if err != nil { if err != nil {
log.Panicf("Failed to prepare sql select: %v\n", err) log.Panic().Err(err).Msg("failed to create sql statement")
} }
gpSelectChat, err = db.Prepare("SELECT userid,gaypoints FROM gaypoints WHERE chatid = ? ORDER BY gaypoints DESC") gpSelectChat, err = db.Prepare("SELECT userid,gaypoints FROM gaypoints WHERE chatid = ? ORDER BY gaypoints DESC")
if err != nil { if err != nil {
log.Panicf("Failed to prepare sql select: %v\n", err) log.Panic().Err(err).Msg("failed to create sql statement")
} }
gpSet, err = db.Prepare("INSERT OR REPLACE INTO gaypoints (chatid, userid, gaypoints) values (?,?,?)") gpSet, err = db.Prepare("INSERT OR REPLACE INTO gaypoints (chatid, userid, gaypoints) values (?,?,?)")
if err != nil { if err != nil {
log.Panicf("Failed to prepare sql insert: %v\n", err) log.Panic().Err(err).Msg("failed to create sql statement")
} }
log.Info().Str("dbpath", dbPath).Msg("Database prepared and connected")
} }

View file

@ -1,16 +1,21 @@
package notify package notify
import ( import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"log"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"watn3y/bloaterbotv3/botIO"
"watn3y.de/bloaterbot/botIO"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/rs/zerolog/log"
) )
func Reminder(update tgbotapi.Update, bot *tgbotapi.BotAPI) { func Reminder(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
log.Trace().Str("args", update.Message.CommandArguments()).Msg(("Parsing new Reminder"))
commandArgs := strings.Fields(update.Message.CommandArguments()) commandArgs := strings.Fields(update.Message.CommandArguments())
var timeArg string var timeArg string
@ -20,6 +25,9 @@ func Reminder(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
timeArg = strings.ToLower(commandArgs[0]) timeArg = strings.ToLower(commandArgs[0])
textArg = strings.Replace(update.Message.CommandArguments(), timeArg, "", 1) textArg = strings.Replace(update.Message.CommandArguments(), timeArg, "", 1)
} else { } else {
log.Error().Str("CommandArgs", update.Message.CommandArguments()).Msg("Failed to add Reminder. Unable to parse reminder")
message := tgbotapi.MessageConfig{ message := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},
ParseMode: "html", ParseMode: "html",
@ -30,11 +38,12 @@ func Reminder(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
return return
} }
log.Println("[notify] Attempting to set reminder for user " + strconv.FormatInt(update.Message.From.ID, 10) + " in chat " + strconv.FormatInt(update.Message.Chat.ID, 10) + " with arguments " + timeArg)
isValidFormat := regexp.MustCompile(`(?m)^\d{1,3}[mhd]$`) isValidFormat := regexp.MustCompile(`(?m)^\d{1,3}[mhd]$`)
if !isValidFormat.MatchString(timeArg) { if !isValidFormat.MatchString(timeArg) {
log.Error().Str("CommandArgs", update.Message.CommandArguments()).Msg("Failed to add Reminder. Unable to parse reminder")
message := tgbotapi.MessageConfig{ message := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},
ParseMode: "html", ParseMode: "html",
@ -64,9 +73,7 @@ func Reminder(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
notifyTime := time.Now().UTC().Add(time.Duration(number) * modifyTime) notifyTime := time.Now().UTC().Add(time.Duration(number) * modifyTime)
var reminder reminderConfig reminder := reminderConfig{
reminder = reminderConfig{
updateID: update.UpdateID, updateID: update.UpdateID,
notifyTime: notifyTime.Unix(), notifyTime: notifyTime.Unix(),
chatID: update.Message.Chat.ID, chatID: update.Message.Chat.ID,
@ -84,29 +91,33 @@ func Reminder(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
Text: "Set reminder for " + notifyTime.Format("02.01.2006") + " at " + notifyTime.Format("15:04") + " UTC ", Text: "Set reminder for " + notifyTime.Format("02.01.2006") + " at " + notifyTime.Format("15:04") + " UTC ",
} }
botIO.SendMessage(message, bot) botIO.SendMessage(message, bot)
log.Info().Int("ID", reminder.updateID).Int64("chat", reminder.chatID).Int64("user", reminder.userID).Int64("time", reminder.notifyTime).Msg("Added new Reminder")
return return
} }
func NotifyHandler(bot *tgbotapi.BotAPI) { func NotifyHandler(bot *tgbotapi.BotAPI) {
log.Info().Msg("Handling Reminders")
for { for {
reminders := sqlGetReminders() reminders := sqlGetReminders()
for updateID, reminderTime := range reminders { for updateID, reminderTime := range reminders {
if reminderTime <= time.Now().UTC().Unix() { if reminderTime <= time.Now().UTC().Unix() {
log.Info().Int("ID", updateID).Msg("reminder is due")
details := sqlGetReminderDetails(updateID) details := sqlGetReminderDetails(updateID)
message := tgbotapi.MessageConfig{ message := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{ChatID: details.chatID, ReplyToMessageID: details.messageToReplyToID}, BaseChat: tgbotapi.BaseChat{ChatID: details.chatID, ReplyToMessageID: details.messageToReplyToID},
ParseMode: "html", ParseMode: "html",
DisableWebPagePreview: false, DisableWebPagePreview: false,
Text: "Reminder: " + details.reminderText,
Text: details.reminderText,
} }
botIO.SendMessage(message, bot) botIO.SendMessage(message, bot)
sqlDeleteReminder(updateID) sqlDeleteReminder(updateID)
log.Info().Int64("chat", details.chatID).Int64("user", details.userID).Str("text", details.reminderText).Msg("Sent Reminder")
} }
} }

View file

@ -2,8 +2,8 @@ package notify
import ( import (
"database/sql" "database/sql"
"log" "github.com/rs/zerolog/log"
"strconv" _ "modernc.org/sqlite"
) )
var notifySetReminder *sql.Stmt var notifySetReminder *sql.Stmt
@ -12,62 +12,68 @@ var notifyGetReminderDetails *sql.Stmt
var notifyDeleteReminder *sql.Stmt var notifyDeleteReminder *sql.Stmt
func InitDB() { func InitDB() {
const dbPath string = "./bloater.db" const dbPath string = "data/db/notify.db"
db, err := sql.Open("sqlite3", dbPath) db, err := sql.Open("sqlite", dbPath)
if err != nil { if err != nil {
log.Panicf("Failed to open sqlite database: %v\n", err) log.Panic().Err(err).Msg("failed to open sqlite database")
} }
_, err = db.Exec("CREATE TABLE IF NOT EXISTS notify (updateID INTEGER,notifyTime INTEGER,chatID INTEGER, userID INTEGER,messageToReplyToID INTEGER,notifyText TEXT)") _, err = db.Exec("CREATE TABLE IF NOT EXISTS notify (updateID INTEGER,notifyTime INTEGER,chatID INTEGER, userID INTEGER,messageToReplyToID INTEGER,notifyText TEXT)")
if err != nil { if err != nil {
log.Panicf("Failed to create table: %v\n", err) log.Panic().Err(err).Msg("failed to create table")
} }
log.Println("[notify.sql] Created sqlite table in database at " + dbPath)
notifySetReminder, err = db.Prepare("INSERT OR REPLACE INTO notify (updateID,notifyTime,chatID, userID,messageToReplyToID,notifyText) values (?,?,?,?,?,?)") notifySetReminder, err = db.Prepare("INSERT OR REPLACE INTO notify (updateID,notifyTime,chatID, userID,messageToReplyToID,notifyText) values (?,?,?,?,?,?)")
if err != nil { if err != nil {
log.Panicf("Failed to prepare sql insert: %v\n", err) log.Panic().Err(err).Msg("failed to create sql statement")
} }
notifyGetReminders, err = db.Prepare("SELECT updateID,notifyTime FROM notify") notifyGetReminders, err = db.Prepare("SELECT updateID,notifyTime FROM notify")
if err != nil { if err != nil {
log.Panicf("Failed to prepare sql select: %v\n", err) log.Panic().Err(err).Msg("failed to create sql statement")
} }
notifyGetReminderDetails, err = db.Prepare("SELECT chatID, userID,messageToReplyToID,notifyText FROM notify WHERE updateID=?") notifyGetReminderDetails, err = db.Prepare("SELECT chatID, userID,messageToReplyToID,notifyText FROM notify WHERE updateID=?")
if err != nil { if err != nil {
log.Panicf("Failed to prepare sql select: %v\n", err) log.Panic().Err(err).Msg("failed to create sql statement")
} }
notifyDeleteReminder, err = db.Prepare("DELETE FROM notify WHERE updateID=?") notifyDeleteReminder, err = db.Prepare("DELETE FROM notify WHERE updateID=?")
if err != nil { if err != nil {
log.Panicf("Failed to prepare sql select: %v\n", err) log.Panic().Err(err).Msg("failed to create sql statement")
} }
log.Info().Str("dbpath", dbPath).Msg("Database prepared and connected")
} }
func sqlDeleteReminder(updateID int) { func sqlDeleteReminder(updateID int) {
_, err := notifyDeleteReminder.Exec(updateID) _, err := notifyDeleteReminder.Exec(updateID)
if err != nil { if err != nil {
log.Panicf("Failed to delete reminder: %v\n", err) log.Error().Err(err).Msg("Failed to execute SQL Query. Can't delete Reminder")
return
} }
log.Trace().Int("ID", updateID).Msg(("SQL: deleted reminder"))
} }
func sqlAddReminder(reminder reminderConfig) { func sqlAddReminder(reminder reminderConfig) {
_, err := notifySetReminder.Exec(reminder.updateID, reminder.notifyTime, reminder.chatID, reminder.userID, reminder.messageToReplyToID, reminder.reminderText) _, err := notifySetReminder.Exec(reminder.updateID, reminder.notifyTime, reminder.chatID, reminder.userID, reminder.messageToReplyToID, reminder.reminderText)
if err != nil { if err != nil {
log.Panicf("Failed to set add reminder: %v\n", err) log.Error().Err(err).Msg("Failed to execute SQL Query. Can't add Reminder")
return
} }
log.Println("[notify.sql] Set new reminder for " + strconv.FormatInt(reminder.userID, 10) + " in chat " + strconv.FormatInt(reminder.chatID, 10)) log.Trace().Interface("Reminder", reminder).Msg(("SQL: added Reminder"))
} }
func sqlGetReminders() (reminders map[int]int64) { func sqlGetReminders() (reminders map[int]int64) {
rows, err := notifyGetReminders.Query() rows, err := notifyGetReminders.Query()
if err != nil { if err != nil {
log.Panicf("Failed to query reminders: %v\n", err) log.Error().Err(err).Msg("Failed to execute SQL Query. Can't get Reminders")
return
} }
reminders = make(map[int]int64) reminders = make(map[int]int64)
@ -78,11 +84,13 @@ func sqlGetReminders() (reminders map[int]int64) {
case nil: case nil:
reminders[c] = b reminders[c] = b
default: default:
log.Panicf("Failed to query gaypoints: %v\n", err) log.Error().Err(err).Msg("Failed to parse SQL Result. Can't get Reminders")
return
} }
} }
log.Trace().Interface("Reminders", reminders).Msg(("SQL: got Reminders"))
return reminders return reminders
} }
@ -93,9 +101,10 @@ func sqlGetReminderDetails(updateID int) (reminder reminderConfig) {
case nil: case nil:
break break
default: default:
log.Panicf("Failed to get reminder details: %v\n", err) log.Error().Err(err).Msg("Failed to execute SQL Query. Can't get Reminder Details")
return
} }
log.Println("[notify.sql] Got reminder details for update ID" + string(rune(updateID))) log.Trace().Interface("Reminder", reminder).Msg(("SQL: got Reminder Details"))
return reminder return reminder
} }

View file

@ -1,5 +1,10 @@
package commonlogic package commonlogic
import (
"github.com/rs/zerolog/log"
"os"
)
func ContainsInt64(a []int64, b int64) bool { func ContainsInt64(a []int64, b int64) bool {
for _, v := range a { for _, v := range a {
if v == b { if v == b {
@ -19,3 +24,12 @@ func ContainsString(a []string, b string) bool {
return false return false
} }
func GetFileSize(path string) (size int64) {
file, err := os.Stat(path)
if err != nil {
log.Error().Err(err).Msg("Failed to stat " + path)
return 0
}
return file.Size()
}

View file

@ -1,25 +0,0 @@
APIToken = "073fv3b07tvrudgbdf"
DebugMode = true
PrivilegedUsers = [1212121212]
[Nhentai]
APIEndpoint = "0.0.0.0"
Domain = "https://nhentai.net"
EnabledChats = [-00000,-111111,-22222]
[Balonlyl]
EnabledChats = [-1001462089309]
BalonlylAT = "@Balonlyl"
TriggerWords = ["french","france","baguette","casque bleu"]
[GayPoints]
EnabledChats = [-00000,-111111,-22222]
ModifyUsers = [-00000,-111111,-22222]
[Download]
Prefix = "http://192.168.0.10:3556"
[Download.Yourls]
APIPath = "https://yourl.tld/yourls-api.php"
Signature = "u8zibfd876sfvb"

View file

@ -2,53 +2,81 @@ package config
import ( import (
"github.com/BurntSushi/toml" "github.com/BurntSushi/toml"
"log" "github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"os" "os"
"time" "time"
) )
type config struct {
APIToken string
DebugMode bool
PrivilegedUsers []int64
Shutup map[int64]time.Time
Nhentai struct {
EnabledChats []int64
APIEndpoint string
Domain string
}
Balonlyl struct {
EnabledChats []int64
BalonlylAT string
TriggerWords []string
}
GayPoints struct {
EnabledChats []int64
ModifyUsers []int64
}
Download struct {
Prefix string
Yourls struct {
APIPath string
Signature string
}
}
}
var BotConfig config var BotConfig config
func LoadConfig() { func LoadConfig() {
configFile, err := os.ReadFile("config.toml")
configFile, err := os.ReadFile("data/config.toml")
if err != nil { if err != nil {
log.Fatal(err) log.Panic().Err(err).Msg("error opening data/config.toml")
} }
_, err = toml.Decode(string(configFile), &BotConfig) _, err = toml.Decode(string(configFile), &BotConfig)
if err != nil { if err != nil {
log.Fatal(err) log.Panic().Err(err).Msg("error decoding data/config.toml")
} }
BotConfig.Shutup = make(map[int64]time.Time) BotConfig.Shutup = make(map[int64]time.Time)
log.Printf("[config] Config loaded as: %+v\n", BotConfig) if !BotConfig.DebugMode {
zerolog.SetGlobalLevel(zerolog.InfoLevel)
}
log.Info().Msg("Loaded config")
log.Trace().Interface("config", BotConfig).Msg("")
}
func EncodeToml() {
exampleConfig := config{
APIToken: "1234567:h8Y7ma7hMG93kxDx5o",
DebugMode: false,
PrivilegedUsers: []int64{1234567, 9764382423},
Webserver: struct{ Port string }{
Port: "3000",
},
Balonlyl: struct {
EnabledChats []int64
BalonlylAT string
TriggerWords []string
}{
EnabledChats: []int64{353454534, 8743658},
BalonlylAT: "@Balonlyl",
TriggerWords: []string{"French, France"},
},
GayPoints: struct {
EnabledChats []int64
ModifyUsers []int64
}{
EnabledChats: []int64{353454534, 8743658},
ModifyUsers: []int64{3827468324, 1736576},
},
Download: struct {
Prefix string
}{
Prefix: "https://bloater.example.com",
},
}
f, err := os.Create("data/config.toml.example")
if err != nil {
log.Panic().Err(err).Msg("Error encoding Config File. Cannot open data/config.toml.example")
}
if err := toml.NewEncoder(f).Encode(exampleConfig); err != nil {
log.Panic().Err(err).Msg("Error encoding Config File")
}
if err := f.Close(); err != nil {
log.Panic().Err(err).Msg("Error encoding Config File. Cannot close data/config.toml.example")
}
log.Info().Msg("Writing example config to data/config.toml.example. Bye Bye")
} }

25
config/types.go Normal file
View file

@ -0,0 +1,25 @@
package config
import "time"
type config struct {
APIToken string
DebugMode bool
PrivilegedUsers []int64
Shutup map[int64]time.Time //! is always filled at startup, not present in config
Webserver struct {
Port string
}
Balonlyl struct {
EnabledChats []int64
BalonlylAT string
TriggerWords []string
}
GayPoints struct {
EnabledChats []int64
ModifyUsers []int64
}
Download struct {
Prefix string
}
}

BIN
data/204.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

View file

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

18
data/config.toml.example Normal file
View file

@ -0,0 +1,18 @@
APIToken = "1234567:h8Y7ma7hMG93kxDx5o"
DebugMode = false
PrivilegedUsers = [1234567, 9764382423]
[Webserver]
Port = "3000"
[Balonlyl]
EnabledChats = [353454534, 8743658]
BalonlylAT = "@Balonlyl"
TriggerWords = ["French, France"]
[GayPoints]
EnabledChats = [353454534, 8743658]
ModifyUsers = [3827468324, 1736576]
[Download]
Prefix = "https://bloater.example.com"

View file

0
data/videos/placeholder Normal file
View file

View file

@ -1,12 +1,10 @@
version: '3.5'
services: services:
nenefootbot: bloaterbot:
image: bloaterbot:latest image: bloaterbot:latest
container_name: bloaterbot container_name: bloaterbot
restart: unless-stopped restart: unless-stopped
volumes: volumes:
- /opt/bloaterbot/config.toml:/app/config.toml - /opt/bloaterbot/data:/app/data
- /opt/bloaterbot/bloater.db:/app/bloater.db
networks: networks:
- expose - expose
networks: networks:

13
entrypoint.sh Normal file
View file

@ -0,0 +1,13 @@
#!/usr/bin/env ash
#update yt-dlp as there are breaking changes often
pip3 install --upgrade yt-dlp
if $? == 0; then
clear
echo Updated yt-dlp
else
echo ERROR updating yt-dlp
fi
/app/bloaterbot

31
go.mod
View file

@ -1,9 +1,32 @@
module watn3y/bloaterbotv3 module watn3y.de/bloaterbot
go 1.20 go 1.21
require ( require (
github.com/BurntSushi/toml v1.2.1 github.com/BurntSushi/toml v1.3.2
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1
github.com/mattn/go-sqlite3 v1.14.16 github.com/rs/zerolog v1.31.0
modernc.org/sqlite v1.28.0
)
require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/uuid v1.5.0 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/mod v0.14.0 // indirect
golang.org/x/sys v0.15.0 // indirect
golang.org/x/tools v0.16.1 // indirect
lukechampine.com/uint128 v1.3.0 // indirect
modernc.org/cc/v3 v3.41.0 // indirect
modernc.org/ccgo/v3 v3.16.15 // indirect
modernc.org/libc v1.38.0 // indirect
modernc.org/mathutil v1.6.0 // indirect
modernc.org/memory v1.7.2 // indirect
modernc.org/opt v0.1.3 // indirect
modernc.org/strutil v1.2.0 // indirect
modernc.org/token v1.1.0 // indirect
) )

69
go.sum
View file

@ -1,6 +1,71 @@
github.com/BurntSushi/toml v1.2.1 h1:9F2/+DoOYIOksmaJFPw1tGFy1eDnIJXg+UHjuD8lTak= github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8=
github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc= github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc=
github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8= github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y= github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.31.0 h1:FcTR3NnLWW+NnTwwhFWiJSZr4ECLpqCm6QsEnyvbV4A=
github.com/rs/zerolog v1.31.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0=
golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/tools v0.16.1 h1:TLyB3WofjdOEepBHAU20JdNC1Zbg87elYofWYAY5oZA=
golang.org/x/tools v0.16.1/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0=
lukechampine.com/uint128 v1.3.0 h1:cDdUVfRwDUDovz610ABgFD17nXD4/uDgVHl2sC3+sbo=
lukechampine.com/uint128 v1.3.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk=
modernc.org/cc/v3 v3.41.0 h1:QoR1Sn3YWlmA1T4vLaKZfawdVtSiGx8H+cEojbC7v1Q=
modernc.org/cc/v3 v3.41.0/go.mod h1:Ni4zjJYJ04CDOhG7dn640WGfwBzfE0ecX8TyMB0Fv0Y=
modernc.org/ccgo/v3 v3.16.15 h1:KbDR3ZAVU+wiLyMESPtbtE/Add4elztFyfsWoNTgxS0=
modernc.org/ccgo/v3 v3.16.15/go.mod h1:yT7B+/E2m43tmMOT51GMoM98/MtHIcQQSleGnddkUNI=
modernc.org/ccorpus v1.11.6 h1:J16RXiiqiCgua6+ZvQot4yUuUy8zxgqbqEEUuGPlISk=
modernc.org/ccorpus v1.11.6/go.mod h1:2gEUTrWqdpH2pXsmTM1ZkjeSrUWDpjMu2T6m29L/ErQ=
modernc.org/httpfs v1.0.6 h1:AAgIpFZRXuYnkjftxTAZwMIiwEqAfk8aVB2/oA6nAeM=
modernc.org/httpfs v1.0.6/go.mod h1:7dosgurJGp0sPaRanU53W4xZYKh14wfzX420oZADeHM=
modernc.org/libc v1.38.0 h1:o4Lpk0zNDSdsjfEXnF1FGXWQ9PDi1NOdWcLP5n13FGo=
modernc.org/libc v1.38.0/go.mod h1:YAXkAZ8ktnkCKaN9sw/UDeUVkGYJ/YquGO4FTi5nmHE=
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
modernc.org/memory v1.7.2 h1:Klh90S215mmH8c9gO98QxQFsY+W451E8AnzjoE2ee1E=
modernc.org/memory v1.7.2/go.mod h1:NO4NVCQy0N7ln+T9ngWqOQfi7ley4vpwvARR+Hjw95E=
modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
modernc.org/sqlite v1.28.0 h1:Zx+LyDDmXczNnEQdvPuEfcFVA2ZPyaD7UCZDjef3BHQ=
modernc.org/sqlite v1.28.0/go.mod h1:Qxpazz0zH8Z1xCFyi5GSL3FzbtZ3fvbjmywNogldEW0=
modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=
modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=
modernc.org/tcl v1.15.2 h1:C4ybAYCGJw968e+Me18oW55kD/FexcHbqH2xak1ROSY=
modernc.org/tcl v1.15.2/go.mod h1:3+k/ZaEbKrC8ePv8zJWPtBSW0V7Gg9g8rkmhI1Kfs3c=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
modernc.org/z v1.7.3 h1:zDJf6iHjrnB+WRD88stbXokugjyc0/pB91ri1gO6LZY=
modernc.org/z v1.7.3/go.mod h1:Ipv4tsdxZRbQyLq9Q1M6gdbkxYzdlrciF2Hi/lS7nWE=

View file

@ -0,0 +1,29 @@
package nenefoot
import (
//"watn3y.de/bloaterbot/botIO"
//"watn3y.de/bloaterbot/config"
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
//"github.com/rs/zerolog/log"
)
func Nenefoot(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
msg3 := tgbotapi.NewInlineQueryResultVideo("hihi", "https://bloater.watn3y.de/5r5NJELyDKYSdPsX6fzK/7000%20Dollars%20for%20this%20car%2C%20but%20i%20got%20a%20slight%20dent.mp4")
msg3.MimeType = "video/mp4"
msg3.Title = "Rat Pencilcase"
msg3.ThumbURL = "https://i.imgur.com/XjCWMco.jpeg"
inline := tgbotapi.InlineConfig{
InlineQueryID: update.InlineQuery.ID,
Results: []interface{}{msg3},
CacheTime: 0,
}
if _, err := bot.Request(inline); err != nil {
fmt.Println(err)
}
}

47
inline/nenefoot/sql.go Normal file
View file

@ -0,0 +1,47 @@
package nenefoot
import (
"database/sql"
"github.com/rs/zerolog/log"
_ "modernc.org/sqlite"
)
var gpSelectUser *sql.Stmt
var gpSelectChat *sql.Stmt
var gpSet *sql.Stmt
func InitDB() {
const dbPath string = "data/db/nenefoot.db"
log.Info().Str("dbpath", dbPath).Msg("init database")
db, err := sql.Open("sqlite", dbPath)
if err != nil {
log.Panic().Err(err).Msg("failed to open sqlite database")
}
_, err = db.Exec("CREATE TABLE IF NOT EXISTS nenefoot (title string, type string, ID string, URL string, UNIQUE(title), UNIQUE(ID), UNIQUE(URL))")
if err != nil {
log.Panic().Err(err).Msg("failed to create table")
}
gpSelectUser, err = db.Prepare("SELECT gaypoints FROM gaypoints WHERE chatid = ? AND userid = ?")
if err != nil {
log.Panic().Err(err).Msg("failed to create sql statement")
}
gpSelectChat, err = db.Prepare("SELECT userid,gaypoints FROM gaypoints WHERE chatid = ? ORDER BY gaypoints DESC")
if err != nil {
log.Panic().Err(err).Msg("failed to create sql statement")
}
gpSet, err = db.Prepare("INSERT OR REPLACE INTO gaypoints (chatid, userid, gaypoints) values (?,?,?)")
if err != nil {
log.Panic().Err(err).Msg("failed to create sql statement")
}
log.Info().Msg("init database: done")
}

45
main.go
View file

@ -1,17 +1,52 @@
package main package main
import ( import (
"watn3y/bloaterbotv3/commands/gaypoints" "flag"
"watn3y/bloaterbotv3/commands/notify" "fmt"
"watn3y/bloaterbotv3/config" "os"
"watn3y/bloaterbotv3/webserver" "time"
"watn3y.de/bloaterbot/commands/gaypoints"
"watn3y.de/bloaterbot/commands/notify"
"watn3y.de/bloaterbot/config"
"watn3y.de/bloaterbot/webserver"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
) )
func main() { func main() {
fmt.Println("Starting bloaterbot...")
configureLogger()
encodeConfig := flag.Bool("generate-example-config", false, "Generates a example config to config.toml.example")
flag.Parse()
if *encodeConfig {
config.EncodeToml()
os.Exit(0)
}
config.LoadConfig() config.LoadConfig()
gaypoints.InitDB() gaypoints.InitDB()
notify.InitDB() notify.InitDB()
go webserver.RunWeb()
go webserver.RunServer()
bot() bot()
} }
func configureLogger() {
output := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.DateTime}
log.Logger = zerolog.New(output).With().Timestamp().Caller().Logger()
//! note that we overwrite the loglevel after loading the config in config/config.go:53. This is just the default
zerolog.SetGlobalLevel(zerolog.TraceLevel)
log.Info().Msg("Started logger")
}

View file

@ -1,28 +1,19 @@
package balonlyl package balonlyl
import ( import (
"watn3y.de/bloaterbot/botIO"
"watn3y.de/bloaterbot/config"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"log"
"strconv"
"watn3y/bloaterbotv3/botIO"
"watn3y/bloaterbotv3/config"
) )
func Balonlyl(update tgbotapi.Update, bot *tgbotapi.BotAPI) { func Balonlyl(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
/*balonlylLines := [4]string{
balonlylAT + " they're talking about you",
"Bitch " + balonlylAT + " they're shittalking you again",
"Bruh wtf " + balonlylAT + ", again",
balonlylAT + " look at these idiots",
}*/
log.Println("[balonlyl] French detected in Chat: " + strconv.FormatInt(update.Message.Chat.ID, 10))
message := tgbotapi.MessageConfig{ message := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID}, BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},
ParseMode: "html", ParseMode: "html",
DisableWebPagePreview: true, DisableWebPagePreview: true,
//Text: balonlylLines[rand.Intn(len(balonlylLines))],
Text: config.BotConfig.Balonlyl.BalonlylAT, Text: config.BotConfig.Balonlyl.BalonlylAT,
} }

View file

@ -1,32 +1,28 @@
package text package text
import ( import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"strings" "strings"
"time" "time"
"watn3y/bloaterbotv3/commonlogic"
"watn3y/bloaterbotv3/config" "watn3y.de/bloaterbot/commonlogic"
"watn3y/bloaterbotv3/text/balonlyl" "watn3y.de/bloaterbot/config"
"watn3y.de/bloaterbot/text/balonlyl"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/rs/zerolog/log"
) )
// TODO logging
func Matcher(update tgbotapi.Update, bot *tgbotapi.BotAPI) { func Matcher(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
log.Debug().Str("Text", update.Message.Text).Msg("Starting text matcher")
if time.Since(config.BotConfig.Shutup[update.Message.Chat.ID]) <= time.Minute*60 { if time.Since(config.BotConfig.Shutup[update.Message.Chat.ID]) <= time.Minute*60 {
log.Debug().Str("text", update.Message.Text).Int64("chat", update.Message.Chat.ID).Msg("Aborting due to shut-up")
return return
} }
/*
//nhentai
const nhentaiRegex string = "([ \\t\\n\\r]|^)\\d{4,}([ \\t\\n\\r]|$)"
isNhentai, err := regexp.MatchString(nhentaiRegex, update.Message.Text)
if err != nil {
log.Panicf("Failed to compile regex for nhentai", err)
}
if isNhentai && (commonlogic.ContainsInt64(config.BotConfig.Nhentai.EnabledChats, update.Message.Chat.ID) || update.Message.From.ID == update.Message.Chat.ID) {
go nhentai.Nhentai(nhentaiRegex, update, bot)
}
*/
//balonlyl //balonlyl
var isBalonlyl bool = false var isBalonlyl = false
for _, word := range config.BotConfig.Balonlyl.TriggerWords { for _, word := range config.BotConfig.Balonlyl.TriggerWords {
if strings.Contains(strings.ToLower(update.Message.Text), word) && (commonlogic.ContainsInt64(config.BotConfig.Balonlyl.EnabledChats, update.Message.Chat.ID)) { if strings.Contains(strings.ToLower(update.Message.Text), word) && (commonlogic.ContainsInt64(config.BotConfig.Balonlyl.EnabledChats, update.Message.Chat.ID)) {
isBalonlyl = true isBalonlyl = true
@ -34,6 +30,7 @@ func Matcher(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
} }
} }
if isBalonlyl { if isBalonlyl {
log.Info().Str("text", update.Message.Text).Int64("chat", update.Message.Chat.ID).Msg("Matched text in message")
go balonlyl.Balonlyl(update, bot) go balonlyl.Balonlyl(update, bot)
} }

View file

@ -1,81 +0,0 @@
package nhentai
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"watn3y/bloaterbotv3/config"
)
func doAPIRequest(hentaiID string) (exists bool, Details nhentaiResponse) {
client := &http.Client{}
req, err := http.NewRequest("GET", config.BotConfig.Nhentai.APIEndpoint+"/gallery/"+hentaiID, nil)
if err != nil {
log.Fatalln(err)
}
req.Header.Set("User-Agent", "Golang_Spider_Bot/3.0")
resp, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
if resp.StatusCode == 404 {
return false, nhentaiResponse{}
} else if resp.StatusCode != 200 {
return false, nhentaiResponse{}
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
var hentai nhentaiResponse
if err := json.Unmarshal(body, &hentai); err != nil { // Parse []byte to the go struct pointer
fmt.Println("Can not unmarshal JSON")
}
return true, hentai
}
func parseAPIResponse(rawHentai nhentaiResponse) (formattedHentai hentai) {
var hentai = hentai{
ID: rawHentai.ID,
Title: rawHentai.Title.Pretty,
UploadDate: rawHentai.UploadDate,
}
for _, tag := range rawHentai.Tags {
if tag.Type == "tag" {
hentai.Tags = append(hentai.Tags, struct {
Name string
URL string
}{Name: tag.Name, URL: tag.URL})
} /* else if tag.Type == "parody" {
} else if tag.Type == "character" {
} else if tag.Type == "language" {
} else if tag.Type == "group" {
} else if tag.Type == "artist" {
} else if tag.Type == "category" {
}*/
}
return hentai
}

View file

@ -1,47 +0,0 @@
package nhentai
import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"log"
"regexp"
"strconv"
"watn3y/bloaterbotv3/botIO"
"watn3y/bloaterbotv3/config"
)
func Nhentai(regex string, update tgbotapi.Update, bot *tgbotapi.BotAPI) {
re := regexp.MustCompile(regex)
getdigit := regexp.MustCompile("\\d{4,}")
match := re.FindStringSubmatch(update.Message.Text)
hentainumber := getdigit.FindStringSubmatch(match[0])
log.Println("[nhentai] Looking for Hentai " + hentainumber[0] + " from Chat: " + strconv.FormatInt(update.Message.Chat.ID, 10))
hentaiExists, hentaiResponse := doAPIRequest(hentainumber[0])
if !hentaiExists {
log.Println("[nhentai] Dit not find Hentai " + hentainumber[0] + " from Chat: " + strconv.FormatInt(update.Message.Chat.ID, 10))
return
}
hentai := parseAPIResponse(hentaiResponse)
var tags string
for _, tag := range hentai.Tags {
tags = tags + `<a href="` + config.BotConfig.Nhentai.Domain + tag.URL + `">` + tag.Name + `</a>` + `, `
}
hentaitext := `<b>` + `<a href="` + config.BotConfig.Nhentai.Domain + `/g/` + strconv.Itoa(hentai.ID) + `">` + hentai.Title + `</a> ` + `</b>` + "\n\n" + tags
log.Println("[nhentai] Found Hentai " + hentai.Title + " in Chat: " + strconv.FormatInt(update.Message.Chat.ID, 10))
message := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},
ParseMode: "html",
DisableWebPagePreview: false,
Text: hentaitext,
}
botIO.SendMessage(message, bot)
}

View file

@ -1,56 +0,0 @@
package nhentai
type nhentaiResponse struct {
ID int `json:"id"`
Title struct {
English string `json:"english,omitempty"`
Chinese string `json:"chinese,omitempty"`
Japanese string `json:"japanese,omitempty"`
Pretty string `json:"pretty,omitempty"`
} `json:"title,omitempty"`
UploadDate int `json:"upload_date"`
Tags []struct {
Type string `json:"type"`
Name string `json:"name"`
URL string `json:"url"`
} `json:"tags"`
}
type hentai struct {
ID int
Title string
UploadDate int
/*
Language struct { //since there can be multiple languages I won't implement this shit
Name string
URL string
}
Artist struct {
Name string
URL string
}
Group struct {
Name string
URL string
}
Category struct {
Name string
URL string
}
Character struct {
Name string
URL string
}
Parody struct {
Name string
URL string
}
*/
Tags []struct {
Name string
URL string
}
}

View file

@ -1,17 +1,39 @@
package webserver package webserver
import ( import (
"log"
"net/http" "net/http"
"watn3y.de/bloaterbot/config"
"github.com/rs/zerolog/log"
) )
func RunWeb() { func RunServer() {
fs := http.FileServer(http.Dir("./videos")) //http.HandleFunc("/", handle204)
http.Handle("/", fs)
videos := http.FileServer(http.Dir("data/videos"))
nenefoot := http.FileServer(http.Dir("data/nenefoot"))
http.Handle("/", videos)
http.Handle("/nenefoot/", nenefoot)
log.Info().Str("port", config.BotConfig.Webserver.Port).Msg("Started webserver")
err := http.ListenAndServe(":"+config.BotConfig.Webserver.Port, nil)
log.Print("Listening on :3556...")
err := http.ListenAndServe(":3556", nil)
if err != nil { if err != nil {
log.Fatal(err) log.Panic().Err(err).Msg("Failed to start webserver")
} }
} }
/*func handle204(w http.ResponseWriter, r *http.Request) {
buf, err := os.ReadFile("data/204.jpg")
if err != nil {
log.Err(err).Msg("failed to open data/204.jpg")
}
w.Header().Set("Content-Type", "image/jpeg")
w.Write(buf)
return
}
*/