func init() { opt = new(telebot.SendOptions) flag.StringVar(&iniFile, "ini", "", "Specify php.ini path") flag.StringVar(&tokenFile, "t", "token", "File contains bot token") flag.StringVar(&phpFile, "php", "entry.php", "PHP entry file, you can access JSON encoded message data in $message") flag.UintVar(&workers, "w", 1, "Run `N` goroutines to process message, must greater than 0") flag.Parse() data, err := ioutil.ReadFile(tokenFile) if err != nil { log.Fatalf("Cannot read token from file[%s]: %s", tokenFile, err) } token = strings.TrimSpace(string(data)) if workers < 1 { flag.PrintDefaults() os.Exit(1) } if _, err := os.Stat(phpFile); err != nil { log.Fatalf("PHP entry file %s error: %s", phpFile, err) } bot, err = telebot.NewBot(token) if err != nil { log.Fatalf("Cannot start telebot: %s", err) } pipe = make(chan task) }
func main() { flag.Parse() if *token_file == "" { flag.PrintDefaults() os.Exit(1) } args := flag.Args() log.Print(args) if len(args) < 1 { log.Fatal(`Usage: ` + os.Args[0] + ` -worker 5 -token=token_file cmd_to_run arg1 arg2 ...`) } token, err := ioutil.ReadFile(*token_file) if err != nil { log.Fatal(err) } bot, err := telebot.NewBot(string(token)) if err != nil { log.Fatal(err) } messages := make(chan telebot.Message) bot.Listen(messages, 1*time.Second) h := CreateHandler(bot, args, *max_worker) log.Printf("Workers: %d\n", *max_worker) for msg := range messages { go h.Process(bot, msg) } }
// bot execution logic, init logic func main() { bot, err := telebot.NewBot(os.Getenv("TELEGRAM_TOKEN")) if err != nil { fmt.Println("Fatal(0x0): Unable to start bot") return } data_map = make(map[string]BotData) msg_map = make(map[string]string) data, err := ioutil.ReadFile("msg.txt") if err != nil { fmt.Println("Fatal(0x1): Unable to read msg file") return } err = json.Unmarshal(data, &msg_map) if err != nil { fmt.Println("Fatal(0x2): Unable to parse msg file") return } messages := make(chan telebot.Message) bot.Listen(messages, 1*time.Second) fmt.Println("Info(0x0): Now listening") for msg := range messages { handler(bot, msg) } }
func RunTelegramBot() { if GetConfiguration().Notification.TelegramBotApiKey == "" { return } bot, err := telebot.NewBot(GetConfiguration().Notification.TelegramBotApiKey) if err != nil { logging.MustGetLogger("").Error("Unable to start Telegram-Bot: ", err) return } logging.MustGetLogger("").Info("Telgram-Bot started.") Bot = bot messages := make(chan telebot.Message) bot.Listen(messages, 1*time.Second) for message := range messages { if message.Text == "/start" { bot.SendMessage(message.Chat, "Welcome to the UpAndRunning2 Telegram-Bot! \U0001F44B\n\nPlease use your User-ID (`"+strconv.Itoa(message.Sender.ID)+"`) as notification-target in UpAndRunning2.", &SendOptions) } else if message.Text == "/id" { bot.SendMessage(message.Chat, "Your User-ID: `"+strconv.Itoa(message.Sender.ID)+"`", &SendOptions) } else if message.Text == "/server" { bot.SendMessage(message.Chat, "This server is running *UpAndRunning2 v"+GetConfiguration().Static.Version+"* (`"+GetConfiguration().Static.GoVersion+"@"+GetConfiguration().Static.GoArch+"`).\n"+ "You can find more information about this application [here](https://github.com/MarvinMenzerath/UpAndRunning2).\n\n"+ "*Server-Settings:*\n - Title: `"+GetConfiguration().Application.Title+"`\n - Interval: `"+strconv.Itoa(GetConfiguration().Dynamic.Interval)+"`\n"+ " - Redirects: `"+strconv.Itoa(GetConfiguration().Application.RedirectsToFollow)+"`\n - Offline-Checks: `"+strconv.FormatBool(GetConfiguration().Application.RunCheckIfOffline)+"`", &SendOptions) } } }
func OpenBot(name string) (*Bot, error) { rand.Seed(time.Now().UTC().UnixNano()) file, err := os.Open(name) if err != nil { return nil, err } defer file.Close() var bot *Bot err = json.NewDecoder(file).Decode(&bot) if err != nil { return nil, err } bot.Bot, err = telebot.NewBot(bot.Token) if err != nil { log.Fatal(err) } else { log.Printf("Bot " + bot.Name + " started!") } return bot, err }
// NewBot creates a Bots with token `token`, which is a secret API key assigned to particular bot. func NewBot(token string) (*Bot, error) { bot, err := telebot.NewBot(token) if err != nil { return nil, errors.New("Failed to create a bot!") } return &Bot{token, false, bot, make(chan telebot.Message), make(map[string]*Task)}, nil }
func main() { // the token on which telebot will send/receive stuff var token = flag.String("token", "", "The bot token") // the address and port on which redis will listen var redis = flag.String("redis", "localhost:6379", "The address to bind to redis, e.g. \"localhost:5555\"") // the cron string on which to send all the currencies (why I did this?) var cronString = flag.String("cron", "0 0 9 * * *", "The cron string on which to send currencies.") // the filename of the log when on the server (this is good) var output = flag.String("output", "", "The file where to create the log") flag.Parse() bot, err := telebot.NewBot(*token) // if telegram is not there, bail. if err != nil { panic(err) } fixrAccessor := fixrdb.New("tcp", *redis) defer fixrAccessor.Close() // if there's a file, create it and use it. Else, assume debugging: pipe to stdout. if len(*output) > 0 { output, err := os.Create(*output) if err != nil { panic(err) } logging.Start(output) } else { logging.Start(os.Stdout) } // this doesn't actually work... but whatever. defer func() { logging.Info("Stopping the program") }() logging.Info("Started Redis instance") // start the scheduler startSched(bot, fixrAccessor, *cronString) messages := make(chan telebot.Message) done := make(chan bool) // listen to updates bot.Listen(messages, 1*time.Second) // handle messages on a different goroutine, so we don't mess this up. go handleMessages(messages, bot, fixrAccessor, done) // wait for the inevitable end (that never comes) <-done }
// Initialize Telegram adapter func (adapter *Telegram) Init() error { bot, err := telebot.NewBot(adapter.cfg.Token) if err != nil { return err } adapter.bot = bot return nil }
func main() { // Grab current executing directory // In most cases it's the folder in which the Go binary is located. pwd, err := osext.ExecutableFolder() if err != nil { log.Fatalf("error getting executable folder: %s", err) } configJSON, err := ioutil.ReadFile(path.Join(pwd, "config.json")) if err != nil { log.Fatalf("error reading config file! Boo: %s", err) } var config map[string]string json.Unmarshal(configJSON, &config) telegramAPIKey, ok := config["telegram_api_key"] if !ok { log.Fatalf("config.json exists but doesn't contain a Telegram API Key! Read https://core.telegram.org/bots#3-how-do-i-create-a-bot on how to get one!") } botName, ok := config["name"] if !ok { log.Fatalf("config.json exists but doesn't contain a bot name. Set your botname when registering with The Botfather.") } bot, err := telebot.NewBot(telegramAPIKey) if err != nil { log.Fatalf("error creating new bot, dude %s", err) } logger := log.New(os.Stdout, "[jarvis] ", 0) jb := jarvisbot.InitJarvis(botName, bot, logger, config) defer jb.CloseDB() jb.AddFunction("/laugh", jb.SendLaugh) jb.AddFunction("/neverforget", jb.NeverForget) jb.AddFunction("/touch", jb.Touch) jb.AddFunction("/hanar", jb.Hanar) jb.AddFunction("/ducks", jb.SendImage("quack quack m**********r")) jb.AddFunction("/chickens", jb.SendImage("cluck cluck m**********r")) jb.GoSafely(func() { logger.Println("Scheduling exchange rate update") for { time.Sleep(1 * time.Hour) jb.RetrieveAndSaveExchangeRates() logger.Printf("[%s] exchange rates updated!", time.Now().Format(time.RFC3339)) } }) messages := make(chan telebot.Message) bot.Listen(messages, 1*time.Second) for message := range messages { jb.Router(message) } }
func main() { // Grab current executing directory // In most cases it's the folder in which the Go binary is located. pwd, err := osext.ExecutableFolder() if err != nil { log.Fatalf("error getting executable folder: %s", err) } configJSON, err := ioutil.ReadFile(path.Join(pwd, "config.json")) if err != nil { log.Fatalf("error reading config file! Boo: %s", err) } var config map[string]string json.Unmarshal(configJSON, &config) telegramAPIKey, ok := config["telegram_api_key"] if !ok { log.Fatalf("config.json exists but doesn't contain a Telegram API Key! Read https://core.telegram.org/bots#3-how-do-i-create-a-bot on how to get one!") } botName, ok := config["name"] if !ok { log.Fatalf("config.json exists but doesn't contain a bot name. Set your botname when registering with The Botfather.") } bot, err := telebot.NewBot(telegramAPIKey) if err != nil { log.Fatalf("error creating new bot, %s", err) } logger := log.New(os.Stdout, "[morningbot] ", 0) logger.Printf("Args: %s %s %s", botName, bot, logger) mb := morningbot.InitMorningBot(botName, bot, logger, config) defer mb.CloseDB() mb.GoSafely(func() { logger.Println("Scheduling Time Check") for { nextHour := time.Now().Truncate(time.Hour).Add(time.Hour) timeToNextHour := nextHour.Sub(time.Now()) time.Sleep(timeToNextHour) logger.Printf("[%s] [%s] !", time.Now().Format(time.RFC3339), time.Now().Hour()) if time.Now().Hour() == 7 { mb.MorningCall() } } }) messages := make(chan telebot.Message) bot.Listen(messages, 1*time.Second) for message := range messages { mb.Router(message) } }
func main() { var msg, country string flag.Parse() if *token_file == "" { flag.PrintDefaults() os.Exit(1) } token, err := ioutil.ReadFile(*token_file) if err != nil { log.Fatal(err) } bot, err := telebot.NewBot(string(token)) if err != nil { return } messages := make(chan telebot.Message) bot.Listen(messages, 1*time.Second) for message := range messages { // pretty.Println(message.Sender) msg = message.Text if msg == "/hi" { count := 1 for { pretty.Println(count) count++ bot.SendMessage(message.Chat, "Hello, "+message.Sender.FirstName+"!", nil) time.Sleep(1000 * time.Millisecond) } } else if strings.HasPrefix(msg, "/flag") { //check if flag is empty country = "ASEAN" //msg[6:] pretty.Print(country) photo := "./resources/flags/" + country + ".png" boom, err := telebot.NewFile(photo) if err != nil { pretty.Print(err) } pretty.Print(&bot) pretty.Print(&boom) // SendPhoto // telebot.File{}ASEAN&telebot.File{FileID:"", FileSize:0, filename:"./resources/flags/ASEAN.png"} // pretty.Print(reflect.TypeOf((*bot).SendMessage)) // // get from directory // err = bot.SendAudio(message.Chat, &boom, nil) // err = bot.SendMessage(message.Chat, &boom, nil) if err != nil { pretty.Print(err) } } } }
func main() { var c int var configurationFile = "telegram-config.json" var logFile string OptErr = 0 for { if c = Getopt("c:l:h"); c == EOF { break } switch c { case 'c': configurationFile = OptArg case 'l': logFile = OptArg case 'h': println("usage: " + os.Args[0] + " [-c configfile.json|-l logfile|-h]") os.Exit(1) } } config, err := util.LoadConfig(configurationFile) if logFile != "" { //Set logging to file f, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { log.Fatal("error opening file: %v", err) } defer f.Close() log.SetOutput(f) } bot, err := telebot.NewBot(config.Token) if config.Token != "" { fmt.Println("Token: " + config.Token) } fmt.Println("Configuration file: " + configurationFile) fmt.Println("Log file: " + logFile) if err != nil { return } messages := make(chan telebot.Message) bot.Listen(messages, 1*time.Second) for message := range messages { for _, d := range plugin_registry.Plugins { go d.Run(bot, config, message) } } }
func main() { telegramAPIKey := os.Getenv("DJIGURBOT_TELEGRAMAPIKEY") if telegramAPIKey == "" { panic("Telegram api key is not set.") } bot, err := telebot.NewBot(telegramAPIKey) if err != nil { panic("Could not connect to Telegram API") } toasts, err := readToastsFile() if err != nil { panic("Could not read toasts.txt file") } messages := make(chan telebot.Message) bot.Listen(messages, 1*time.Second) for message := range messages { if message.Text == "/hi" { bot.SendMessage(message.Chat, "Привет, "+message.Sender.FirstName+"!", nil) } else if strings.Contains(message.Text, "Тост!") { randomToast := toasts[rand.Intn(len(toasts))] bot.SendMessage(message.Chat, randomToast.Text, nil) } else if strings.Contains(strings.ToLower(message.Text), "костя") { bot.SendMessage(message.Chat, "Костя крутой!", nil) } else if strings.Contains(strings.ToLower(message.Text), "твоя!") { bot.SendMessage(message.Chat, "Нееееет, твоя!", nil) } else if strings.Contains(strings.ToLower(message.Text), "крутой") { bot.SendMessage(message.Chat, "Нееееет, "+message.Sender.FirstName+", это ты крутой!", nil) } else if strings.Contains(strings.ToLower(message.Text), "сокиабле") { bot.SendMessage(message.Chat, "Сокиабле? ЧОБЛЯ?", nil) } else if strings.Contains(strings.ToLower(message.Text), "доброе утро") { bot.SendMessage(message.Chat, "И тебе наидобрейшего утра, "+message.Sender.FirstName+"!", nil) } else if strings.Contains(strings.ToLower(message.Text), "поздравляй!") { bot.SendMessage(message.Chat, `С 8 марта поздравляем вас, коллеги, От души хотим вам пожелать, Чтоб совместные победы и успехи Дали нам возможность процветать! Чтоб в делах житейских и в работе Находить умели компромисс, Одевались по последней моде, Были леди, то бишь миссис или мисс. Чтобы было нам в кого влюбляться, Чтобы было нас кому любить, Молодыми вечно оставаться и насыщенной веселой жизнью жить!`, nil) } } }
func newbot(c *cli.Context) { var err error theBot, err = telebot.NewBot(c.String("tgtoken")) if err != nil { println(err.Error()) os.Exit(TG_ERROR) } theBot.Messages = make(chan telebot.Message, 1000) theBot.Queries = make(chan telebot.Query, 1000) go messages() go queries() theBot.Start(1 * time.Second) }
func GetBotInstance() *bot { bot_once.Do(func() { cfg := GetConfigurationInstance() tb, err := telebot.NewBot(cfg.TelegramKey) if err != nil { log.Fatal(err) } bot_instance = &bot{Connection: tb} }) return bot_instance }
func startBot() *Cambot { var err error var cb Cambot cb.bot, err = telebot.NewBot(TELEGRAM_SECRET_TOKEN) if err != nil { return nil } cb.messages = make(chan telebot.Message) cb.bot.Listen(cb.messages, REFRESH_TIME) go cb.ProceessMessage() return &cb }
func main() { bot, err := telebot.NewBot("124223052:AAGr9lxL0Ewi50jBzEDSKy36d_Rxh-g5pUg") if err != nil { return } messages := make(chan telebot.Message) bot.Listen(messages, 1*time.Second) for message := range messages { if message.Text == "/hi" { bot.SendMessage(message.Chat, "Hello, "+message.Sender.FirstName+"!", nil) } } }
func main() { bot, err := telebot.NewBot(os.Getenv("TELEGRAM_SECRET")) if err != nil { panic(err) } messages := make(chan telebot.Message) bot.Listen(messages, 1*time.Second) fmt.Println("Bot started.") // Message handler for message := range messages { if message.Text == "/help" || message.Text == "/start" { bot.SendMessage(message.Chat, "Hello, "+message.Sender.FirstName+"! To get the location of a place in NUS, just type the keywords of the place you're looking for.", nil) } else { // Perform case insensitive search and remove bot mention in case it's a mention locations, err := getLocationInfoNUS(strings.Replace(strings.ToLower(message.Text), strings.ToLower(BOT_NICK)+" ", "", 1)) if len(locations) != 0 && err != nil { bot.SendMessage(message.Chat, "Oops! I encountered an error while searching for the location you requested. Please try again later.", nil) fmt.Printf("Error while retrieving location: %s\n", err.Error()) continue } if len(locations) == 0 { bot.SendMessage(message.Chat, "Oops! I cannot find any result with your search query.", nil) continue } for _, location := range locations { bot.SendMessage(message.Chat, "Location found! Sending you the map...", nil) photo, err := getLocationMap(location) if err != nil { bot.SendMessage(message.Chat, "Oops! I encountered an error while searching for the location you requested. Please try again later.", nil) fmt.Printf("Error while retrieving map: %s\n", err.Error()) continue } bot.SendPhoto(message.Chat, photo, nil) } } // Keep track of number of requests (no particular reason to) requestCount++ fmt.Printf("Total Requests: %d\n", requestCount) } }
func processHook(ctx webhooks.Context) { h := ctx.Hook() branch := strings.TrimPrefix(h.Ref, `refs/heads/`) for _, r := range cfg.Repos { go func(r repo) { if r.Name != h.Repo.Name || (r.Branch != `*` && r.Branch != branch) { return } go r.Tasks.Run() //execute tasks if r.Notify.Telegram.ChatID != 0 && r.Notify.Telegram.Token != `` { var ( buf bytes.Buffer bot *telebot.Bot err error ) err = tmpl.Execute(&buf, map[string]interface{}{ `hook`: h, `branch`: branch, }) if err != nil { log.Println(`Template ERR:`, err) return } if bot, err = telebot.NewBot(r.Notify.Telegram.Token); err != nil { log.Println(`Telegram ERR:`, err) return } err = bot.SendMessage(telebot.User{ID: r.Notify.Telegram.ChatID}, buf.String(), &sendOpts) if err != nil { log.Println(`Telegram ERR:`, err) return } log.Println(`Message Sent`) } }(r) } }
func main() { bot, err := telebot.NewBot(botToken) if err != nil { return } messages := make(chan telebot.Message) bot.Listen(messages, 1*time.Second) for message := range messages { if message.Text == "stat" { uptime := cmd("uptime") bot.SendMessage(message.Chat, uptime, nil) } if message.Text == "dir" { ls := cmd("ls") bot.SendMessage(message.Chat, ls, nil) } } }
func NewHerald(token string) (*Herald, error) { bot, err := telebot.NewBot(token) if err != nil { return nil, err } h := &Herald{bot: bot} h.Handlers = map[string]Handler{ "/hi": h.RegisterUser, "/help": h.GetUsage, "/kill": h.KillCommand, "/log": h.GetOutput, // "/stats": , "/who": h.GetUsers, } return h, nil }
func main() { bot, err := telebot.NewBot(os.Getenv("TELEGRAM_TOKEN")) if err != nil { panic(err) } bot.Messages = make(chan telebot.Message, 1000) bot.Queries = make(chan telebot.Query, 1000) go inlineHandler(bot) go func() { for message := range bot.Messages { if message.Text == "/start" { log.Printf("%s %d signed up for Printer Facts", message.Sender.Username, message.Sender.ID) bot.SendMessage(message.Chat, "Hello human. I am a printer facts bot. Inline me to get printer facts.\n\nIf you are having trouble with cached facts, type in some random garbage in after @printerfacts.", nil) } } }() bot.Start(1 * time.Second) }
func main() { rand.Seed(time.Now().UnixNano()) cards, err := mtgprice.Open(mtgprice.Opts{Filename: "mtgprice.kv", CardData: "AllCards.json"}) if err != nil { log.Fatal("loading cards:", err) } closeOnTerm(cards) bot, err := telebot.NewBot(os.Getenv("TOKEN")) if err != nil { log.Fatal(err) } messages := make(chan telebot.Message) bot.Listen(messages, 1*time.Minute) for msg := range messages { if err := handleMessage(cards, bot, msg); err != nil { log.Printf("Error handling message %v: %v", msg, err) } } }
func main() { rand.Seed(time.Now().UTC().UnixNano()) dictData, err := ioutil.ReadFile("dict.txt") if err != nil { logger.Fatal(err) } dict := strings.Split(string(dictData), "\n") SecretAPIKey := os.Getenv(BotApiKey) if SecretAPIKey == "" { logger.Fatalf("env variable %s not specifited", BotApiKey) } bot, err := telebot.NewBot(SecretAPIKey) if err != nil { logger.Fatal(err) } messages := make(chan telebot.Message) bot.Listen(messages, 1*time.Second) sendOptions := telebot.SendOptions{ ReplyMarkup: telebot.ReplyMarkup{ ForceReply: true, Selective: true, CustomKeyboard: [][]string{ []string{"Совет Гуру"}, }, }, } for message := range messages { logger.Printf("Req %s from user %s ", message.Text, message.Sender.FirstName) if message.Text == "/start" { bot.SendMessage(message.Chat, "Привет, я раскажу тебе как двигать тазом, "+message.Sender.FirstName+"!", &sendOptions) } else { bot.SendMessage(message.Chat, processGeneralMessage(message.Text, dict), &sendOptions) } } }
func main() { start := util.TimestampMS() // Connect to Telegram var err error bot, err = telebot.NewBot(*token) if err != nil { log.Fatalf("Error connecting to Telegram: %[1]s", err) return } messages := make(chan telebot.Message) // Enable message listener bot.Listen(messages, 1*time.Second) // Print "connected" message log.Infof("Successfully connected to Telegram!") // Update timetables timetables.Update() go posts.Loop(bot, *debug) go laundry.Loop(bot) go listen(bot) startedAt = time.Now() var startup = "Ranssibot started up" if *debug { startup = fmt.Sprintf("Ranssibot started up in %[1]dms @ %[2]s (Debug mode)", util.TimestampMS()-start, startedAt.Format("15:04:05 02.01.2006")) } log.Infof(startup) onoffspam(startup) // Listen to messages for message := range messages { go handleCommand(bot, message) } }
func main() { //init redis redisClient = redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", DB: 1, }) dict.PrepareIndex() bot, err := telebot.NewBot(BOT_TOKEN) if err != nil { return } util.LogInit() messages := make(chan telebot.Message) bot.Listen(messages, 2*time.Second) for message := range messages { sender_id := message.Chat.ID // analytics purpose k := "u:" + strconv.Itoa(sender_id) redisClient.ZIncrBy("sorted_users", 1, k) definition := GetDefinition(message.Text, message.Chat) err = bot.SendMessage(message.Chat, definition, &telebot.SendOptions{ParseMode: "Markdown"}) if err != nil { util.LogError("sendMessage", sender_id, err) } } }
func main() { // Load main configuration. usr, err := user.Current() if err != nil { log.Fatal(err) } fmt.Println(usr) //configFile := usr.HomeDir + "/.config/gfxbot/config.toml" configFile := "config.toml" err = gfxBot.LoadConfig(configFile, &globalConfig) if err != nil { log.Fatal(err) } bot, err := telebot.NewBot(globalConfig.Token) if err != nil { log.Fatal(err) } messages := make(chan telebot.Message) bot.Listen(messages, 1*time.Second) for message := range messages { fmt.Println(message) stathat.PostEZCount("gfxBot message processed", "*****@*****.**", 1) if message.Text == "/start" { bot.SendMessage(message.Chat, "This is a Telegram bot for searching images into different services.", nil) } if strings.HasPrefix(message.Text, "/duck") { bot.SendChatAction(message.Chat, telebot.Typing) duck := gfxBot.NewDuck() img, err := duck.Search(strings.TrimPrefix(strings.TrimPrefix(message.Text, "/duck"), "@gfxBot")) if err != nil { fmt.Println("Error in duck.Search()") fmt.Println(err) bot.SendMessage(message.Chat, fmt.Sprintf("%s", err), nil) continue } err = sendImage(bot, message, img) if err != nil { bot.SendMessage(message.Chat, fmt.Sprintf("%s", err), nil) } } if strings.HasPrefix(message.Text, "/flickr") { bot.SendChatAction(message.Chat, telebot.Typing) flickr := gfxBot.NewFlickr(globalConfig.FlickrAPIKey, globalConfig.FlickrAPISecret) img, err := flickr.Search(strings.TrimPrefix(strings.TrimPrefix(message.Text, "/flickr"), "@gfxBot")) if err != nil { fmt.Println("Error in flickr.Search()") fmt.Println(err) bot.SendMessage(message.Chat, fmt.Sprintf("%s", err), nil) continue } err = sendImage(bot, message, img) if err != nil { bot.SendMessage(message.Chat, fmt.Sprintf("%s", err), nil) } } if strings.HasPrefix(message.Text, "/instagram") { bot.SendChatAction(message.Chat, telebot.Typing) instagram := gfxBot.NewInstagram(globalConfig.InstagramAPIKey, globalConfig.InstagramAPISecret, globalConfig.InstagramAPIToken) img, err := instagram.Search(strings.TrimPrefix(strings.TrimPrefix(message.Text, "/instagram"), "@gfxBot")) if err != nil { fmt.Println("Error in instagram.Search()") fmt.Println(err) bot.SendMessage(message.Chat, fmt.Sprintf("%s", err), nil) continue } err = sendImage(bot, message, img) if err != nil { bot.SendMessage(message.Chat, fmt.Sprintf("%s", err), nil) } } if message.Text == "/help" { bot.SendMessage(message.Chat, "This is a Telegram bot for searching images into different services.", nil) } } }
func main() { token := flag.String("token", "", "The Telegram bot token") to := flag.String("to", "", "The mail recipient") from := flag.String("from", "", "The mail sender") server := flag.String("server", "", "The mail server") port := flag.Int("port", 587, "The mail server port") user := flag.String("user", "", "") pass := flag.String("pass", "", "") subject := flag.String("subject", "", "") flag.Parse() bot, err := telebot.NewBot(*token) if err != nil { return } // Fetching Mails and send as Telegram messages var ( c *imap.Client cmd *imap.Command rsp *imap.Response ) c, _ = imap.Dial(*server) defer c.Logout(30 * time.Second) c.Data = nil if c.Caps["STARTTLS"] { c.StartTLS(nil) } if c.State() == imap.Login { c.Login(*user, *pass) } cmd, _ = imap.Wait(c.List("", "%")) c.Data = nil c.Select("INBOX", true) set, _ := imap.NewSeqSet("") set.Add("1:*") cmd, _ = c.Fetch(set, "RFC822.HEADER") for cmd.InProgress() { c.Recv(-1) for _, rsp = range cmd.Data { header := imap.AsBytes(rsp.MessageInfo().Attrs["RFC822.HEADER"]) if msg, _ := mail.ReadMessage(bytes.NewReader(header)); msg != nil { fmt.Println("|--", msg.Header.Get("FROM")) } } cmd.Data = nil c.Data = nil } if rsp, err := cmd.Result(imap.OK); err != nil { if err == imap.ErrAborted { fmt.Println("Fetch command aborted") } else { fmt.Println("Fetch error:", rsp.Info) } } /* * Listen to Telegram messages and send as mail */ messages := make(chan telebot.Message) bot.Listen(messages, 1*time.Second) for message := range messages { m := gomail.NewMessage() m.SetHeader("From", *from) m.SetHeader("To", *to) m.SetHeader("Subject", *subject) m.SetBody("text/html", message.Text) d := gomail.NewPlainDialer(*server, *port, *user, *pass) d.TLSConfig = &tls.Config{InsecureSkipVerify: true} if err := d.DialAndSend(m); err != nil { panic(err) } } }