main.go (2427B)
1 package main 2 3 import ( 4 "fmt" 5 ini "github.com/go-ini/ini" 6 tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" 7 "log" 8 "os" 9 "path/filepath" 10 "strings" 11 "sync" 12 "time" 13 ) 14 15 var logPath string 16 17 func main() { 18 binPath, err := filepath.Abs(os.Args[0]) 19 if err != nil { 20 log.Fatal(err) 21 } 22 logPath = filepath.Dir(binPath) 23 log.Println("Logs path:", logPath) 24 25 cfg, err := ini.Load("config.ini") 26 if err != nil { 27 log.Fatal("Invalid config.ini: ", err) 28 } 29 30 token := cfg.Section("").Key("token").String() 31 bot, err := tgbotapi.NewBotAPI(token) 32 if err != nil { 33 log.Fatal("Cannot connect to Telegram: ", err) 34 } 35 bot.Debug = false 36 log.Printf("Authorized on account %s", bot.Self.UserName) 37 var writeMutex sync.Mutex 38 u := tgbotapi.NewUpdate(0) 39 u.Timeout = 60 40 updates := bot.GetUpdatesChan(u) 41 42 for update := range updates { 43 if update.Message != nil { 44 go writeLog(update.Message, &writeMutex) 45 } 46 } 47 } 48 49 func clearName(name *string) { 50 *name = strings.ReplaceAll(*name, string(os.PathSeparator), "-") 51 *name = strings.ReplaceAll(*name, string(os.PathListSeparator), "-") 52 *name = strings.ReplaceAll(*name, ".", "") 53 } 54 55 func writeLog(msg *tgbotapi.Message, mtx *sync.Mutex) { 56 mtx.Lock() 57 defer mtx.Unlock() 58 59 var chat string 60 if msg.Chat.Type == "group" { 61 chat = msg.Chat.Title 62 } else { 63 chat = "private" 64 } 65 clearName(&chat) 66 67 var fromName string 68 if msg.From.UserName != "" { 69 fromName = msg.From.UserName 70 } else { 71 fromName = msg.From.FirstName + " " + msg.From.LastName 72 } 73 74 ts := time.Unix(int64(msg.Date), 0) 75 ps := string(os.PathSeparator) 76 fpath := logPath + ps + "logs" + ps + chat + ps + ts.Format("2006"+ps+"01"+ps+"02") 77 fname := fpath + ps + "log.txt" 78 79 if err := os.MkdirAll(fpath, 0750); err != nil { 80 log.Println(err) 81 return 82 } 83 84 logfile, err := os.OpenFile(fname, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0640) 85 if err != nil { 86 log.Println(err) 87 return 88 } 89 defer logfile.Close() 90 t := ts.Format("2006-01-02 15:04:05") 91 logstr := fmt.Sprintf("[%s][%s]", t, fromName) 92 93 if msg.ForwardFromChat != nil { 94 logstr += "(-> " + msg.ForwardFromChat.Title + ")" 95 } 96 97 if msg.ForwardFrom != nil { 98 logstr += "(-> " + msg.ForwardFrom.FirstName + " " + msg.ForwardFrom.LastName + ")" 99 } 100 101 if msg.Caption != "" { 102 logstr += "{" + msg.Caption + "}" 103 } 104 105 if msg.Text != "" { 106 logstr += " " + msg.Text 107 } 108 109 logstr += "\n" 110 111 if _, err := logfile.WriteString(logstr); err != nil { 112 log.Println(err) 113 } 114 }