コード例 #1
0
ファイル: metafora.go プロジェクト: Hamcha/clessy
func metafora(broker *tg.Broker, update tg.APIMessage) {
	if isCommand(update, "metafora") {
		n := rand.Intn(len(actions))
		m := rand.Intn(len(objects))
		broker.SendTextMessage(update.Chat, actions[n]+" "+objects[m], nil)
		return
	}
}
コード例 #2
0
ファイル: viaggi.go プロジェクト: Hamcha/clessy
func viaggi(broker *tg.Broker, update tg.APIMessage) {
	if isCommand(update, "viaggi") {
		usage := func() {
			broker.SendTextMessage(update.Chat, "Formato: /viaggi <i>&lt;PARTENZA&gt;</i> -> <i>&lt;DESTINAZIONE&gt;</i>", &update.MessageID)
		}
		oops := func(err error) {
			log.Println("[viaggi] GET error:" + err.Error())
			broker.SendTextMessage(update.Chat, "<b>ERRORE!</b> @hamcha controlla la console!", &update.MessageID)
		}

		parts := strings.SplitN(*(update.Text), " ", 2)
		if len(parts) < 2 {
			usage()
			return
		}
		text := parts[1]
		msgs := reg.FindStringSubmatch(text)
		if len(msgs) <= 2 {
			usage()
			return
		}

		msgs[1] = strings.Replace(msgs[1], ",", "", -1)
		msgs[1] = strings.Replace(msgs[1], " ", "-", -1)
		msgs[2] = strings.Replace(msgs[2], ",", "", -1)
		msgs[2] = strings.Replace(msgs[2], " ", "-", -1)
		src := url.QueryEscape(msgs[1])
		dst := url.QueryEscape(msgs[2])
		url := viaggiurl + "&oName=" + src + "&dName=" + dst
		resp, err := http.Get(url)
		if err != nil {
			oops(err)
			return
		}
		defer resp.Body.Close()

		var outjson Romejson
		err = json.NewDecoder(resp.Body).Decode(&outjson)
		if err != nil {
			broker.SendTextMessage(update.Chat, "Hm, Rome2rio non ha trovato nulla, mi spiace :(\nForse non hai scritto bene uno dei due posti?", &update.MessageID)
			return
		}

		var moreeco Romeroute
		var lesstim Romeroute
		if len(outjson.Routes) < 1 {
			// Should never happen
			log.Println("[viaggi] No routes found (??)")
			broker.SendTextMessage(update.Chat, "<b>ERRORE!</b> @hamcha controlla la console!", &update.MessageID)
			return
		}

		// Calculate cheapest and fastest
		moreeco = outjson.Routes[0]
		lesstim = outjson.Routes[0]
		for _, v := range outjson.Routes {
			if v.IndicativePrice.Price < moreeco.IndicativePrice.Price {
				moreeco = v
			}
			if v.Duration < lesstim.Duration {
				lesstim = v
			}
		}

		broker.SendTextMessage(update.Chat,
			"Viaggio da <b>"+outjson.Places[0].Name+
				"</b> a <b>"+outjson.Places[1].Name+"</b>"+
				"\n\n"+
				"Piu economico: <b>"+moreeco.Name+"</b> ("+parseData(moreeco)+")"+
				"\n"+
				"Piu veloce: <b>"+lesstim.Name+"</b> ("+parseData(lesstim)+")"+
				"\n\n"+
				"<a href=\"http://www.rome2rio.com/it/s/"+src+"/"+dst+"\">Maggiori informazioni</a>",
			&update.MessageID)
	}
}
コード例 #3
0
ファイル: memegen.go プロジェクト: Hamcha/clessy
func memegen(broker *tg.Broker, update tg.APIMessage) {
	// Make replies work
	if update.ReplyTo != nil && update.Text != nil && update.ReplyTo.Photo != nil {
		update.Photo = update.ReplyTo.Photo
		update.Caption = update.Text
	}

	if update.Photo != nil && update.Caption != nil {
		caption := *(update.Caption)
		if strings.HasPrefix(caption, "/meme ") && len(caption) > 6 {
			idx := strings.Index(caption, ";")
			if idx < 0 {
				broker.SendTextMessage(update.Chat, "<b>Formato</b>: /meme TESTO IN ALTO<b>;</b>TESTO IN BASSO", &update.MessageID)
				return
			}

			txtup := caption[6:idx]
			txtdw := caption[idx+1:]

			maxsz := 0
			photo := tg.APIPhotoSize{}
			for _, curphoto := range update.Photo {
				if curphoto.Width > maxsz {
					maxsz = curphoto.Width
					photo = curphoto
				}
			}

			broker.GetFile(photo.FileID, func(broker *tg.Broker, data tg.BrokerUpdate) {
				if data.Type == tg.BError {
					log.Println("[memegen] Received error from broker: %s\n", *data.Error)
					broker.SendTextMessage(update.Chat, "<b>ERRORE!</b> @hamcha controlla la console!", &update.MessageID)
					return
				}

				pbytes, err := base64.StdEncoding.DecodeString(*data.Bytes)
				if err != nil {
					log.Println("[memegen] Base64 decode error: %s\n", err.Error())
					broker.SendTextMessage(update.Chat, "<b>ERRORE!</b> @hamcha controlla la console!", &update.MessageID)
					return
				}

				img, _, err := image.Decode(bytes.NewReader(pbytes))
				if err != nil {
					log.Println("[memegen] Image decode error: %s\n", err.Error())
					broker.SendTextMessage(update.Chat, "<b>ERROR</b>: Non riesco a leggere l'immagine", &update.MessageID)
					return
				}

				//TODO Clean up this mess

				// Create target image
				bounds := img.Bounds()
				iwidth := float64(bounds.Size().X)
				iheight := float64(bounds.Size().Y)

				timg := image.NewRGBA(bounds)
				gc := draw2dimg.NewGraphicContext(timg)
				gc.SetStrokeColor(image.Black)
				gc.SetFillColor(image.White)
				gc.SetFontData(memeFontData)
				gc.DrawImage(img)

				write := func(text string, istop bool) {
					text = strings.ToUpper(strings.TrimSpace(text))
					gc.Restore()
					gc.Save()

					// Detect appropriate font size
					scale := iheight / iwidth * (iwidth / 10)
					gc.SetFontSize(scale)
					gc.SetLineWidth(scale / 15)

					// Get NEW bounds
					left, top, right, bottom := gc.GetStringBounds(text)

					width := right - left
					texts := []string{text}
					if width > iwidth {
						// Split text
						texts = splitCenter(text)

						// Get longest line
						longer := float64(0)
						longid := 0
						widths := make([]float64, len(texts))
						for id := range texts {
							tleft, _, tright, _ := gc.GetStringBounds(texts[id])
							widths[id] = tright - tleft
							if width > longer {
								longer = widths[id]
								longid = id
							}
						}

						// Still too big? Decrease font size again
						iter := 0
						for width > iwidth && iter < 10 {
							log.Println("Warning, resizing!")
							gc.SetFontSize(scale * (0.8 - 0.1*float64(iter)))
							left, top, right, bottom = gc.GetStringBounds(texts[longid])
							width = right - left
							iter++
						}
					}

					height := bottom - top
					margin := float64(height / 50)
					lines := float64(len(texts) - 1)

					gc.Save()
					for id, txt := range texts {
						gc.Save()
						left, _, right, _ = gc.GetStringBounds(txt)
						width = right - left

						y := float64(0)
						if istop {
							y = (height+margin)*float64(id+1) + margin*5
						} else {
							y = iheight - (height * lines) + (height * float64(id)) - margin*5
						}

						gc.Translate((iwidth-width)/2, y)
						gc.StrokeString(txt)
						gc.FillString(txt)
						gc.Restore()
					}
				}
				write(txtup, true)
				write(txtdw, false)

				buf := new(bytes.Buffer)
				err = jpeg.Encode(buf, timg, &(jpeg.Options{Quality: 80}))
				if err != nil {
					log.Println("[memegen] Image encode error: %s\n", err.Error())
					broker.SendTextMessage(update.Chat, "<b>ERRORE!</b> @hamcha controlla la console!", &update.MessageID)
					return
				}
				broker.SendPhoto(update.Chat, buf.Bytes(), "meme.jpg", "", &update.MessageID)
			})
		}
	}
}
コード例 #4
0
ファイル: unsplash.go プロジェクト: Hamcha/clessy
func unsplash(broker *tg.Broker, update tg.APIMessage) {
	if isCommand(update, "unsplash") {
		text := ""
		user := update.User

		if update.ReplyTo != nil {
			if update.ReplyTo.Text == nil {
				broker.SendTextMessage(update.Chat, "Non c'e' niente di 'ispiratore' in questo..", &update.MessageID)
				return
			}
			text = *(update.ReplyTo.Text)
			user = update.ReplyTo.User
		} else {
			if strings.Index(*(update.Text), " ") > 0 {
				text = strings.TrimSpace(strings.SplitN(*(update.Text), " ", 2)[1])
			}
		}

		author := user.FirstName
		if user.LastName != "" {
			author = user.FirstName + " " + user.LastName
		}
		author += " (" + user.Username + ")"

		if strings.TrimSpace(text) == "" {
			broker.SendTextMessage(update.Chat, "Non c'e' niente di 'ispiratore' in questo..", &update.MessageID)
			return
		}

		resp, err := http.Get(unsplashUrl)
		if err != nil {
			log.Println("[unsplash] HTTP request failed: %s\n", err.Error())
			broker.SendTextMessage(update.Chat, "<b>ERRORE!</b> @hamcha controlla la console!", &update.MessageID)
			return
		}
		defer resp.Body.Close()

		img, _, err := image.Decode(resp.Body)
		if err != nil {
			log.Println("[unsplash] Image decode error: %s\n", err.Error())
			broker.SendTextMessage(update.Chat, "<b>ERRORE</b>: Non riesco a leggere l'immagine", &update.MessageID)
			return
		}

		// Darken image
		img = imaging.AdjustBrightness(imaging.AdjustGamma(imaging.AdjustSigmoid(img, 0.5, -6.0), 0.8), -20)

		// Create target image
		bounds := img.Bounds()
		iwidth := float64(bounds.Size().X)
		iheight := float64(bounds.Size().Y)

		timg := image.NewRGBA(bounds)
		gc := draw2dimg.NewGraphicContext(timg)
		gc.SetFontData(quoteFontData)
		gc.DrawImage(img)
		gc.SetStrokeColor(image.Black)
		gc.SetFillColor(image.White)

		text = strings.ToUpper(strings.TrimSpace(text))
		gc.Restore()
		gc.Save()

		// Detect appropriate font size
		scale := iheight / iwidth * (iwidth / 10) * 0.8
		gc.SetFontSize(scale)
		gc.SetLineWidth(scale / 15)

		// Get NEW bounds
		left, top, right, bottom := gc.GetStringBounds(text)

		width := right - left
		texts := []string{text}
		if width*1.2 > iwidth {
			// Split text
			texts = splitCenter(text)

			// Get longest line
			longer := float64(0)
			longid := 0
			widths := make([]float64, len(texts))
			for id := range texts {
				tleft, _, tright, _ := gc.GetStringBounds(texts[id])
				widths[id] = tright - tleft
				if width > longer {
					longer = widths[id]
					longid = id
				}
			}

			// Still too big? Decrease font size again
			iter := 0
			for width*1.2 > iwidth && iter < 10 {
				log.Println("Warning, resizing!")
				scale *= (0.9 - 0.05*float64(iter))
				gc.SetFontSize(scale)
				left, top, right, bottom = gc.GetStringBounds(texts[longid])
				width = right - left
				iter++
			}
		}

		texts = append(texts, author)
		height := bottom - top + 20
		margin := float64(height / 50)
		txtheight := (height + margin) * float64(len(texts))

		gc.Save()
		for id, txt := range texts {
			gc.Save()
			left, _, right, _ = gc.GetStringBounds(txt)
			width = right - left

			x := (iwidth - width) / 2
			y := (iheight-txtheight)/2 + (height+margin*2)*float64(id+1)
			if id == len(texts)-1 {
				gc.SetFontSize(scale * 0.7)
				left, _, right, _ = gc.GetStringBounds(txt)
				width = right - left
				x = (iwidth - width) / 1.5
				y = (iheight-txtheight)/2 + (height+margin)*float64(id+1) + margin*6
			}

			gc.Translate(x, y)
			gc.StrokeString(txt)
			gc.FillString(txt)
			gc.Restore()
		}

		buf := new(bytes.Buffer)
		err = jpeg.Encode(buf, timg, &(jpeg.Options{Quality: 80}))
		if err != nil {
			log.Println("[unsplash] Image encode error: %s\n", err.Error())
			broker.SendTextMessage(update.Chat, "<b>ERRORE!</b> @hamcha controlla la console!", &update.MessageID)
			return
		}
		broker.SendPhoto(update.Chat, buf.Bytes(), "quote.jpg", "", &update.MessageID)
	}
}