Esempio n. 1
1
File: net.go Progetto: piguet/yatzie
func SendPhoto(url string, message telebot.Message, bot *telebot.Bot) error {
	imagefile, err := SaveImage(url)
	if err != nil {
		log.Println("Error fetching ")
		log.Println(err)
		bot.SendMessage(message.Chat, url, nil)

		return err
	}
	defer os.Remove(imagefile)

	var photo = telebot.Photo{}
	photo.Thumbnail.File, err = telebot.NewFile(imagefile)
	if err != nil {
		log.Println("Error creating the new file ")
		log.Println(err)
		bot.SendMessage(message.Chat, url, nil)

		return err
	}
	//photo.filename=imagefile

	err = bot.SendPhoto(message.Chat, &photo, nil)
	if err != nil {
		log.Println("Error sending photo")
		log.Println(err)
		bot.SendMessage(message.Chat, url, nil)

		return err
	}
	return err
}
Esempio n. 2
1
func (img *Image) Send(bot *telebot.Bot, msg telebot.Message) (err error) {
	if img == nil {
		warning := "You are trying to call a method of inexistent object :-)"
		bot.SendMessage(msg.Chat, warning, nil)
		return errors.New(warning)
	}

	img.Filename = fmt.Sprint("assets/", msg.ID, img.Ext)
	if img.Filename == "" {
		bot.SendMessage(msg.Chat, "There's any filename associated to this query.", nil)
		return errors.New("There's any filename associated to this query.")
	}

	i, err := telebot.NewFile(img.Filename)
	if err != nil {
		return err
	}

	caption := img.Caption[:int(math.Min(float64(len(img.Caption)), MaxCaption))]
	photo := telebot.Photo{Thumbnail: telebot.Thumbnail{File: i, Width: img.Width, Height: img.Height}, Caption: caption}

	err = bot.SendPhoto(msg.Chat, &photo, &telebot.SendOptions{ReplyTo: msg})
	if err != nil {
		return err
	}

	return nil
}
Esempio n. 3
0
func (r *runner) handleReply(msg telebot.Message, rep *Reply) {
	if rep.User == nil {
		rep.User = &msg.Chat
	}

	switch rep.Type {
	case "doc":
		if file, err := telebot.NewFile(rep.Content); err == nil {
			doc := telebot.Document{File: file}
			r.bot.SendDocument(*rep.User, &doc, nil)
		}
	case "photo":
		if file, err := telebot.NewFile(rep.Content); err == nil {
			photo := telebot.Photo{Thumbnail: telebot.Thumbnail{File: file}}
			r.bot.SendPhoto(*rep.User, &photo, nil)
		}
	case "audio":
		if file, err := telebot.NewFile(rep.Content); err == nil {
			audio := telebot.Audio{File: file}
			r.bot.SendAudio(*rep.User, &audio, nil)
		}
	case "video":
		if file, err := telebot.NewFile(rep.Content); err == nil {
			video := telebot.Video{Audio: telebot.Audio{File: file}}
			r.bot.SendVideo(*rep.User, &video, nil)
		}
	default:
		if rep.Content != "" {
			r.bot.SendMessage(*rep.User, rep.Content, nil)
		}
	}
}
Esempio n. 4
0
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)
			}
		}
	}
}
Esempio n. 5
0
// Get map PNG from StreetDirectory
func getLocationMap(location LocationInfo) (*telebot.Photo, error) {
	filepath := fmt.Sprintf("%s/%f_%f.png", MAP_CACHE_DIR, location.Lng, location.Lat)

	// if map does not exist in our cache, retrieve!
	if _, err := os.Stat(filepath); err != nil {
		qs := SDMapQuery{
			Level: 14,
			SizeX: 500,
			SizeY: 500,
			Lon:   location.Lng,
			Lat:   location.Lat,
			Star:  1,
		}

		res, err := goreq.Request{
			Uri:         "http://www.streetdirectory.com/api/map/world.cgi",
			QueryString: qs,
			Compression: goreq.Gzip(),
		}.Do()
		if err != nil {
			return nil, err
		}

		data, err := res.Body.ToString()
		if err != nil {
			return nil, err
		}

		err = ioutil.WriteFile(filepath, []byte(data), 0644)
		if err != nil {
			return nil, err
		}
	}

	file, err := telebot.NewFile(filepath)
	if err != nil {
		return nil, err
	}

	thumbnail := telebot.Thumbnail{
		File:   file,
		Width:  500,
		Height: 500,
	}

	photo := telebot.Photo{
		Thumbnail: thumbnail,
		Caption:   location.Name,
	}

	return &photo, nil
}
Esempio n. 6
0
func (a *Action) execute(b *Bot) {

	n := len(a.Templates)
	answer := b.SentenceFromTemplate(a.Templates[rand.Intn(n)])
	if strings.HasSuffix(answer, ".ogg") {
		file, _ := telebot.NewFile(answer)
		audio := telebot.Audio{File: file}
		b.SendAudio(b.LastMessage.Chat, &audio, nil)
	} else {
		b.SendMessage(b.LastMessage.Chat, answer, nil)
	}

}
Esempio n. 7
0
func (h *Herald) GetOutput(m telebot.Message) error {
	file, err := telebot.NewFile("/var/log/pacman.log")
	if err != nil {
		return nil
	}

	document := &telebot.Document{
		File:     file,
		FileName: "pacman.log",
	}

	return h.bot.SendDocument(m.Chat, document, nil)
}
Esempio n. 8
0
File: bot.go Progetto: Kimau/GoCam
func (b *Cambot) ProceessMessage() {

	replySendOpt := telebot.SendOptions{
		ParseMode: telebot.ModeMarkdown,
		ReplyMarkup: telebot.ReplyMarkup{
			ForceReply:      true,
			CustomKeyboard:  [][]string{{"/hi"}},
			OneTimeKeyboard: false,
			ResizeKeyboard:  true,
		}}

messageLoop:
	for {
		message, ok := <-b.messages
		if !ok {
			return
		}

		if !checkAuth(message.Sender.ID) {
			text := fmt.Sprintf("Sorry %s BITCH! You are not my boss. Your ID is %d", message.Sender.FirstName, message.Sender.ID)
			b.bot.SendMessage(message.Chat, text, nil)
			continue
		}

		replySendOpt.ReplyMarkup.CustomKeyboard = [][]string{{"hi"}, b.camNames}

		if message.Text == "hi" {
			text := fmt.Sprintf("Hello %s your id is %d", message.Sender.FirstName, message.Sender.ID)
			b.bot.SendMessage(message.Chat, text, &replySendOpt)
		}

		for i, camName := range b.camNames {
			if message.Text == camName {
				fn := <-b.camFeeds[i]
				photofile, _ := telebot.NewFile(fn)
				photo := telebot.Photo{File: photofile}
				_ = b.bot.SendPhoto(message.Chat, &photo, &replySendOpt)
				continue messageLoop
			}
		}

		b.bot.SendMessage(message.Chat, "Say *hi*", &replySendOpt)
	}
}
Esempio n. 9
0
// sendFileWrapper checks if the file exists and writes it before returning the response function.
func (j *JarvisBot) sendFileWrapper(assetName string, filetype string) (ResponseFunc, error) {
	pwd, err := osext.ExecutableFolder()
	if err != nil {
		j.log.Printf("error retrieving pwd: %s", err)
	}

	_, filename := path.Split(assetName)
	filePath := path.Join(pwd, TEMPDIR, filename)
	// Check if file exists, if it doesn't exist, create it
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		fileData, err := Asset(assetName)
		if err != nil {
			err = fmt.Errorf("error retrieving asset %s: %s", assetName, err)
			return nil, err
		}
		err = ioutil.WriteFile(filePath, fileData, 0775)
		if err != nil {
			err = fmt.Errorf("error creating %s: %s", assetName, err)
			return nil, err
		}
	}

	return func(msg *message) {
		file, err := telebot.NewFile(filePath)
		if err != nil {
			j.log.Printf("error reading %s: %s", filePath, err)
			return
		}

		if filetype == "ogg" {
			j.bot.SendAudio(msg.Chat, &telebot.Audio{File: file, Mime: "audio/ogg"}, nil)
		} else if filetype == "photo" {
			j.bot.SendPhoto(msg.Chat, &telebot.Photo{Thumbnail: telebot.Thumbnail{File: file}}, nil)
		}
	}, nil
}
Esempio n. 10
0
// sendPhotoFromURL is a helper function to send a photo from a URL to a chat.
// Photos are temporarily stored in a temp folder in the same directory, and
// are deleted after being sent to Telegram.
func (j *JarvisBot) sendPhotoFromURL(url *url.URL, msg *message) {
	errSO := &telebot.SendOptions{ReplyTo: *msg.Message}

	urlPath := strings.Split(url.Path, "/")
	imgName := urlPath[len(urlPath)-1]
	ext := strings.ToLower(path.Ext(imgName))

	// If the URL doesn't end with a valid image filename, stop.
	if ext != ".jpg" && ext != ".png" && ext != ".jpeg" && ext != ".gif" {
		j.log.Printf("[%s] invalid image filename: %s", time.Now().Format(time.RFC3339), ext)
		j.SendMessage(msg.Chat, "I got an image with an invalid image extension, I'm afraid: "+url.String(), errSO)
		return
	}

	j.bot.SendChatAction(msg.Chat, telebot.UploadingPhoto)
	resp, err := http.Get(url.String())
	if err != nil {
		j.log.Printf("[%s] error retrieving image:\n%s", time.Now().Format(time.RFC3339), err)
		j.SendMessage(msg.Chat, "I encountered a problem when retrieving the image: "+url.String(), errSO)

		return
	}
	defer resp.Body.Close()

	// 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 {
		j.log.Printf("error grabbing pwd \n%s", err)
		return
	}

	// Test if temporary directory exists
	// If it doesn't exist, create it.
	tmpDirPath := filepath.Join(pwd, TEMPDIR)
	if _, err := os.Stat(tmpDirPath); os.IsNotExist(err) {
		j.log.Printf("[%s] creating temporary directory", time.Now().Format(time.RFC3339))
		mkErr := os.Mkdir(tmpDirPath, 0775)
		if mkErr != nil {
			j.log.Printf("[%s] error creating temporary directory\n%s", time.Now().Format(time.RFC3339), err)
			return
		}
	}

	// We generate a random uuid to prevent race conditions
	imgFilePath := filepath.Join(tmpDirPath, uuid.NewV4().String()+ext)
	file, err := os.Create(imgFilePath)
	if err != nil {
		j.log.Printf("error creating image file")
		return
	}
	defer func() {
		err := file.Close()
		if err != nil {
			j.log.Printf("error closing file: %s", err)
		}
		err = os.Remove(imgFilePath)
		if err != nil {
			j.log.Printf("error removing %s: %s", imgFilePath, err)
		}
	}()

	// io.Copy supports copying large files.
	_, err = io.Copy(file, resp.Body)
	if err != nil {
		j.log.Printf("error writing request body to file: %s", err)
		return
	}

	tFile, err := telebot.NewFile(imgFilePath)
	if err != nil {
		j.log.Printf("error creating new Telebot file: %s", err)
		return
	}

	if ext == ".gif" {
		j.bot.SendChatAction(msg.Chat, telebot.UploadingPhoto)
		doc := &telebot.Document{File: tFile, Preview: telebot.Thumbnail{File: tFile}, Mime: "image/gif"}
		j.bot.SendDocument(msg.Chat, doc, nil)
	} else {
		photo := &telebot.Photo{Thumbnail: telebot.Thumbnail{File: tFile}}
		err := j.bot.SendPhoto(msg.Chat, photo, nil)
		if err != nil {
			j.log.Printf("[%s] error sending picture: %s", time.Now().Format(time.RFC3339), err.Error())
		}
	}
}
Esempio n. 11
0
// sendFileWrapper checks if the file exists and writes it before returning the response function.
func (j *JarvisBot) sendFileWrapper(assetName string, filetype string) (ResponseFunc, error) {

	fileId, err := j.getCachedFileID(assetName)
	if err != nil {
		j.log.Printf("error retreiving cached file_id for %s", assetName)
	}

	if fileId != "" {
		file := telebot.File{FileID: fileId}

		return func(msg *message) {
			if filetype == "ogg" {
				audio := telebot.Audio{File: file, Mime: "audio/ogg"}
				j.bot.SendAudio(msg.Chat, &audio, nil)
			} else if filetype == "photo" {
				photo := telebot.Photo{File: file}
				j.bot.SendPhoto(msg.Chat, &photo, nil)
			} else if filetype == "gif" {
				doc := telebot.Document{File: file, Mime: "image/gif"}
				j.bot.SendDocument(msg.Chat, &doc, nil)
			}
		}, nil
	} else {

		pwd, err := osext.ExecutableFolder()
		if err != nil {
			j.log.Printf("error retrieving pwd: %s", err)
		}

		_, filename := path.Split(assetName)
		filePath := path.Join(pwd, tempDir, filename)
		// Check if file exists, if it doesn't exist, create it
		if _, err := os.Stat(filePath); os.IsNotExist(err) {
			fileData, err := Asset(assetName)
			if err != nil {
				err = fmt.Errorf("error retrieving asset %s: %s", assetName, err)
				return nil, err
			}
			err = ioutil.WriteFile(filePath, fileData, 0775)
			if err != nil {
				err = fmt.Errorf("error creating %s: %s", assetName, err)
				return nil, err
			}
		}

		return func(msg *message) {
			file, err := telebot.NewFile(filePath)
			if err != nil {
				j.log.Printf("error reading %s: %s", filePath, err)
				return
			}

			var newFileId string
			if filetype == "ogg" {
				audio := telebot.Audio{File: file, Mime: "audio/ogg"}
				j.bot.SendAudio(msg.Chat, &audio, nil)
				newFileId = audio.FileID
			} else if filetype == "photo" {
				photo := telebot.Photo{File: file, Thumbnail: telebot.Thumbnail{File: file}}
				j.bot.SendPhoto(msg.Chat, &photo, nil)
				newFileId = photo.FileID
			} else if filetype == "gif" {
				doc := telebot.Document{File: file, Preview: telebot.Thumbnail{File: file}, Mime: "image/gif"}
				j.bot.SendDocument(msg.Chat, &doc, nil)
				newFileId = doc.FileID
			}
			err = j.cacheFileID(assetName, newFileId)
			if err != nil {
				j.log.Println("error caching file_id '%s' for '%s': %s", fileId, assetName, err)
			}
		}, nil

	}

}