Пример #1
0
func (bot *Bot) CmdInterpreter(username string, usermessage string) {
	message := strings.ToLower(usermessage)
	tempstr := strings.Split(message, " ")

	for _, str := range tempstr {
		if strings.HasPrefix(str, "https://") || strings.HasPrefix(str, "http://") {
			go bot.Message("^ " + webTitle(str))
		} else if isWebsite(str) {
			go bot.Message("^ " + webTitle("http://"+str))
		}
	}

	if strings.HasPrefix(message, "!help") {
		bot.Message("For help on the bot please go to http://commandanddemand.com/bot.html")
	} else if strings.HasPrefix(message, "!quote") {
		bot.Message(bot.getQuote())
	} else if strings.HasPrefix(message, "!addquote ") {
		stringpls := strings.Replace(message, "!addquote ", "", 1)
		if bot.isMod(username) {
			bot.quotes[stringpls] = username
			bot.writeQuoteDB()
			bot.Message("Quote added!")
		} else {
			bot.Message(username + " you are not a mod!")
		}
	} else if strings.HasPrefix(message, "!timeout ") {
		stringpls := strings.Replace(message, "!timeout ", "", 1)
		temp1 := strings.Split(stringpls, " ")
		temp2 := strings.Replace(stringpls, temp1[0], "", 1)
		if temp2 == "" {
			temp2 = "no reason"
		}
		if bot.isMod(username) {
			bot.timeout(temp1[0], temp2)
		} else {
			bot.Message(username + " you are not a mod!")
		}
	} else if strings.HasPrefix(message, "!ban ") {
		stringpls := strings.Replace(message, "!ban ", "", 1)
		temp1 := strings.Split(stringpls, " ")
		temp2 := strings.Replace(stringpls, temp1[0], "", 1)
		if temp2 == "" {
			temp2 = "no reason"
		}
		if bot.isMod(username) {
			bot.ban(temp1[0], temp2)
		} else {
			bot.Message(username + " you are not a mod!")
		}
	} else if message == "!song" {
		api := lastfm.New("e6563970017df6d5966edfa836e12835", "dcc462ffd8a371fee5a5b49c248a2371")
		temp, _ := api.User.GetRecentTracks(lastfm.P{"user": bot.lastfm})
		var inserthere string
		if temp.Tracks[0].Date.Date != "" {
			inserthere = ". It was played on: " + temp.Tracks[0].Date.Date
		}
		bot.Message("Song: " + temp.Tracks[0].Artist.Name + " - " + temp.Tracks[0].Name + inserthere)
	}
}
Пример #2
0
func (l *lookupApi) ConnectWithConfig(configPath string) {
	configFile, err := os.Open(configPath)
	defer configFile.Close()
	if err != nil {
		panic(fmt.Errorf("Could not load config file %s", configPath))
	}

	var config lastfmConfig
	json.NewDecoder(configFile).Decode(&config)

	l.api = lastfm.New(config.Key, config.Secret)
}
Пример #3
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()
}
Пример #4
0
// PostLastFM allows access to the Last.fm API, enabling wavepipe to set a user's currently-playing
// track, as well as to enable scrobbling.
func PostLastFM(w http.ResponseWriter, r *http.Request) {
	// Retrieve render
	ren := context.Get(r, CtxRender).(*render.Render)

	// Attempt to retrieve user from context
	user := new(data.User)
	if tempUser := context.Get(r, CtxUser); tempUser != nil {
		user = tempUser.(*data.User)
	} else {
		// No user stored in context
		log.Println("api: no user stored in request context!")
		ren.JSON(w, 500, serverErr)
		return
	}

	// Output struct for Last.fm response
	out := LastFMResponse{}

	// Check API version
	if version, ok := mux.Vars(r)["version"]; ok {
		// Check if this API call is supported in the advertised version
		if !apiVersionSet.Has(version) {
			ren.JSON(w, 400, errRes(400, "unsupported API version: "+version))
			return
		}
	}

	// Do not allow guests and below to use Last.fm functionality
	if user.RoleID < data.RoleUser {
		ren.JSON(w, 403, permissionErr)
		return
	}

	// Check API action
	action, ok := mux.Vars(r)["action"]
	if !ok {
		ren.JSON(w, 400, errRes(400, "no string action provided"))
		return
	}

	// Check for valid action
	if !set.New(lfmLogin, lfmNowPlaying, lfmScrobble).Has(action) {
		ren.JSON(w, 400, errRes(400, "invalid string action provided"))
		return
	}

	// Instantiate Last.fm package
	lfm := lastfm.New(lfmAPIKey, lfmAPISecret)

	// Authenticate to the Last.fm API
	if action == lfmLogin {
		// Retrieve username from POST body
		username := r.PostFormValue("username")
		if username == "" {
			ren.JSON(w, 400, errRes(400, lfmLogin+": no username provided"))
			return
		}

		// Retrieve password from POST body
		password := r.PostFormValue("password")
		if password == "" {
			ren.JSON(w, 400, errRes(400, lfmLogin+": no password provided"))
			return
		}

		// Send a login request to Last.fm
		if err := lfm.Login(username, password); err != nil {
			ren.JSON(w, 401, errRes(401, lfmLogin+": last.fm authentication failed"))
			return
		}

		// Retrieve the API token for this user with wavepipe
		token, err := lfm.GetToken()
		if err != nil {
			log.Println(err)
			ren.JSON(w, 500, serverErr)
			return
		}

		// Store the user's Last.fm token in the database
		user.LastFMToken = token
		if err := user.Update(); err != nil {
			log.Println(err)
			ren.JSON(w, 500, serverErr)
			return
		}

		// Return the token authorization URL for the user
		out.URL = lfm.GetAuthTokenUrl(token)

		log.Println(lfmLogin, ": generated new token for user:"******"" {
		ren.JSON(w, 401, errRes(401, action+": user must authenticate to last.fm"))
		return
	}

	// Send a login request to Last.fm using token
	if err := lfm.LoginWithToken(user.LastFMToken); err != nil {
		// Check if token has not been authorized
		if strings.HasPrefix(err.Error(), "LastfmError[14]") {
			// Generate error output, but add the token authorization URL
			out.URL = lfm.GetAuthTokenUrl(user.LastFMToken)
			ren.JSON(w, 401, errRes(401, action+": last.fm token not yet authorized"))
			return
		}

		// All other failures
		ren.JSON(w, 401, errRes(401, action+": last.fm authentication failed"))
		return
	}

	// Check for an ID parameter
	pID, ok := mux.Vars(r)["id"]
	if !ok {
		ren.JSON(w, 400, errRes(400, action+": no integer song ID provided"))
		return
	}

	// Verify valid integer ID
	id, err := strconv.Atoi(pID)
	if err != nil {
		ren.JSON(w, 400, errRes(400, action+": invalid integer song ID"))
		return
	}

	// Load the song by ID
	song := &data.Song{ID: id}
	if err := song.Load(); err != nil {
		// Check for invalid ID
		if err == sql.ErrNoRows {
			ren.JSON(w, 404, errRes(404, action+": song ID not found"))
			return
		}

		// All other errors
		log.Println(err)
		ren.JSON(w, 500, serverErr)
		return
	}

	// Log the current action
	log.Printf("%s : %s : [#%05d] %s - %s", action, user.Username, song.ID, song.Artist, song.Title)

	// Create the track entity required by Last.fm from the song
	track := lastfm.P{
		"artist":    song.Artist,
		"album":     song.Album,
		"track":     song.Title,
		"timestamp": time.Now().Unix(),
	}

	// Check for optional timestamp parameter, which could be useful for sending scrobbles at
	// past times, etc
	if pTS := r.URL.Query().Get("timestamp"); pTS != "" {
		// Verify valid integer timestamp
		ts, err := strconv.Atoi(pTS)
		if err != nil || ts < 0 {
			ren.JSON(w, 400, errRes(400, action+": invalid integer timestamp"))
			return
		}

		// Override previously set timestamp with this one
		track["timestamp"] = ts
	}

	// Send a now playing request to the Last.fm API
	if action == lfmNowPlaying {
		// Perform the action
		if _, err := lfm.Track.UpdateNowPlaying(track); err != nil {
			log.Println(err)
			ren.JSON(w, 500, serverErr)
			return
		}

		// HTTP 200 OK with JSON
		out.Error = nil
		ren.JSON(w, 200, out)
		return
	}

	// Send a scrobble request to the Last.fm API
	if action == lfmScrobble {
		// Perform the action
		if _, err := lfm.Track.Scrobble(track); err != nil {
			log.Println(err)
			ren.JSON(w, 500, serverErr)
			return
		}

		// HTTP 200 OK with JSON
		out.Error = nil
		ren.JSON(w, 200, out)
		return
	}

	// Invalid action, meaning programmer error, HTTP 500
	panic("no such Last.fm action: " + action)
}