Created
August 1, 2022 15:45
-
-
Save slonoed/523c5050b8f74622b9cc1b1d33a356b6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"log" | |
"os" | |
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" | |
"go.mongodb.org/mongo-driver/mongo" | |
"go.mongodb.org/mongo-driver/mongo/options" | |
) | |
const ( | |
_mongoMessagesCollection = "messages" | |
) | |
func main() { | |
tgBotToken := os.Getenv("TG_BOT_TOKEN") | |
if tgBotToken == "" { | |
panic("empty TG_BOT_TOKEN") | |
} | |
dbName := os.Getenv("DB_NAME") | |
if dbName == "" { | |
panic("empty DB_NAME") | |
} | |
dbUser := os.Getenv("DB_USER") | |
if dbUser == "" { | |
panic("empty DB_USER") | |
} | |
dbPassword := os.Getenv("DB_PASSWORD") | |
if dbPassword == "" { | |
panic("empty DB_PASSWORD") | |
} | |
dbURL := os.Getenv("DB_URL") | |
if dbURL == "" { | |
panic("empty DB_URL") | |
} | |
bot, err := tgbotapi.NewBotAPI(tgBotToken) | |
if err != nil { | |
log.Panic(err) | |
} | |
opts := options. | |
Client(). | |
SetAuth(options.Credential{ | |
Username: dbUser, | |
Password: dbPassword, | |
}). | |
ApplyURI(dbURL) | |
client, err := mongo.Connect(context.Background(), opts) | |
if err != nil { | |
log.Panic(err) | |
} | |
collection := client.Database(dbName).Collection(_mongoMessagesCollection) | |
u := tgbotapi.NewUpdate(0) | |
u.Timeout = 60 | |
updates := bot.GetUpdatesChan(u) | |
log.Println("Start reading updates") | |
for update := range updates { | |
if update.Message != nil { | |
msg := update.Message | |
_, err := collection.InsertOne(context.Background(), msg) | |
if err != nil { | |
log.Printf("[error] unable to insert message, charID:%d", msg.Chat.ID) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment