Пример #1
0
func init() {
	var err error
	Folder, err = osext.ExecutableFolder()
	if err != nil {
		panic(err)
	}
}
Пример #2
0
func getDir() string {
	dir, err := osext.ExecutableFolder()
	if err != nil {
		log.Fatal(err)
	}
	return dir
}
Пример #3
0
// GuessAppFromLocation uses the location of the execution to determine the app to launch
func GuessApp() string {
	// 1) check if current directory contains .app file and load it into the ENVIRONMENT
	if _, err := ioutil.ReadFile(config.APP_FILE); err == nil {
		utils.LoadEnvironmentFile("app")
	}

	appFromFile := os.Getenv("APP")

	if len(appFromFile) > 0 {
		return appFromFile
	} else {
		// use the name of the current directory but ask for confirmation
		currentDirPath, error := osext.ExecutableFolder()
		if error != nil {
			logger.Fatal("Cannot use current directory name for the app name")
			os.Exit(1)
		} else {
			startPosition := strings.LastIndex(currentDirPath, string(os.PathSeparator)) + 1
			currentDirectoryName := currentDirPath[startPosition:]
			appNameFromDirectory := strings.ToLower(string(currentDirectoryName))

			// TODO: ask for confirmation
			fmt.Println("No app name was passed and no appfile found...")
			answer := terminal.AskForConfirmation("Do you want to use the current directory name [" + appNameFromDirectory + "] ?")
			if answer == "YES" {
				return appNameFromDirectory
			} else {
				os.Exit(0)
			}
		}

		return ""
	}
}
Пример #4
0
func NewPsqlDao(conn string) *PsqlDao {
	db := PsqlDao{}
	db.conn = os.Getenv("DATABASE_URL")

	if db.conn == "" {
		log.Fatal("DATABASE_URL environment variable not set!")
	}

	db.dao = make(map[string]*sql.DB)

	// Create all the Tables, Views if they do not exist
	execPath, err := osext.ExecutableFolder()
	if err != nil {
		log.Fatal(err)
	}
	log.Println(execPath)
	db.ddl = goyesql.MustParseFile(path.Join(execPath, "data/sql/ddl.sql"))

	db.EnsurePool(AppDB)

	logExec(db.dao[AppDB], (string)(db.ddl["create-user-table"]))
	logExec(db.dao[AppDB], (string)(db.ddl["create-post-table"]))
	logExec(db.dao[AppDB], (string)(db.ddl["create-command-table"]))
	logExec(db.dao[AppDB], (string)(db.ddl["create-tag-table"]))
	logExec(db.dao[AppDB], (string)(db.ddl["create-invocation-table"]))
	logExec(db.dao[AppDB], (string)(db.ddl["create-invocationtag-table"]))
	logExec(db.dao[AppDB], (string)(db.ddl["create-commandhistory-view"]))
	logExec(db.dao[AppDB], (string)(db.ddl["create-timestamp-index"]))

	// Load all data-manipulation queries
	db.dml = goyesql.MustParseFile(path.Join(execPath, "data/sql/queries.sql"))

	log.Println("storage init completed")
	return &db
}
Пример #5
0
func init() {
	ThemeDir, _ = osext.ExecutableFolder()
	ThemeDir += "/../src/github.com/superhx/goblog/theme"
	templateDir = ThemeDir + "/template"
	homeTmpl, _ = template.ParseFiles(templateDir + "/home.htm")
	blogTmpl, _ = template.ParseFiles(templateDir + "/article.htm")
}
Пример #6
0
func logPath() string {
	now := time.Now().Format("2006-01-02")
	fName := fmt.Sprintf("%s.log", now)
	directory, _ := osext.ExecutableFolder()
	path := filepath.Join(directory, "logs", fName)
	return path
}
Пример #7
0
func main() {
	pwd, _ := osext.ExecutableFolder()

	config, err := ini.LoadFile(pwd + "/config.ini")
	if err != nil {
		panic("Config file not loaded.")
	}
	api_key, ok := config.Get("telegram", "token")
	if !ok {
		panic("Telegram API token not available.")
	}
	chat_id_str, ok := config.Get("telegram", "chat_id")
	if !ok {
		panic("Telegram Chat ID not available.")
	}

	os.Chdir(pwd)
	v := exec.Command("node", "version-fetcher.js")
	v.CombinedOutput()
	ver, err := ioutil.ReadFile(pwd + "/version")
	hash, err := ioutil.ReadFile(pwd + "/hash")
	c := exec.Command("gulp", "test")
	c.CombinedOutput()
	if _, err := os.Stat(pwd + "/error-msg"); os.IsNotExist(err) {
		msg := time.Now().Format("[2006-01-02 15:04]") + " Firefox Installers Check OK \nVERSION: " + string(ver) + ", SHA512: " + string(hash)[:10] + "..."
		send_msg(api_key, chat_id_str, msg)
	} else {
		msg := time.Now().Format("[2006-01-02 15:04]") + " Firefox Installers Check Failure \u2757\ufe0f\u2757\ufe0f\u2757\ufe0f \nVERSION: " + string(ver) + ", SHA512: " + string(hash)[:10] + "..."
		send_msg(api_key, chat_id_str, msg)
	}
}
Пример #8
0
func detectProdConfig(useosxt bool) string {
	var levelUp string
	var curDir string
	sep := string(filepath.Separator)

	if useosxt {
		curDir, _ = os.Getwd()
	} else {
		curDir, _ = osext.ExecutableFolder()
	}

	//detect from test or console
	match, _ := regexp.MatchString("_test", curDir)
	matchArgs, _ := regexp.MatchString("arguments", curDir)
	matchTestsDir, _ := regexp.MatchString("tests", curDir)
	if match || matchArgs || matchTestsDir {
		if matchTestsDir {
			levelUp = ".."
		}
		curDir, _ = filepath.Abs(curDir + sep + levelUp + sep)
	}

	CurrDirectory = curDir
	configDir, _ := filepath.Abs(curDir + sep + CONFIG_DIR + sep)
	appConfig := configDir + sep + CONFIG_FILE
	appProdConfig := configDir + sep + PRODUCTION_FOLDER + sep + CONFIG_FILE
	if fileExists(appProdConfig) {
		appConfig = appProdConfig
	} else if !useosxt {
		appConfig = detectProdConfig(true)
	}

	return appConfig
}
Пример #9
0
func DefaultAssetPath() string {
	var assetPath string
	pwd, _ := os.Getwd()
	srcdir := path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist")

	// If the current working directory is the go-ethereum dir
	// assume a debug build and use the source directory as
	// asset directory.
	if pwd == srcdir {
		assetPath = path.Join(pwd, "assets")
	} else {
		switch runtime.GOOS {
		case "darwin":
			// Get Binary Directory
			exedir, _ := osext.ExecutableFolder()
			assetPath = filepath.Join(exedir, "..", "Resources")
		case "linux":
			assetPath = path.Join("usr", "share", "mist")
		case "windows":
			assetPath = path.Join(".", "assets")
		default:
			assetPath = "."
		}
	}

	// Check if the assetPath exists. If not, try the source directory
	// This happens when binary is run from outside cmd/mist directory
	if _, err := os.Stat(assetPath); os.IsNotExist(err) {
		assetPath = path.Join(srcdir, "assets")
	}

	return assetPath
}
Пример #10
0
// GetData retrieves and calculates the metrics to be displayed in the report page.
func getData(data *Info) error {
	currentFolder, err := osext.ExecutableFolder()
	if err != nil {
		log.Error("Could not retrieve current folder. Attempting to use dot(.) instead...", "error", err)
		currentFolder = "."
	}

	dbFilePath := currentFolder + "/values.db"
	db, err := sql.Open("sqlite3", dbFilePath)
	if err != nil {
		log.Crit("Failed to opend database", "error", err, "path", dbFilePath)
		return err
	}
	defer db.Close()

	rows, err := db.Query("SELECT timestamp, ping, download, upload FROM bandwidth")
	if err != nil {
		log.Crit("Could not retrieve data from database", "error", err)
		return err
	}
	defer rows.Close()

	min := 10000.0 // Unfortunately, I don't see myself with a 10000Mbit/s connection anytime soon...
	max := 0.0
	counter := 0
	average := 0.0
	data.Points = [][]interface{}{{map[string]string{"type": "datetime", "label": "Time"}, "Download", "Upload"}}

	for rows.Next() {
		var timestamp string
		var ping, download, upload float64
		rows.Scan(&timestamp, &ping, &download, &upload)

		if download < min {
			min = download
		}

		if download > max {
			max = download
		}

		average += download
		counter++

		// Timestamp is presented as YYYY-MM-DD HH:MI:SS.Milli+0000
		split := strings.Split(timestamp, " ")
		dateOnly := strings.Split(string(split[0]), "-")
		timeOnly := strings.Split(string(split[1]), ".")
		timeOnly = strings.Split(string(timeOnly[0]), ":")
		axis := fmt.Sprintf("Date(%s, %s, %s, %s, %s, %s)", dateOnly[0], dateOnly[1], dateOnly[2], timeOnly[0], timeOnly[1], timeOnly[2])

		data.Points = append(data.Points, []interface{}{axis, download, upload})
	}
	data.MinValue = min
	data.MaxValue = max
	data.AvgValue = average / float64(counter)
	data.LastValue = data.Points[len(data.Points)-1][1].(float64)

	return nil
}
Пример #11
0
func stopRemoteMasterServer() {
	if *serveStopConfigFile == "" {
		folderPath, err := osext.ExecutableFolder()
		if err != nil {
			log.Fatal(err)
		}
		*serveStopConfigFile = folderPath + "/.apmenv/config.toml"
		os.MkdirAll(path.Dir(*serveStopConfigFile), 0777)
	}
	ctx := &daemon.Context{
		PidFileName: path.Join(filepath.Dir(*serveStopConfigFile), "main.pid"),
		PidFilePerm: 0644,
		LogFileName: path.Join(filepath.Dir(*serveStopConfigFile), "main.log"),
		LogFilePerm: 0640,
		WorkDir:     "./",
		Umask:       027,
	}

	if ok, p, _ := isDaemonRunning(ctx); ok {
		if err := p.Signal(syscall.Signal(syscall.SIGQUIT)); err != nil {
			log.Fatalf("Failed to kill daemon %v", err)
		}
	} else {
		ctx.Release()
		log.Info("instance is not running.")
	}
}
Пример #12
0
// Get the local config file -- accounts for .app bundled procs as well
func GetLocalConfigFile() string {
	folder, err := osext.ExecutableFolder()
	if err != nil {
		panic(err)
	}
	return filepath.Join(folder, "config.json")
}
Пример #13
0
func DetectFile(isServ bool) (string, bool) {
	p, e := osext.ExecutableFolder()
	u, e := user.Current()
	var homeDir string
	if e == nil {
		homeDir = u.HomeDir
	} else {
		homeDir = os.Getenv("HOME")
	}
	var name string
	if isServ {
		name = "deblocus.d5s"
	} else {
		name = "deblocus.d5c"
	}
	for _, f := range []string{name, // cwd
		filepath.Join(p, name),                 // bin
		filepath.Join(homeDir, name),           // home
		filepath.Join("/etc/deblocus", name)} { // /etc/deblocus
		if !IsNotExist(f) {
			return f, true
		}
	}
	return filepath.Join(p, name), false
}
Пример #14
0
func (p *program) run() {
	logger.Infof("Service running %v.", service.Platform())

	exePath, err := osext.ExecutableFolder()
	if err != nil {
		log.Fatal(err)
	}

	if _, err := os.Stat(exePath + "/logs"); os.IsNotExist(err) {
		err = os.Mkdir(exePath+"/logs", 0766)
		if err != nil {
			log.Fatalf("error creating logs folder: %v", err)
		}
	}

	ts := time.Now().Local().Format("2006-01-02")
	f, err := os.OpenFile(exePath+"/logs/print-server-"+ts+".log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalf("error opening log file: %v", err)
	}
	defer f.Close()

	log.SetOutput(f)
	log.SetFlags(log.Ldate + log.Ltime + log.Lmicroseconds)

	http.HandleFunc("/print", print)
	http.HandleFunc("/", home)

	log.Printf("Server started-up and listening at %s.", *addr)
	log.Fatal(http.ListenAndServe(*addr, nil))
}
Пример #15
0
// lets find the executable on the PATH or in the fabric8 directory
func resolveBinaryLocation(executable string) string {
	path, err := exec.LookPath(executable)
	if err != nil || fileNotExist(path) {
		home := os.Getenv("HOME")
		if home == "" {
			util.Error("No $HOME environment variable found")
		}
		writeFileLocation := getFabric8BinLocation()

		// lets try in the fabric8 folder
		path = filepath.Join(writeFileLocation, executable)
		if fileNotExist(path) {
			path = executable
			// lets try in the folder where we found the gofabric8 executable
			folder, err := osext.ExecutableFolder()
			if err != nil {
				util.Errorf("Failed to find executable folder: %v\n", err)
			} else {
				path = filepath.Join(folder, executable)
				if fileNotExist(path) {
					util.Infof("Could not find executable at %v\n", path)
					path = executable
				}
			}
		}
	}
	util.Infof("using the executable %s\n", path)
	return path
}
Пример #16
0
// GetBlankDir returns the path to go-bootstrap's blank directory
func GetBlankDir() (string, error) {
	executableDir, err := osext.ExecutableFolder()
	ExitOnError(err, "Cannot find go-bootstrap path")

	ret := filepath.Join(executableDir, "blank")
	if _, err = os.Stat(ret); err == nil {
		return ret, nil
	}

	base := filepath.Join("src", "github.com", "go-bootstrap", "go-bootstrap")

	// if the blank project can't be found in the executable's dir,
	// try to locate the source code, it should be there.
	// $gopath/bin/../src/github.com/go-bootstrap/go-bootstrap
	srcDir := filepath.Join(filepath.Dir(executableDir), base)
	ret = filepath.Join(srcDir, "blank")
	if _, err = os.Stat(ret); err == nil {
		return ret, nil
	}

	// As the last resort search all gopaths.
	// This is useful when executed with `go run`
	for _, gopath := range GoPaths() {
		ret = filepath.Join(filepath.Join(gopath, base), "blank")
		if _, err = os.Stat(ret); err == nil {
			return ret, nil
		}
	}

	return "", errors.New("Cannot find go-bootstrap's blank directory")
}
Пример #17
0
func getMoonLauncher() *MoonLauncher {
	if moonLauncher != nil {
		return moonLauncher
	}

	moonLauncher = &MoonLauncher{
		name: "MoonDeploy",
	}

	moonLauncher.title = fmt.Sprintf("%v %v", moonLauncher.name, moondeploy.Version)

	var err error
	moonLauncher.executable, err = osext.Executable()
	if err != nil {
		panic(err)
	}

	moonLauncher.directory, err = osext.ExecutableFolder()
	if err != nil {
		panic(err)
	}

	moonLauncher.iconPathAsIco = filepath.Join(moonLauncher.directory, "moondeploy.ico")
	moonLauncher.iconPathAsPng = filepath.Join(moonLauncher.directory, "moondeploy.png")

	moonLauncher.settings = getMoonSettings()

	return moonLauncher
}
Пример #18
0
func NewRouter() *mux.Router {
	var handler http.Handler

	logger := log.New("module", "web.router")
	router := mux.NewRouter().StrictSlash(true)
	for _, route := range routes {
		handler = route.HandlerFunc
		handler = Logger(handler, route.Name, logger)

		router.
			Methods(route.Method).
			Path(route.Pattern).
			Name(route.Name).
			Handler(handler)
	}

	currentFolder, err := osext.ExecutableFolder()
	if err != nil {
		panic(err)
	}

	handler = http.FileServer(http.Dir(currentFolder + "/html/lib/"))
	handler = http.StripPrefix("/resources/", handler)
	handler = Logger(handler, "Resources", logger)
	router.
		Methods("GET").
		PathPrefix("/resources/").
		Name("Resources").
		Handler(handler)

	return router
}
Пример #19
0
func main() {

	ROOT_DIR, _ = osext.ExecutableFolder()
	config.LoadConfig(ge.BuildFullPath(ROOT_DIR, "config.json"))

	GE = ge.NewGalaxyEmpires(ge.BuildFullPath(ROOT_DIR, "data"), ge.CoordinatesStruct{1, 15, 5})

	r := gin.New()
	r.Use(gin.Logger())
	r.Use(gin.Recovery())
	r.Use(middleware.Errors("", "", nil))

	debug.AssignDebugHandlers(r.Group("/debug"))

	handlers.NewAccountHandler(r.Group("/account"), GE)
	handlers.NewPlayerHandler(r.Group("/player", middleware.Authentication([]byte(config.Config.Key))), GE)
	handlers.NewPlanetHandler(r.Group("/planet", middleware.Authentication([]byte(config.Config.Key))), GE)

	r.Static("/assets", ROOT_DIR+"/web/assets")
	r.StaticFile("/", ROOT_DIR+"/web/index.html")

	if err := r.Run(":" + config.Config.Port); err != nil {
		panic(err)
	}

}
Пример #20
0
// start
func main() {
	var p Player
	folderPath, _ := osext.ExecutableFolder()
	p.client_id, _ = ioutil.ReadFile(folderPath + "/client_id.txt")
	p.MinD = 50 * 60 * 1000
	p.MaxD = 500 * 60 * 1000
	println("Please type a search term or 'x' to exit ....")
	r := bufio.NewReader(os.Stdin)
	for {
		i, _, _ := r.ReadLine()
		p.li = string(i)
		switch {
		case p.li == "x":
			p.exit()
		case p.li == "ll":
			p.showResultList()
		case strings.HasPrefix(p.li, "set "):
			p.set()
		case strings.HasPrefix(p.li, "i "):
			p.info()
		case isAllint(p.li):
			go p.killAndPlay()
		case true:
			p.searchSoundCloud()
			sort.Sort(ByLength{p.srs})
			sort.Sort(ByAge{p.srs})
			p.showResultList()
		}
	}
}
Пример #21
0
func GetConfiguration(fileName *string) (*Configuration, error) {

	configuration := Configuration{
		QueueUrl:          "https://sqs.us-west-2.amazonaws.com/343529734570/messagerecorder",
		BatchSize:         10,
		VisibilityTimeout: 1,
		WaitTimeSeconds:   1,
		SqsRegion:         "us-west-2",
		SnsRegion:         "us-east-1",
		DynamoRegion:      "us-west-2",
		TopicArn:          "arn:aws:sns:us-east-1:343529734570:TaxQuery",
	}

	rootPath, err := osext.ExecutableFolder()
	if err != nil {
		log.Println("Failed to get the executable folder:")
		log.Fatal(err)
		log.Println("use default ==>")
		log.Println(configuration)
		return &configuration, nil
	}

	folderExist, _ := exists(rootPath)
	if folderExist {
		log.Println("folder exists: " + rootPath)
	} else {
		log.Println("folder DOES NOT exist: " + rootPath)
	}

	fullPath := filepath.Join(rootPath, *fileName)
	log.Println("conf.json path:", fullPath)

	fileExist, _ := exists(fullPath)
	if fileExist {
		log.Println("file exists: " + fullPath)
	} else {
		log.Println("file DOES NOT exist: " + fullPath)
	}

	file, err := os.Open(fullPath)
	if err != nil {
		log.Println("Failed to open configuration file: conf.json;"+err.Error(), fullPath)
		log.Println("use default ==>")
		log.Println(configuration)
		return &configuration, nil
	}

	decoder := json.NewDecoder(file)

	if err = decoder.Decode(&configuration); err != nil {
		log.Println("Invalid JSON file: conf.json; ", err)
		log.Println("use default ==>")
		log.Println(configuration)
		return &configuration, nil
	}

	log.Println(configuration)
	return &configuration, nil
}
Пример #22
0
func determineWorkingDirectory() string {
	executablePath, err := osext.ExecutableFolder()
	if err != nil {
		log.Fatal("Error: Couldn't determine working directory: " + err.Error())
	}
	os.Chdir(executablePath)
	return ""
}
Пример #23
0
func filesPath() string {
	binPath, _ := osext.ExecutableFolder()
	path := filepath.Join(binPath, "files")
	if _, err := os.Stat(path); os.IsNotExist(err) {
		os.MkdirAll(path, 0755)
	}
	return path
}
Пример #24
0
func configPath() (res string, err error) {
	exeFolder, err := osext.ExecutableFolder()
	if err != nil {
		return
	}
	res = path.Join(exeFolder, "gweet.json")
	return
}
Пример #25
0
func determineExecutablePath() string {
	// Get the path this executable is located in
	executablePath, err := osext.ExecutableFolder()
	if err != nil {
		log.Fatal("Error: Couldn't determine what directory this executable is in:", err)
	}
	return executablePath
}
Пример #26
0
func ServiceStart(service Service, configMethod ConfigMethod, waitGroup *sync.WaitGroup) (chanStop chan int) {
	var err error

	if waitGroup != nil {
		waitGroup.Add(1)
	}

	directory, err := osext.ExecutableFolder()
	if err != nil {
		log.Fatalf("Get directory of app err: %v", err)
	}

	config := service.NewConfig()
	flConfigPath := flag.String("c", "", "config path")
	flag.Parse()
	if flag.NFlag() == 0 {
		flag.PrintDefaults()
		return
	}

	if *flConfigPath == "" {
		log.Fatalf("need config file")
	}

	if err = configMethod(config, *flConfigPath); err != nil {
		log.Fatalf("load config err: %s", err)
	}

	if err = service.Init(directory); err != nil {
		log.Fatalf("init err: %s", err)
	}
	chSignals := make(chan os.Signal)
	chStop := make(chan int)
	go func() {
		if err = service.Run(); err != nil {
			log.Fatalf("run err: %s", err)
		}
		chStop <- 1
	}()
	signal.Notify(chSignals, syscall.SIGINT, syscall.SIGKILL)
	go func() {
		select {
		case sig := <-chSignals:
			log.Printf("received signal %d", sig)
		case <-chStop:
			log.Printf("received command stop")
		}
		log.Printf("stopping")
		if err = service.Stop(); err != nil {
			log.Fatalf("stop err: %s", err)
		}
		if waitGroup != nil {
			waitGroup.Done()
		}
	}()
	return chStop
}
Пример #27
0
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)
	}
}
Пример #28
0
func GetExecutorPath() string {
	// we cannot rely on os.Args[0], it may be faked sometimes
	execPath, err := osext.ExecutableFolder()
	if err != nil {
		log.Fatal(err)
	}

	return execPath
}
Пример #29
0
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)
	}
}
Пример #30
0
func readConfig() {
	path, _ := osext.ExecutableFolder()
	viper.AddConfigPath("/etc/eremetic")
	viper.AddConfigPath(path)
	viper.AutomaticEnv()
	viper.SetConfigName("eremetic")
	viper.SetDefault("loglevel", "debug")
	viper.SetDefault("database", "db/eremetic.db")
	viper.ReadInConfig()
}