当前位置: 首页>>代码示例>>Golang>>正文


Golang telebot.NewBot函数代码示例

本文整理汇总了Golang中github.com/tucnak/telebot.NewBot函数的典型用法代码示例。如果您正苦于以下问题:Golang NewBot函数的具体用法?Golang NewBot怎么用?Golang NewBot使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NewBot函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: init

func init() {
	opt = new(telebot.SendOptions)
	flag.StringVar(&iniFile, "ini", "", "Specify php.ini path")
	flag.StringVar(&tokenFile, "t", "token", "File contains bot token")
	flag.StringVar(&phpFile, "php", "entry.php", "PHP entry file, you can access JSON encoded message data in $message")
	flag.UintVar(&workers, "w", 1, "Run `N` goroutines to process message, must greater than 0")
	flag.Parse()

	data, err := ioutil.ReadFile(tokenFile)
	if err != nil {
		log.Fatalf("Cannot read token from file[%s]: %s", tokenFile, err)
	}
	token = strings.TrimSpace(string(data))

	if workers < 1 {
		flag.PrintDefaults()
		os.Exit(1)
	}

	if _, err := os.Stat(phpFile); err != nil {
		log.Fatalf("PHP entry file %s error: %s", phpFile, err)
	}

	bot, err = telebot.NewBot(token)
	if err != nil {
		log.Fatalf("Cannot start telebot: %s", err)
	}

	pipe = make(chan task)
}
开发者ID:Ronmi,项目名称:phptelegoram,代码行数:30,代码来源:main.go

示例2: main

func main() {
	flag.Parse()
	if *token_file == "" {
		flag.PrintDefaults()
		os.Exit(1)
	}

	args := flag.Args()
	log.Print(args)
	if len(args) < 1 {
		log.Fatal(`Usage: ` + os.Args[0] + ` -worker 5 -token=token_file cmd_to_run arg1 arg2 ...`)
	}

	token, err := ioutil.ReadFile(*token_file)
	if err != nil {
		log.Fatal(err)
	}

	bot, err := telebot.NewBot(string(token))
	if err != nil {
		log.Fatal(err)
	}

	messages := make(chan telebot.Message)
	bot.Listen(messages, 1*time.Second)

	h := CreateHandler(bot, args, *max_worker)
	log.Printf("Workers: %d\n", *max_worker)

	for msg := range messages {
		go h.Process(bot, msg)
	}
}
开发者ID:Ronmi,项目名称:telebot-worker,代码行数:33,代码来源:main.go

示例3: main

// bot execution logic, init logic
func main() {
	bot, err := telebot.NewBot(os.Getenv("TELEGRAM_TOKEN"))
	if err != nil {
		fmt.Println("Fatal(0x0): Unable to start bot")
		return
	}

	data_map = make(map[string]BotData)
	msg_map = make(map[string]string)
	data, err := ioutil.ReadFile("msg.txt")
	if err != nil {
		fmt.Println("Fatal(0x1): Unable to read msg file")
		return
	}

	err = json.Unmarshal(data, &msg_map)
	if err != nil {
		fmt.Println("Fatal(0x2): Unable to parse msg file")
		return
	}

	messages := make(chan telebot.Message)
	bot.Listen(messages, 1*time.Second)

	fmt.Println("Info(0x0): Now listening")

	for msg := range messages {
		handler(bot, msg)
	}
}
开发者ID:a1sams1a,项目名称:telegram-kaist-bot,代码行数:31,代码来源:bot.go

示例4: RunTelegramBot

func RunTelegramBot() {
	if GetConfiguration().Notification.TelegramBotApiKey == "" {
		return
	}

	bot, err := telebot.NewBot(GetConfiguration().Notification.TelegramBotApiKey)
	if err != nil {
		logging.MustGetLogger("").Error("Unable to start Telegram-Bot: ", err)
		return
	}
	logging.MustGetLogger("").Info("Telgram-Bot started.")
	Bot = bot

	messages := make(chan telebot.Message)
	bot.Listen(messages, 1*time.Second)

	for message := range messages {
		if message.Text == "/start" {
			bot.SendMessage(message.Chat, "Welcome to the UpAndRunning2 Telegram-Bot! \U0001F44B\n\nPlease use your User-ID (`"+strconv.Itoa(message.Sender.ID)+"`) as notification-target in UpAndRunning2.", &SendOptions)
		} else if message.Text == "/id" {
			bot.SendMessage(message.Chat, "Your User-ID: `"+strconv.Itoa(message.Sender.ID)+"`", &SendOptions)
		} else if message.Text == "/server" {
			bot.SendMessage(message.Chat, "This server is running *UpAndRunning2 v"+GetConfiguration().Static.Version+"* (`"+GetConfiguration().Static.GoVersion+"@"+GetConfiguration().Static.GoArch+"`).\n"+
				"You can find more information about this application [here](https://github.com/MarvinMenzerath/UpAndRunning2).\n\n"+
				"*Server-Settings:*\n    - Title: `"+GetConfiguration().Application.Title+"`\n    - Interval: `"+strconv.Itoa(GetConfiguration().Dynamic.Interval)+"`\n"+
				"    - Redirects: `"+strconv.Itoa(GetConfiguration().Application.RedirectsToFollow)+"`\n    - Offline-Checks: `"+strconv.FormatBool(GetConfiguration().Application.RunCheckIfOffline)+"`", &SendOptions)
		}
	}
}
开发者ID:MarvinMenzerath,项目名称:UpAndRunning2,代码行数:29,代码来源:telegram.go

示例5: OpenBot

func OpenBot(name string) (*Bot, error) {

	rand.Seed(time.Now().UTC().UnixNano())
	file, err := os.Open(name)
	if err != nil {
		return nil, err
	}

	defer file.Close()

	var bot *Bot

	err = json.NewDecoder(file).Decode(&bot)
	if err != nil {
		return nil, err
	}

	bot.Bot, err = telebot.NewBot(bot.Token)
	if err != nil {
		log.Fatal(err)
	} else {
		log.Printf("Bot " + bot.Name + " started!")
	}

	return bot, err
}
开发者ID:ivanthelad,项目名称:telegram-botcreator,代码行数:26,代码来源:bot.go

示例6: NewBot

// NewBot creates a Bots with token `token`, which is a secret API key assigned to particular bot.
func NewBot(token string) (*Bot, error) {
	bot, err := telebot.NewBot(token)
	if err != nil {
		return nil, errors.New("Failed to create a bot!")
	}

	return &Bot{token, false, bot, make(chan telebot.Message), make(map[string]*Task)}, nil
}
开发者ID:sgl0v,项目名称:go-ticketswap,代码行数:9,代码来源:bot.go

示例7: main

func main() {
	// the token on which telebot will send/receive stuff
	var token = flag.String("token", "", "The bot token")

	// the address and port on which redis will listen
	var redis = flag.String("redis", "localhost:6379", "The address to bind to redis, e.g. \"localhost:5555\"")

	// the cron string on which to send all the currencies (why I did this?)
	var cronString = flag.String("cron", "0 0 9 * * *", "The cron string on which to send currencies.")

	// the filename of the log when on the server (this is good)
	var output = flag.String("output", "", "The file where to create the log")

	flag.Parse()

	bot, err := telebot.NewBot(*token)

	// if telegram is not there, bail.
	if err != nil {
		panic(err)
	}

	fixrAccessor := fixrdb.New("tcp", *redis)

	defer fixrAccessor.Close()

	// if there's a file, create it and use it. Else, assume debugging: pipe to stdout.
	if len(*output) > 0 {
		output, err := os.Create(*output)
		if err != nil {
			panic(err)
		}
		logging.Start(output)
	} else {
		logging.Start(os.Stdout)
	}

	// this doesn't actually work... but whatever.
	defer func() {
		logging.Info("Stopping the program")
	}()

	logging.Info("Started Redis instance")

	// start the scheduler
	startSched(bot, fixrAccessor, *cronString)
	messages := make(chan telebot.Message)
	done := make(chan bool)

	// listen to updates
	bot.Listen(messages, 1*time.Second)

	// handle messages on a different goroutine, so we don't mess this up.
	go handleMessages(messages, bot, fixrAccessor, done)

	// wait for the inevitable end (that never comes)
	<-done
}
开发者ID:nubunto,项目名称:fixr,代码行数:58,代码来源:main.go

示例8: Init

// Initialize Telegram adapter
func (adapter *Telegram) Init() error {
	bot, err := telebot.NewBot(adapter.cfg.Token)
	if err != nil {
		return err
	}

	adapter.bot = bot
	return nil
}
开发者ID:pusparajm,项目名称:linda,代码行数:10,代码来源:telegram.go

示例9: main

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 motherfucker"))
	jb.AddFunction("/chickens", jb.SendImage("cluck cluck motherfucker"))

	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)
	}
}
开发者ID:nicluo,项目名称:jarvisbot,代码行数:57,代码来源:main.go

示例10: main

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)
	}
}
开发者ID:nicluo,项目名称:morningbot,代码行数:56,代码来源:main.go

示例11: main

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)
			}
		}
	}
}
开发者ID:aladine,项目名称:telebot-worker,代码行数:55,代码来源:telebot.go

示例12: main

func main() {

	var c int
	var configurationFile = "telegram-config.json"
	var logFile string
	OptErr = 0
	for {
		if c = Getopt("c:l:h"); c == EOF {
			break
		}
		switch c {
		case 'c':
			configurationFile = OptArg
		case 'l':
			logFile = OptArg
		case 'h':
			println("usage: " + os.Args[0] + " [-c configfile.json|-l logfile|-h]")
			os.Exit(1)
		}
	}

	config, err := util.LoadConfig(configurationFile)

	if logFile != "" {
		//Set logging to file
		f, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			log.Fatal("error opening file: %v", err)
		}
		defer f.Close()

		log.SetOutput(f)
	}

	bot, err := telebot.NewBot(config.Token)
	if config.Token != "" {
		fmt.Println("Token: " + config.Token)
	}
	fmt.Println("Configuration file: " + configurationFile)
	fmt.Println("Log file: " + logFile)

	if err != nil {
		return
	}

	messages := make(chan telebot.Message)
	bot.Listen(messages, 1*time.Second)

	for message := range messages {
		for _, d := range plugin_registry.Plugins {
			go d.Run(bot, config, message)
		}
	}
}
开发者ID:gitter-badger,项目名称:yatzie,代码行数:54,代码来源:main.go

示例13: main

func main() {
	telegramAPIKey := os.Getenv("DJIGURBOT_TELEGRAMAPIKEY")
	if telegramAPIKey == "" {
		panic("Telegram api key is not set.")
	}

	bot, err := telebot.NewBot(telegramAPIKey)
	if err != nil {
		panic("Could not connect to Telegram API")
	}

	toasts, err := readToastsFile()
	if err != nil {
		panic("Could not read toasts.txt file")
	}

	messages := make(chan telebot.Message)
	bot.Listen(messages, 1*time.Second)

	for message := range messages {
		if message.Text == "/hi" {
			bot.SendMessage(message.Chat,
				"Привет, "+message.Sender.FirstName+"!", nil)
		} else if strings.Contains(message.Text, "Тост!") {
			randomToast := toasts[rand.Intn(len(toasts))]
			bot.SendMessage(message.Chat, randomToast.Text, nil)
		} else if strings.Contains(strings.ToLower(message.Text), "костя") {
			bot.SendMessage(message.Chat, "Костя крутой!", nil)
		} else if strings.Contains(strings.ToLower(message.Text), "твоя!") {
			bot.SendMessage(message.Chat, "Нееееет, твоя!", nil)
		} else if strings.Contains(strings.ToLower(message.Text), "крутой") {
			bot.SendMessage(message.Chat, "Нееееет, "+message.Sender.FirstName+", это ты крутой!", nil)
		} else if strings.Contains(strings.ToLower(message.Text), "сокиабле") {
			bot.SendMessage(message.Chat, "Сокиабле? ЧОБЛЯ?", nil)
		} else if strings.Contains(strings.ToLower(message.Text), "доброе утро") {
			bot.SendMessage(message.Chat, "И тебе наидобрейшего утра, "+message.Sender.FirstName+"!", nil)
		} else if strings.Contains(strings.ToLower(message.Text), "поздравляй!") {
			bot.SendMessage(message.Chat, `С 8 марта поздравляем вас, коллеги,
От души хотим вам пожелать,
Чтоб совместные победы и успехи
Дали нам возможность процветать!
Чтоб в делах житейских и в работе
Находить умели компромисс,
Одевались по последней моде,
Были леди, то бишь миссис или мисс.
Чтобы было нам в кого влюбляться,
Чтобы было нас кому любить,
Молодыми вечно оставаться
и насыщенной веселой жизнью жить!`, nil)
		}

	}
}
开发者ID:grishin,项目名称:djigurbot,代码行数:53,代码来源:bot.go

示例14: newbot

func newbot(c *cli.Context) {
	var err error
	theBot, err = telebot.NewBot(c.String("tgtoken"))
	if err != nil {
		println(err.Error())
		os.Exit(TG_ERROR)
	}
	theBot.Messages = make(chan telebot.Message, 1000)
	theBot.Queries = make(chan telebot.Query, 1000)
	go messages()
	go queries()
	theBot.Start(1 * time.Second)
}
开发者ID:andresvia,项目名称:tg-kick-ban,代码行数:13,代码来源:bot.go

示例15: GetBotInstance

func GetBotInstance() *bot {
	bot_once.Do(func() {
		cfg := GetConfigurationInstance()

		tb, err := telebot.NewBot(cfg.TelegramKey)
		if err != nil {
			log.Fatal(err)
		}

		bot_instance = &bot{Connection: tb}
	})

	return bot_instance
}
开发者ID:Supro,项目名称:fitbot,代码行数:14,代码来源:bot.go


注:本文中的github.com/tucnak/telebot.NewBot函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。