Example #1
0
func main() {
	flag.Parse()

	var client *maps.Client
	var err error
	if *apiKey != "" {
		client, err = maps.NewClient(maps.WithAPIKey(*apiKey))
	} else if *clientID != "" || *signature != "" {
		client, err = maps.NewClient(maps.WithClientIDAndSignature(*clientID, *signature))
	} else {
		usageAndExit("Please specify an API Key, or Client ID and Signature.")
	}
	check(err)

	r := &maps.QueryAutocompleteRequest{
		Input:    *input,
		Language: *language,
		Radius:   *radius,
		Offset:   *offset,
	}

	parseLocation(*location, r)

	resp, err := client.QueryAutocomplete(context.Background(), r)
	check(err)

	pretty.Println(resp)
}
func main() {
	flag.Parse()

	var client *maps.Client
	var err error
	if *apiKey != "" {
		client, err = maps.NewClient(maps.WithAPIKey(*apiKey))
	} else if *clientID != "" || *signature != "" {
		client, err = maps.NewClient(maps.WithClientIDAndSignature(*clientID, *signature))
	} else {
		usageAndExit("Please specify an API Key, or Client ID and Signature.")
	}
	check(err)

	r := &maps.NearbySearchRequest{
		Radius:    *radius,
		Keyword:   *keyword,
		Language:  *language,
		Name:      *name,
		OpenNow:   *openNow,
		PageToken: *pageToken,
	}

	parseLocation(*location, r)
	parsePriceLevels(*minPrice, *maxPrice, r)
	parseRankBy(*rankBy, r)
	parsePlaceType(*placeType, r)

	resp, err := client.NearbySearch(context.Background(), r)
	check(err)

	pretty.Println(resp)
}
Example #3
0
func main() {
	flag.Parse()

	var client *maps.Client
	var err error
	if *apiKey != "" {
		client, err = maps.NewClient(maps.WithAPIKey(*apiKey))
	} else if *clientID != "" || *signature != "" {
		client, err = maps.NewClient(maps.WithClientIDAndSignature(*clientID, *signature))
	} else {
		usageAndExit("Please specify an API Key, or Client ID and Signature.")
	}
	check(err)

	r := &maps.GeocodingRequest{
		Address:  *address,
		Language: *language,
		Region:   *region,
	}

	parseComponents(*components, r)
	parseBounds(*bounds, r)
	parseLatLng(*latlng, r)
	parseResultType(*resultType, r)
	parseLocationType(*locationType, r)

	resp, err := client.Geocode(context.Background(), r)
	check(err)

	pretty.Println(resp)
}
Example #4
0
func NewGoogleClient() (GoogleClient, error) {
	c, err := maps.NewClient(maps.WithAPIKey(os.Getenv("GOOGLE_API_KEY")))

	return GoogleClient{
		Client: c,
	}, err
}
Example #5
0
func main() {
	flag.Parse()
	if *apiKey == "" {
		usageAndExit("Please specify an API Key.")
	}
	client, err := maps.NewClient(maps.WithAPIKey(*apiKey))
	if err != nil {
		log.Fatalf("error %v", err)
	}
	r := &maps.SpeedLimitsRequest{}

	if *units == "KPH" {
		r.Units = maps.SpeedLimitKPH
	}
	if *units == "MPH" {
		r.Units = maps.SpeedLimitMPH
	}

	if *path == "" && *placeIDs == "" {
		usageAndExit("Please specify either a path to be snapped, or a list of Place IDs.")
	}
	parsePath(*path, r)
	parsePlaceIDs(*placeIDs, r)

	resp, err := client.SpeedLimits(context.Background(), r)
	if err != nil {
		log.Fatalf("error %v", err)
	}

	pretty.Println(resp)
}
func main() {
	flag.Parse()

	var client *maps.Client
	var err error
	if *apiKey != "" {
		client, err = maps.NewClient(maps.WithAPIKey(*apiKey))
	} else if *clientID != "" || *signature != "" {
		client, err = maps.NewClient(maps.WithClientIDAndSignature(*clientID, *signature))
	} else {
		usageAndExit("Please specify an API Key, or Client ID and Signature.")
	}
	check(err)

	r := &maps.TextSearchRequest{
		Query:    *query,
		Language: *language,
		Radius:   *radius,
		OpenNow:  *opennow,
	}

	parseLocation(*location, r)
	parsePriceLevels(*minprice, *maxprice, r)
	parsePlaceType(*placeType, r)

	resp, err := client.TextSearch(context.Background(), r)
	check(err)

	pretty.Println(resp)
}
Example #7
0
func main() {
	flag.Parse()

	var client *maps.Client
	var err error
	if *apiKey != "" {
		client, err = maps.NewClient(maps.WithAPIKey(*apiKey))
	} else if *clientID != "" || *signature != "" {
		client, err = maps.NewClient(maps.WithClientIDAndSignature(*clientID, *signature))
	} else {
		usageAndExit("Please specify an API Key, or Client ID and Signature.")
	}
	check(err)

	t, err := strconv.Atoi(*timestamp)
	check(err)

	r := &maps.TimezoneRequest{
		Language:  *language,
		Timestamp: time.Unix(int64(t), 0),
	}

	parseLocation(*location, r)

	resp, err := client.Timezone(context.Background(), r)
	check(err)

	pretty.Println(resp)
}
Example #8
0
func botGeocode(location string) string {
	c, err := maps.NewClient(maps.WithAPIKey(os.Getenv("GOOGLE_API")))
	if err != nil {
		log.Fatalf("fatal error: %s", err)
	}
	l := stripTag("where", location)
	gr := &maps.GeocodingRequest{
		Address: l,
	}
	gresp, err := c.Geocode(context.Background(), gr)

	addr := gresp[0].FormattedAddress
	coords := gresp[0].Geometry.Location.String()

	return fmt.Sprintf("%s (%s)", addr, coords)
}
Example #9
0
func botDirection(from string, to string) string {
	c, err := maps.NewClient(maps.WithAPIKey(os.Getenv("GOOGLE_API")))
	if err != nil {
		log.Fatalf("fatal error: %s", err)
	}

	dr := &maps.DirectionsRequest{
		Origin:      from,
		Destination: to,
	}

	dresp, _, err := c.Directions(context.Background(), dr)
	if err != nil {
		log.Fatalf("fatal error: %s", err)
	}

	pretty.Println(dresp)
	return fmt.Sprintf("Come back later for _'%s -> %s'_ directions", from, to)
}
Example #10
0
func main() {
	flag.Parse()
	if len(*apiKey) == 0 {
		log.Fatal("-key is required")
	}
	c, err := maps.NewClient(maps.WithAPIKey(*apiKey))
	if err != nil {
		log.Fatalf("fatal error: %s", err)
	}

	if *scrape {
		if err := scrapeBuildings(); err != nil {
			log.Fatal(err)
		}
	}
	if *geocode {
		if err := geocodeBuildings(c); err != nil {
			log.Fatal(err)
		}
	}
}
Example #11
0
func main() {
	flag.Parse()
	if *apiKey == "" {
		usageAndExit("Please specify an API Key.")
	}
	client, err := maps.NewClient(maps.WithAPIKey(*apiKey))
	check(err)
	r := &maps.SnapToRoadRequest{
		Interpolate: *interpolate,
	}

	if *path == "" {
		usageAndExit("Please specify a path to be snapped.")
	}
	parsePath(*path, r)

	resp, err := client.SnapToRoad(context.Background(), r)
	check(err)

	pretty.Println(resp)
}
Example #12
0
func botWeather(location string) string {
	weatherURL := "http://api.openweathermap.org/data/2.5/forecast"

	l := stripTag("weather", location)
	if l == "" {
		return "New York"
	}

	c, err := maps.NewClient(maps.WithAPIKey(os.Getenv("GOOGLE_API")))
	gr := &maps.GeocodingRequest{Address: l}
	gresp, err := c.Geocode(context.Background(), gr)
	coords := gresp[0].Geometry.Location

	// http://www.openweathermap.com/forecast5#parameter
	params := map[string]string{
		"lat":   fmt.Sprintf("%g", coords.Lat),
		"lon":   fmt.Sprintf("%g", coords.Lng),
		"units": "metric", // "imperial"
		"lang":  "en",
		"cnt":   "3",
		"mode":  "json",
		"appid": os.Getenv("OPENWEATHERMAP_API_KEY"),
		"type":  "like"}
	resp, err := resty.
		R().
		SetQueryParams(params).
		SetHeader("Accept", "application/json").Get(weatherURL)

	if err != nil {
		log.Fatal(err)
	}

	var wResp weatherResponse
	err = json.Unmarshal(resp.Body(), &wResp)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s", err.Error())
		return resp.String()
	}
	return wResp.String()
}
Example #13
0
func main() {
	flag.Parse()

	var client *maps.Client
	var err error
	if *apiKey != "" {
		client, err = maps.NewClient(maps.WithAPIKey(*apiKey))
	} else if *clientID != "" || *signature != "" {
		client, err = maps.NewClient(maps.WithClientIDAndSignature(*clientID, *signature))
	} else {
		usageAndExit("Please specify an API Key, or Client ID and Signature.")
	}
	check(err)

	r := &maps.ElevationRequest{}

	if *samples > 0 {
		r.Samples = *samples
	}

	if *locations != "" {
		l, err := decodeLocations(*locations)
		check(err)
		r.Locations = l
	}

	if *path != "" {
		p, err := decodePath(*path)
		check(err)
		r.Path = p
	}

	resp, err := client.Elevation(context.Background(), r)
	if err != nil {
		log.Fatalf("Could not request elevations: %v", err)
	}

	pretty.Println(resp)
}
Example #14
0
func main() {
	flag.Parse()

	var client *maps.Client
	var err error
	if *apiKey != "" {
		client, err = maps.NewClient(maps.WithAPIKey(*apiKey))
	} else if *clientID != "" || *signature != "" {
		client, err = maps.NewClient(maps.WithClientIDAndSignature(*clientID, *signature))
	} else {
		usageAndExit("Please specify an API Key, or Client ID and Signature.")
	}
	check(err)

	r := &maps.PlacePhotoRequest{
		PhotoReference: *photoreference,
		MaxHeight:      uint(*maxheight),
		MaxWidth:       uint(*maxwidth),
	}

	resp, err := client.PlacePhoto(context.Background(), r)
	check(err)

	log.Printf("Content-Type: %v\n", resp.ContentType)
	img, err := resp.Image()
	check(err)
	log.Printf("Image bounds: %v", img.Bounds())

	if *basename != "" {
		filename := fmt.Sprintf("%s.%s", *basename, "jpg")
		f, err := os.Create(filename)
		check(err)
		err = jpeg.Encode(f, img, &jpeg.Options{Quality: 85})
		check(err)

		log.Printf("Wrote image to %s\n", filename)
	}
}
func main() {
	flag.Parse()

	var client *maps.Client
	var err error
	if *apiKey != "" {
		client, err = maps.NewClient(maps.WithAPIKey(*apiKey))
	} else if *clientID != "" || *signature != "" {
		client, err = maps.NewClient(maps.WithClientIDAndSignature(*clientID, *signature))
	} else {
		usageAndExit("Please specify an API Key, or Client ID and Signature.")
	}
	check(err)

	r := &maps.RadarSearchRequest{
		Radius:  *radius,
		Keyword: *keyword,
		Name:    *name,
		OpenNow: *opennow,
	}

	parseLocation(*location, r)
	parsePriceLevels(*minprice, *maxprice, r)
	parsePlaceType(*placeType, r)

	resp, err := client.RadarSearch(context.Background(), r)
	check(err)

	for i, result := range resp.Results {
		r2 := &maps.PlaceDetailsRequest{
			PlaceID: result.PlaceID,
		}
		resp, err := client.PlaceDetails(context.Background(), r2)
		check(err)

		fmt.Printf("%d: %v at %v\n", i, resp.Name, resp.FormattedAddress)
	}
}
Example #16
0
func main() {
	flag.Parse()

	var client *maps.Client
	var err error
	if *apiKey != "" {
		client, err = maps.NewClient(maps.WithAPIKey(*apiKey))
	} else if *clientID != "" || *signature != "" {
		client, err = maps.NewClient(maps.WithClientIDAndSignature(*clientID, *signature))
	} else {
		usageAndExit("Please specify an API Key, or Client ID and Signature.")
	}
	check(err)

	r := &maps.DistanceMatrixRequest{
		Language:      *language,
		DepartureTime: *departureTime,
		ArrivalTime:   *arrivalTime,
	}

	if *origins != "" {
		r.Origins = strings.Split(*origins, "|")
	}
	if *destinations != "" {
		r.Destinations = strings.Split(*destinations, "|")
	}

	lookupMode(*mode, r)
	lookupAvoid(*avoid, r)
	lookupUnits(*units, r)
	lookupTransitMode(*transitMode, r)
	lookupTransitRoutingPreference(*transitRoutingPreference, r)

	resp, err := client.DistanceMatrix(context.Background(), r)
	check(err)

	pretty.Println(resp)
}
Example #17
0
func main() {
	flag.Parse()

	var client *maps.Client
	var err error
	if *apiKey != "" {
		client, err = maps.NewClient(maps.WithAPIKey(*apiKey))
	} else if *clientID != "" || *signature != "" {
		client, err = maps.NewClient(maps.WithClientIDAndSignature(*clientID, *signature))
	} else {
		usageAndExit("Please specify an API Key, or Client ID and Signature.")
	}
	check(err)

	r := &maps.PlaceDetailsRequest{
		PlaceID: *placeID,
	}

	resp, err := client.PlaceDetails(context.Background(), r)
	check(err)

	pretty.Println(resp)
}
Example #18
0
func botTime(location string) string {
	l := stripTag("time", location)
	if l == "" {
		return time.Now().Format(time.RFC850)
	}

	c, err := maps.NewClient(maps.WithAPIKey(os.Getenv("GOOGLE_API")))
	gr := &maps.GeocodingRequest{
		Address: l,
	}
	gresp, err := c.Geocode(context.Background(), gr)
	coords := gresp[0].Geometry.Location
	r := &maps.TimezoneRequest{
		Location: &maps.LatLng{
			Lat: coords.Lat,
			Lng: coords.Lng,
		},
		Timestamp: time.Now().UTC(),
	}

	resp, err := c.Timezone(context.Background(), r)

	if err != nil {
		return fmt.Sprintf("r.Get returned non nil error: %v", err)
	}

	utc, err := time.LoadLocation(resp.TimeZoneID)
	if err != nil {
		return fmt.Sprintf("%s returned non nil error: %v", resp.TimeZoneID, err)
	}

	return fmt.Sprintf("Location: %s Time: %s\nLocation: '%s' Time: %s",
		time.Now().Location(),
		time.Now().Local(),
		utc.String(),
		time.Now().In(utc))
}
Example #19
0
func main() {
	flag.Parse()

	var client *maps.Client
	var err error
	if *apiKey != "" {
		client, err = maps.NewClient(maps.WithAPIKey(*apiKey), maps.WithRateLimit(2))
	} else if *clientID != "" || *signature != "" {
		client, err = maps.NewClient(maps.WithClientIDAndSignature(*clientID, *signature))
	} else {
		usageAndExit("Please specify an API Key, or Client ID and Signature.")
	}
	check(err)

	r := &maps.DirectionsRequest{
		Origin:        *origin,
		Destination:   *destination,
		DepartureTime: *departureTime,
		ArrivalTime:   *arrivalTime,
		Alternatives:  *alternatives,
		Language:      *language,
		Region:        *region,
	}

	lookupMode(*mode, r)
	lookupUnits(*units, r)
	lookupTransitRoutingPreference(*transitRoutingPreference, r)
	lookupTrafficModel(*trafficModel, r)

	if *waypoints != "" {
		r.Waypoints = strings.Split(*waypoints, "|")
	}

	if *avoid != "" {
		for _, a := range strings.Split(*avoid, "|") {
			switch a {
			case "tolls":
				r.Avoid = append(r.Avoid, maps.AvoidTolls)
			case "highways":
				r.Avoid = append(r.Avoid, maps.AvoidHighways)
			case "ferries":
				r.Avoid = append(r.Avoid, maps.AvoidFerries)
			default:
				log.Fatalf("Unknown avoid restriction %s", a)
			}
		}
	}
	if *transitMode != "" {
		for _, t := range strings.Split(*transitMode, "|") {
			switch t {
			case "bus":
				r.TransitMode = append(r.TransitMode, maps.TransitModeBus)
			case "subway":
				r.TransitMode = append(r.TransitMode, maps.TransitModeSubway)
			case "train":
				r.TransitMode = append(r.TransitMode, maps.TransitModeTrain)
			case "tram":
				r.TransitMode = append(r.TransitMode, maps.TransitModeTram)
			case "rail":
				r.TransitMode = append(r.TransitMode, maps.TransitModeRail)
			}
		}
	}

	if *iterations == 1 {
		routes, waypoints, err := client.Directions(context.Background(), r)
		check(err)

		pretty.Println(waypoints)
		pretty.Println(routes)
	} else {
		done := make(chan iterationResult)
		for i := 0; i < *iterations; i++ {
			go func(i int) {
				startTime := time.Now()
				_, _, err := client.Directions(context.Background(), r)
				done <- iterationResult{
					fmt.Sprintf("Iteration %2d: round trip %.2f seconds", i, float64(time.Now().Sub(startTime))/1000000000),
					err,
				}
			}(i)
		}

		for i := 0; i < *iterations; i++ {
			result := <-done
			if err != nil {
				fmt.Printf("error: %+v\n", result.err)
			} else {
				fmt.Println(result.result)
			}
		}
	}
}
Example #20
0
func main() {
	file, _ := os.Open("config.json")
	decoder := json.NewDecoder(file)
	configuration := Configuration{}
	err := decoder.Decode(&configuration)
	if err != nil {
		fmt.Println("error:", err)
	}

	reload()
	nick = configuration.Nick
	user = configuration.User
	server = configuration.Server
	channel = configuration.Channel
	riotUrl = "https://euw.api.pvp.net/api/lol/euw/"
	riotApiKey = configuration.RiotApiKey
	weatherApiKey = configuration.WeatherApiKey
	mapsApiKey = configuration.MapsApiKey
	legMode = false

	fmt.Println("Server: " + server)
	fmt.Println("Nick: " + nick)
	fmt.Println("User: "******"channel: " + channel)
	fmt.Println("API Key: " + configuration.ApiKey)
	fmt.Println("API Secret: " + configuration.ApiKey)

	api = lastfm.New(configuration.ApiKey, configuration.ApiSecret)

	mapsClient, _ = maps.NewClient(maps.WithAPIKey(mapsApiKey))

	db, err = sql.Open("sqlite3", "./flamingo.db")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	_, err = db.Exec("CREATE TABLE IF NOT EXISTS users(nick TEXT PRIMARY KEY NOT NULL, lastfm TEXT NOT NULL)")
	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Println("Last.fm table created successfully")
	}

	_, err = db.Exec("CREATE TABLE IF NOT EXISTS league(nick TEXT PRIMARY KEY NOT NULL, summoner TEXT NOT NULL, id TEXT NOT NULL)")
	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Println("League of Legends table created successfully")
	}

	riot.SetAPIKey(riotApiKey)

	irccon = irc.IRC(nick, user)
	//irccon.Debug = true
	//irccon.VerboseCallbackHandler = true
	err = irccon.Connect(server)
	if err != nil {
		log.Fatal(err.Error())
		fmt.Println("Não me consegui ligar ao server")
	}

	irccon.AddCallback("001", func(e *irc.Event) {
		time.Sleep(5000 * time.Millisecond)
		fmt.Println("Identifying")
		irccon.Privmsg("NickServ", "identify "+configuration.Password)
		fmt.Println("Identified")
		irccon.Join(channel)
	})

	irccon.AddCallback("JOIN", func(e *irc.Event) {
		var reply string
		if strings.EqualFold("Rick971", e.Nick) && !legMode {
			reply = "Bom dia Henrique"
		} else if strings.EqualFold("altera", e.Nick) {
			reply = altera[rand.Intn(len(altera))]
		} else if CaseInsensitiveContains(e.Nick, "chop") && !legMode {
			chosen := choppa[rand.Intn(len(choppa))]
			//fmt.Println(chosen)
			reply = fmt.Sprintf(chosen, e.Nick)
		} else if CaseInsensitiveContains(e.Nick, "stron") {
			chosen := strongLines[rand.Intn(len(strongLines))]
			reply = chosen
		} else if strings.EqualFold(nick, e.Nick) && !legMode {
			reply = "Bom dia"
		} else if !legMode {
			reply = "Bom dia " + e.Nick
		}
		go botSay(reply)
	})

	irccon.AddCallback("KICK", func(e *irc.Event) {
		time.Sleep(1000 * time.Millisecond)
		irccon.Join(channel)
	})

	irccon.AddCallback("PRIVMSG", func(e *irc.Event) {
		if CaseInsensitiveContains(e.Nick, "Flamingo") {
			return
		}
		message := e.Message()
		req := strings.Split(message, " ")
		if req[0] == ".np" && !legMode {
			nowPlaying(req, e)
		} else if req[0] == ".lfmset" {
			lfmSet(req, e)
		} else if req[0] == ".compare" && !legMode {
			lfmCompare(req, e)
		} else if req[0] == ".lolset" {
			lolSet(req, e)
		} else if req[0] == ".sum" {
			lolSummoner(req, e)
		} else if req[0] == ".w" && !legMode {
			weather(req, e)
		} else if req[0] == ".reload" {
			reloadCall(req, e)
		} else if req[0] == ".strong" {
			strongismos(req, e)
		} else if req[0] == ".leg" {
			legModeToggle(req, e)
		} else if CaseInsensitiveContains(message, "flamingo") && !legMode {
			respostasCall(req, e)
		} /* else if req[0] == ".g" {
			googleSearch(message, e)
		}*/
	})

	irccon.Loop()
}