Example #1
0
// Main aids in the creation of a basic command line gumble bot. It accepts the
// following flag arguments: --server, --username, --password, --insecure,
// --certificate, and --key.
//
// If init is non-nil, it is called before attempting to connect to the server.
func Main(init func(client *gumble.Client), listener gumble.EventListener) {
	server := flag.String("server", "localhost:64738", "Mumble server address")
	username := flag.String("username", "gumble-bot", "client username")
	password := flag.String("password", "", "client password")
	insecure := flag.Bool("insecure", false, "skip server certificate verification")
	certificateFile := flag.String("certificate", "", "user certificate file (PEM)")
	keyFile := flag.String("key", "", "user certificate key file (PEM)")

	if !flag.Parsed() {
		flag.Parse()
	}

	host, port, err := net.SplitHostPort(*server)
	if err != nil {
		host = *server
		port = strconv.Itoa(gumble.DefaultPort)
	}

	keepAlive := make(chan bool)

	// client
	config := gumble.NewConfig()
	config.Username = *username
	config.Password = *password
	config.Address = net.JoinHostPort(host, port)
	client := gumble.NewClient(config)
	if *insecure {
		config.TLSConfig.InsecureSkipVerify = true
	}
	if *certificateFile != "" {
		if *keyFile == "" {
			keyFile = certificateFile
		}
		if certificate, err := tls.LoadX509KeyPair(*certificateFile, *keyFile); err != nil {
			fmt.Printf("%s: %s\n", os.Args[0], err)
			os.Exit(1)
		} else {
			config.TLSConfig.Certificates = append(config.TLSConfig.Certificates, certificate)
		}
	}
	client.Attach(AutoBitrate)
	client.Attach(listener)
	client.Attach(Listener{
		Disconnect: func(e *gumble.DisconnectEvent) {
			keepAlive <- true
		},
	})
	if init != nil {
		init(client)
	}
	if err := client.Connect(); err != nil {
		fmt.Printf("%s: %s\n", os.Args[0], err)
		os.Exit(1)
	}

	<-keepAlive
}
Example #2
0
func main() {
	// setting configuration
	defaultchannel := "DragonHacks2016"

	config := gumble.NewConfig()
	config.Username = "******"
	config.Address = "rlyshw.com:64738"
	config.TLSConfig.InsecureSkipVerify = true

	keepAlive := make(chan bool)
	// generatiing a client instance
	client := gumble.NewClient(config)

	client.Attach(gumbleutil.AutoBitrate)
	// attaching client
	client.Attach(gumbleutil.Listener{
		TextMessage: func(e *gumble.TextMessageEvent) {
			fmt.Printf("Message received: %s\n", e.Message)
			e.Message = "joining"
			client.Send(e)
		},
	})

	// on-connect, perform the following
	client.Attach(gumbleutil.Listener{
		Connect: func(e *gumble.ConnectEvent) {
			fmt.Printf("Connected!!: %s\n", e.MaximumBitrate)
			fmt.Printf("User Channel: %s\n", client.Self.Channel.Name)
			for i, _ := range client.Channels {
				if client.Channels[i].Name == defaultchannel {
					client.Self.Move(client.Channels[i])
					break
				}
			}

			// outlining for audio operations
		},
	})

	client.Attach(gumbleutil.Listener{
		Disconnect: func(e *gumble.DisconnectEvent) {
			keepAlive <- true
		},
	})

	// connecting the client
	if err := client.Connect(); err != nil {
		panic(err)
		os.Exit(1)
	}
	// concurrency???
	<-keepAlive
}
Example #3
0
func (k *Mumble) Start(fl map[string]string, s *services.Services) {
	k.services = s

	//Config
	k.Config = gumble.NewConfig()
	k.Config.Username = fl["Flag_mumble_username"]
	k.Config.Password = fl["Flag_mumble_password"]
	k.Config.Address = fl["Flag_mumble_server"]

	k.Config.TLSConfig.InsecureSkipVerify = true

	k.conf_volume = 1.0

	//Client creation
	k.Client = gumble.NewClient(k.Config)

	//Attach listeners
	k.Client.Attach(gumbleutil.AutoBitrate)
	k.Client.Attach(k)

	//TLS
	if fl["Flag_mumble_cert_lock"] != "" {
		gumbleutil.CertificateLockFile(k.Client, fl["Flag_mumble_cert_lock"])
	}

	if _, err := os.Stat("./config/Kotik.pem"); err == nil && fl["Flag_dev"] == "false" {
		fl["Flag_mumble_cert"] = "./config/Kotik.pem"
	} else if _, err := os.Stat("./config/Kotik-dev.pem"); err == nil && fl["Flag_dev"] == "true" {
		fl["Flag_mumble_cert"] = "./config/Kotik-dev.pem"
	}

	if fl["Flag_mumble_cert"] != "" {
		if fl["Flag_mumble_cert_key"] == "" {
			fl["Flag_mumble_cert_key"] = fl["Flag_mumble_cert"]
		}
		if certificate, err := tls.LoadX509KeyPair(fl["Flag_mumble_cert"], fl["Flag_mumble_cert_key"]); err != nil {
			panic(err)
		} else {
			k.Config.TLSConfig.Certificates = append(k.Config.TLSConfig.Certificates, certificate)
		}
	}

	//Connect
	flag := false
	for flag == false {
		if err := k.Client.Connect(); err != nil {
			time.Sleep(time.Second * 5)
		} else {
			flag = true
		}
	}
}
Example #4
0
func main() {
	// Command line flags
	server := flag.String("server", "localhost:64738", "the server to connect to")
	username := flag.String("username", "", "the username of the client")
	insecure := flag.Bool("insecure", false, "skip server certificate verification")
	certificate := flag.String("certificate", "", "PEM encoded certificate and private key")

	flag.Parse()

	// Initialize
	b := barnard.Barnard{}
	b.Ui = uiterm.New(&b)

	// Gumble
	b.Config = gumble.NewConfig()
	b.Config.Username = *username
	b.Config.Address = *server
	if *insecure {
		b.Config.TLSConfig.InsecureSkipVerify = true
	}
	if *certificate != "" {
		if cert, err := tls.LoadX509KeyPair(*certificate, *certificate); err != nil {
			fmt.Fprintf(os.Stderr, "%s\n", err)
			os.Exit(1)
		} else {
			b.Config.TLSConfig.Certificates = []tls.Certificate{cert}
		}
	}

	b.Client = gumble.NewClient(b.Config)
	b.Client.Attach(gumbleutil.AutoBitrate)
	b.Client.Attach(&b)
	// Audio
	if os.Getenv("ALSOFT_LOGLEVEL") == "" {
		os.Setenv("ALSOFT_LOGLEVEL", "0")
	}
	if stream, err := gumble_openal.New(b.Client); err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err)
		os.Exit(1)
	} else {
		b.Stream = stream
	}

	if err := b.Client.Connect(); err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err)
		os.Exit(1)
	}

	b.Ui.Run()
}
Example #5
0
// main primarily performs startup tasks. Grabs and parses commandline
// args, sets up the gumble client and its listeners, and then connects to the server.
func main() {

	if currentUser, err := user.Current(); err == nil {
		dj.homeDir = currentUser.HomeDir
	}

	if err := loadConfiguration(); err == nil {
		fmt.Println("Configuration successfully loaded!")
	} else {
		panic(err)
	}

	var address, port, username, password, channel, pemCert, pemKey, accesstokens string
	var insecure bool
	var version bool

	flag.StringVar(&address, "server", "localhost", "address for Mumble server")
	flag.StringVar(&port, "port", "64738", "port for Mumble server")
	flag.StringVar(&username, "username", "MumbleDJ", "username of MumbleDJ on server")
	flag.StringVar(&password, "password", "", "password for Mumble server (if needed)")
	flag.StringVar(&channel, "channel", "root", "default channel for MumbleDJ")
	flag.StringVar(&pemCert, "cert", "", "path to user PEM certificate for MumbleDJ")
	flag.StringVar(&pemKey, "key", "", "path to user PEM key for MumbleDJ")
	flag.StringVar(&accesstokens, "accesstokens", "", "list of access tokens for channel auth")
	flag.BoolVar(&insecure, "insecure", false, "skip certificate checking")
	flag.BoolVar(&version, "version", false, "show version")
	flag.Parse()

	if version {
		fmt.Printf("MumbleDJ %s\n", VERSION)
		os.Exit(0)
	}
	dj.config = gumble.Config{
		Username: username,
		Password: password,
		Address:  address + ":" + port,
		Tokens:   strings.Split(accesstokens, " "),
	}
	dj.client = gumble.NewClient(&dj.config)

	dj.config.TLSConfig.InsecureSkipVerify = true
	if !insecure {
		gumbleutil.CertificateLockFile(dj.client, fmt.Sprintf("%s/.mumbledj/cert.lock", dj.homeDir))
	}
	if pemCert != "" {
		if pemKey == "" {
			pemKey = pemCert
		}
		if certificate, err := tls.LoadX509KeyPair(pemCert, pemKey); err != nil {
			panic(err)
		} else {
			dj.config.TLSConfig.Certificates = append(dj.config.TLSConfig.Certificates, certificate)
		}
	}

	dj.defaultChannel = strings.Split(channel, "/")

	services = append(services, Mixcloud{})
	CheckAPIKeys()

	dj.client.Attach(gumbleutil.Listener{
		Connect:     dj.OnConnect,
		Disconnect:  dj.OnDisconnect,
		TextMessage: dj.OnTextMessage,
		UserChange:  dj.OnUserChange,
	})
	dj.client.Attach(gumbleutil.AutoBitrate)

	if err := dj.client.Connect(); err != nil {
		fmt.Printf("Could not connect to Mumble server at %s:%s.\n", address, port)
		os.Exit(1)
	}

	<-dj.keepAlive
}
Example #6
0
//main parses command line argument and sets up the bot to connect
func main() {

	YouTubeAPICheck()

	if currentUser, err := user.Current(); err == nil {
		jew.homeDir = currentUser.HomeDir
	}

	if err := loadConfiguration(); err == nil {
		fmt.Println("Config loaded successfully!")
	} else {
		panic(err)
	}

	var address, port, username, password, pemCert, pemKey, accesstokens string
	var insecure bool

	flag.StringVar(&address, "server", "localhost", "addres of Mumble server")
	flag.StringVar(&port, "port", "64738", "port for Mumble server")
	flag.StringVar(&username, "username", "Jewvis", "username of bot")
	flag.StringVar(&password, "password", "", "password for Mumble server")
	flag.StringVar(&pemCert, "certificate", "", "path to PEM certificate")
	flag.StringVar(&pemKey, "key", "", "path to PEM key")
	flag.StringVar(&accesstokens, "accesstokens", "", "list of access tokens")
	flag.BoolVar(&insecure, "insecure", false, "skip certificate checking")
	flag.Parse()

	jew.config = gumble.Config{
		Username: username,
		Password: password,
		Address:  address + ":" + port,
		Tokens:   strings.Split(accesstokens, " "),
	}
	jew.client = gumble.NewClient(&jew.config)

	jew.config.TLSConfig.InsecureSkipVerify = true
	if !insecure {
		gumbleutil.CertificateLockFile(jew.client, fmt.Sprintf("%s/jewvis/cert.lock", jew.homeDir))
	}
	if pemCert != "" {
		if pemKey == "" {
			pemKey = pemCert
		}
		if certificate, err := tls.LoadX509KeyPair(pemCert, pemKey); err != nil {
			panic(err)
		} else {
			jew.config.TLSConfig.Certificates = append(jew.config.TLSConfig.Certificates, certificate)
		}
	}

	jew.client.Attach(gumbleutil.Listener{
		Connect:     jew.OnConnect,
		Disconnect:  jew.OnDisconnect,
		TextMessage: jew.OnTextMessage,
		UserChange:  jew.OnUserChange,
	})

	if err := jew.client.Connect(); err != nil {
		fmt.Print("Could not connect to server );", err)
		os.Exit(1)
	}

	<-jew.keepAlive
}
Example #7
0
func main() {
	// Flags
	username := flag.String("username", "piepan-bot", "username of the bot")
	password := flag.String("password", "", "user password")
	server := flag.String("server", "localhost:64738", "address of the server")
	certificateFile := flag.String("certificate", "", "user certificate file (PEM)")
	keyFile := flag.String("key", "", "user certificate key file (PEM)")
	insecure := flag.Bool("insecure", false, "skip certificate checking")
	lock := flag.String("lock", "", "server certificate lock file")
	ffmpeg := flag.String("ffmpeg", "ffmpeg", "ffmpeg-capable executable for media streaming")
	var accessTokens strFlagSlice
	flag.Var(&accessTokens, "access-token", "server access token (can be defined multiple times)")

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "piepan v0.7.0\n")
		fmt.Fprintf(os.Stderr, "usage: %s [options] [script files]\n", os.Args[0])
		fmt.Fprintf(os.Stderr, "an easy to use framework for writing scriptable Mumble bots\n")
		flag.PrintDefaults()
		fmt.Fprintf(os.Stderr, "\nScript files are defined in the following way:\n")
		fmt.Fprintf(os.Stderr, "  [type%c[environment%c]]filename\n", os.PathListSeparator, os.PathListSeparator)
		fmt.Fprintf(os.Stderr, "    filename: path to script file\n")
		fmt.Fprintf(os.Stderr, "    type: type of script file (default: file extension)\n")
		fmt.Fprintf(os.Stderr, "    environment: name of environment where script will be executed (default: type)\n\n")
		fmt.Fprintf(os.Stderr, "Enabled script types:\n")
		fmt.Fprintf(os.Stderr, "  Type         Name\n")
		for _, ext := range piepan.PluginExtensions {
			fmt.Fprintf(os.Stderr, "  %-12s %s\n", ext, piepan.Plugins[ext].Name)
		}
	}

	flag.Parse()

	// Configuration
	config := gumble.NewConfig()
	config.Username = *username
	config.Password = *password
	config.Address = *server
	config.Tokens = gumble.AccessTokens(accessTokens)

	client := gumble.NewClient(config)
	instance := piepan.New(client)
	audio := gumble_ffmpeg.New(client)
	audio.Command = *ffmpeg
	instance.Audio = audio

	if *insecure {
		config.TLSConfig.InsecureSkipVerify = true
	}
	if *lock != "" {
		gumbleutil.CertificateLockFile(client, *lock)
	}
	if *certificateFile != "" {
		if *keyFile == "" {
			keyFile = certificateFile
		}
		if certificate, err := tls.LoadX509KeyPair(*certificateFile, *keyFile); err != nil {
			panic(err)
		} else {
			config.TLSConfig.Certificates = append(config.TLSConfig.Certificates, certificate)
		}
	}

	client.Attach(gumbleutil.AutoBitrate)

	// Load scripts
	for _, script := range flag.Args() {
		if err := instance.LoadScript(script); err != nil {
			fmt.Fprintf(os.Stderr, "%s: %s\n", script, err)
		}
	}

	keepAlive := make(chan bool)
	exitStatus := 0
	client.Attach(gumbleutil.Listener{
		Disconnect: func(e *gumble.DisconnectEvent) {
			if e.Type != gumble.DisconnectUser {
				exitStatus = int(e.Type) + 1
			}
			keepAlive <- true
		},
	})

	if err := client.Connect(); err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err)
		os.Exit(1)
	}

	<-keepAlive
	os.Exit(exitStatus)
}
Example #8
0
func (a *adapter) startMumbleConnection() error {
	config := gumble.NewConfig()

	config.Address = net.JoinHostPort(a.server, strconv.Itoa(a.port))
	config.Username = a.Robot.Name
	config.Password = a.password
	config.TLSConfig.InsecureSkipVerify = true
	config.AudioInterval = 10 * time.Millisecond

	conn := gumble.NewClient(config)

	conn.Attach(gumbleutil.AutoBitrate)
	conn.Attach(&gumbleutil.Listener{
		Connect: func(e *gumble.ConnectEvent) {
			hal.Logger.Debug("mumble: connected")

			for _, channel := range e.Client.Channels {
				if strings.ToLower(channel.Name) == a.channel {
					e.Client.Self.Move(channel)
					break
				}
			}

			a.setSelfAvatar()

			go a.ttsGoRoutine()
		},

		Disconnect: func(e *gumble.DisconnectEvent) {
			close(a.speakChan)
		},

		TextMessage: func(e *gumble.TextMessageEvent) {
			message := a.newTextMessage(e)
			if message == nil {
				return
			}

			if err := a.Receive(message); err != nil {
				hal.Logger.Errorf("mumble: error in message receive: %v", err)
			}
		},

		UserChange: func(e *gumble.UserChangeEvent) {
			// TODO: Detect leaving
			if e.Type&gumble.UserChangeChannel != gumble.UserChangeChannel { // We only care about joining and leaving
				return
			}

			if e.User.Session == e.Client.Self.Session {
				return // Ignore our own events
			}

			if e.User.Channel.ID != e.Client.Self.Channel.ID {
				return // If they aren't joining this channel, ignore them
			}

			msg := &hal.Message{
				Type: hal.ENTER,

				User: hal.User{
					ID:   e.User.Name,
					Name: e.User.Name,
				},

				Room: e.User.Channel.Name,
			}

			if err := a.Receive(msg); err != nil {
				hal.Logger.Errorf("mumble: error in enter receive: %v", err)
			}
		},
	})

	a.client = conn

	err := conn.Connect()
	if err != nil {
		return err
	}

	hal.Logger.Debug("mumble: connecting...")

	return nil
}
Example #9
0
func main() {
	// Flags
	username := flag.String("username", "piepan-bot", "username of the bot")
	password := flag.String("password", "", "user password")
	server := flag.String("server", "localhost:64738", "address of the server")
	certificateFile := flag.String("certificate", "", "user certificate file (PEM)")
	keyFile := flag.String("key", "", "user certificate key file (PEM)")
	insecure := flag.Bool("insecure", false, "skip certificate checking")
	lock := flag.String("lock", "", "server certificate lock file")
	ffmpeg := flag.String("ffmpeg", "ffmpeg", "ffmpeg-capable executable for media streaming")
	var accessTokens strFlagSlice
	flag.Var(&accessTokens, "access-token", "server access token (can be defined multiple times)")

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "piepan v0.9.0\n")
		fmt.Fprintf(os.Stderr, "usage: %s [options] [script files]\n", os.Args[0])
		fmt.Fprintf(os.Stderr, "an easy to use framework for writing Mumble bots using Lua\n")
		flag.PrintDefaults()
	}

	flag.Parse()

	// Configuration
	config := gumble.NewConfig()
	config.Username = *username
	config.Password = *password
	config.Address = *server
	config.Tokens = gumble.AccessTokens(accessTokens)

	client := gumble.NewClient(config)
	instance := piepan.New(client)
	instance.AudioCommand = *ffmpeg

	if *insecure {
		config.TLSConfig.InsecureSkipVerify = true
	}
	if *lock != "" {
		gumbleutil.CertificateLockFile(client, *lock)
	}
	if *certificateFile != "" {
		if *keyFile == "" {
			keyFile = certificateFile
		}
		certificate, err := tls.LoadX509KeyPair(*certificateFile, *keyFile)
		if err != nil {
			fmt.Fprintf(os.Stderr, "%s\n", err)
			os.Exit(1)
		}
		config.TLSConfig.Certificates = append(config.TLSConfig.Certificates, certificate)
	}

	client.Attach(gumbleutil.AutoBitrate)

	// Load scripts
	for _, script := range flag.Args() {
		if err := instance.LoadFile(script); err != nil {
			fmt.Fprintf(os.Stderr, "%s: %s\n", script, err)
		}
	}

	keepAlive := make(chan bool)
	exitStatus := 0
	client.Attach(gumbleutil.Listener{
		Disconnect: func(e *gumble.DisconnectEvent) {
			if e.Type != gumble.DisconnectUser {
				exitStatus = int(e.Type) + 1
			}
			keepAlive <- true
		},
	})

	if err := client.Connect(); err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err)
		os.Exit(1)
	}

	<-keepAlive
	os.Exit(exitStatus)
}
Example #10
0
func (m *Mumble) Create() {
	m.Client = gumble.NewClient(m.Config)

	// we'll use this to move users
	// from channels that they're not
	// allowed to get into
	rc := new(gumble.Channel)
	rc.ID = 0 // 0 is the root channel

	removeTemporaryChannels := func() {
		for _, c := range Channels {
			if c.Temporary == true && c.IsEmpty() {
				c.Remove()
			}
		}
	}

	e := gumbleutil.Listener{
		// runs when the bot connect
		Connect: func(e *gumble.ConnectEvent) {
			log.Println("[BOT]: Connected")

			e.Client.Self.Request(gumble.RequestACL)
			e.Client.Self.Request(gumble.RequestPermission)
			e.Client.Self.Request(gumble.RequestUserList)

			// copy channels
			for _, gc := range e.Client.Channels {
				if gc.IsRoot() {
					c := NewChannel()
					c.Name = gc.Name
					c.Temporary = gc.Temporary

					Channels[gc.Name] = c
				}
			}

			// get all users stats on connect
			for _, v := range e.Client.Users {
				log.Println(fmt.Sprintf("Requesting stats for User[Name: %s ID: %s Registered: %s Hash: %s]",
					v.Name, UserIdToString(v.UserID), strconv.FormatBool(v.IsRegistered()), v.Hash))

				// request user stats
				//
				// stats will be available
				// after event: "UserChangeStats"
				v.Request(gumble.RequestStats)
			}

			// register bot
			if !e.Client.Self.IsRegistered() {
				e.Client.Self.Register()
			}
		},

		// user events
		UserChange: func(e *gumble.UserChangeEvent) {

			// user connected
			if e.Type.Has(gumble.UserChangeConnected) {
				log.Println(fmt.Sprintf("[Connected]: User[Name: %s ID: %s]",
					e.User.Name, UserIdToString(e.User.UserID)))

				// "e.User.Stats" is always nil when a user connects
				// so we'll get the user's stats
				// "e.User.Stats" will be available
				// after event: "gumble.UserChangeStats"
				e.User.Request(gumble.RequestStats)

				removeTemporaryChannels()
			}

			if e.Type.Has(gumble.UserChangeDisconnected) {
				log.Println(fmt.Sprintf("[UserChangeDisconnected]: User[Name: %s ID: %s]",
					e.User.Name, UserIdToString(e.User.UserID)))

				removeTemporaryChannels()
			}

			if e.Type.Has(gumble.UserChangeKicked) {
				log.Println(fmt.Sprintf("[UserChangeKicked]: User[Name: %s ID: %s Hash: %s]",
					e.User.Name, UserIdToString(e.User.UserID), e.User.Hash))
			}

			if e.Type.Has(gumble.UserChangeBanned) {
				log.Println(fmt.Sprintf("[UserChangeBanned]: User[Name: %s ID: %s Hash: %s]",
					e.User.Name, UserIdToString(e.User.UserID), e.User.Hash))
			}

			// user change registered
			if e.Type.Has(gumble.UserChangeRegistered) {
				log.Println(fmt.Sprintf("[UserChangeRegistered]: User[Name: %s ID: %s Hash: %s]",
					e.User.Name, UserIdToString(e.User.UserID), e.User.Hash))
			}

			if e.Type.Has(gumble.UserChangeUnregistered) {
				log.Println(fmt.Sprintf("[UserChangeUnregistered]: User[Name: %s ID: %s Hash: %s]",
					e.User.Name, UserIdToString(e.User.UserID), e.User.Hash))
			}

			if e.Type.Has(gumble.UserChangeName) {
				log.Println("[UserChangeName]: User changed name to " + e.User.Name)
			}

			// user change channel
			if e.Type.Has(gumble.UserChangeChannel) {
				removeTemporaryChannels()

				// check for nil because when a user connects
				// stats are always nil
				if e.User.Stats != nil {
					log.Println(fmt.Sprintf("[Channel]: User[Name: %s ID: %s Hash: %s IP: %s] is now at: %s",
						e.User.Name, UserIdToString(e.User.UserID), e.User.Hash,
						e.User.Stats.IP.String(), e.User.Channel.Name))

					id := e.User.Channel.Name
					if !e.User.Channel.IsRoot() && !e.User.Channel.Parent.IsRoot() {
						id = e.User.Channel.Parent.Name + "_" + e.User.Channel.Name
					}

					if !e.User.Channel.IsRoot() && Channels[id] != nil {
						u := NewUser()
						u.CopyInfo(e.User)

						ok, err := Channels[id].IsUserAllowed(u)
						if err != nil {
							log.Println(err)
						}

						if !ok {
							e.User.Move(e.User.Channel.Parent)

							log.Println(fmt.Sprintf("[BOT]: Moved User[%s:%s] to parent channel",
								e.User.Name, UserIdToString(e.User.UserID)))
						}
					}
				} else {
					if !e.User.Channel.IsRoot() {
						e.User.Move(rc)

						log.Println(fmt.Sprintf("[BOT]: Moved User[%s:%s] to root channel",
							e.User.Name, UserIdToString(e.User.UserID)))
					}
				}
			}

			if e.Type.Has(gumble.UserChangeComment) {
				log.Println("User changed comment")
			}

			if e.Type.Has(gumble.UserChangeAudio) {
				log.Println("User changed audio")

				u := NewUser()
				u.CopyInfo(e.User)
				muted, deafened, err := u.IsMD()

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

				log.Println("[MD]: " + strconv.FormatBool(muted) + " - " + strconv.FormatBool(deafened))
			}

			if e.Type.Has(gumble.UserChangeTexture) {
				log.Println("User changed texture")
			}

			if e.Type.Has(gumble.UserChangePrioritySpeaker) {
				log.Println("User priority speaker")
			}

			if e.Type.Has(gumble.UserChangeRecording) {
				log.Println("User recording")
			}

			if e.Type.Has(gumble.UserChangeStats) {
				log.Println(fmt.Sprintf("[UserChangeStats]: User[%s @ %s, Hash: %s]",
					e.User.Name, e.User.Stats.IP.String(), e.User.Hash))
			}
		},

		// runs when the bot disconnect
		Disconnect: func(e *gumble.DisconnectEvent) {
			log.Println("[BOT]: Disconnected -> " + e.String)

			// just to make sure the bot reconnects
			ticker := time.NewTicker(5 * time.Second)
			for _ = range ticker.C {
				if m.Client.Conn == nil {
					err := m.Connect()
					if err != nil {
						log.Println(err)
					}

				} else {
					ticker.Stop()
					break
				}
			}

			//m.KeepAlive <- true
		},

		ACL: func(e *gumble.ACLEvent) {
			log.Println("[ACL]: " + strconv.FormatBool(e.ACL.Inherits))
		},

		PermissionDenied: func(e *gumble.PermissionDeniedEvent) {
			var dType string

			// full channel
			if e.Type.Has(gumble.PermissionDeniedChannelFull) {
				dType = "Channel is full!"
			}

			// missing certificate
			if e.Type.Has(gumble.PermissionDeniedMissingCertificate) {
				dType = "User is missing certificate!"
			}

			// invalid channel name
			if e.Type.Has(gumble.PermissionDeniedInvalidChannelName) {
				dType = "Invalid channel name!"
			}

			// invalid user name
			if e.Type.Has(gumble.PermissionDeniedInvalidUserName) {
				dType = "Invalid user name!"
			}

			// permission
			if e.Type.Has(gumble.PermissionDeniedPermission) {
				dType = "You have no permission!"
			}

			// other
			if e.Type.Has(gumble.PermissionDeniedOther) {
				dType = "I dont know what the denied permission is and at this point im too afraid to ask"
			}

			log.Println("[BOT]: Permission Denied -> " + dType)
			log.Println(e.Permission)
		},
	}

	// insert events to event listener
	// and attach to gumble client
	el := gumble.EventListener(e)
	m.Client.Attach(el)
}
Example #11
0
func main() {

	if currentUser, err := user.Current(); err == nil {
		jew.homeDir = currentUser.HomeDir
	}

	if err := loadConfig(); err == nil {
		fmt.Println("Config loaded!")
	} else {
		panic(err)
	}

	var address, port, username, password, channel, pemCert, pemKey, accesstokens string
	var insecure, version bool

	flag.StringVar(&address, "server", "localhost", "IP of server")
	flag.StringVar(&port, "port", "64738", "Port of server")
	flag.StringVar(&username, "username", "Jewbot", "Username of bot")
	flag.StringVar(&password, "password", "", "Server Password")
	flag.StringVar(&channel, "channel", "", "Default Channel to Enter")
	flag.StringVar(&pemCert, "cert", "", "Path to PEM Certificate")
	flag.StringVar(&pemKey, "key", "", "Path to PEM Key")
	flag.StringVar(&accesstokens, "accesstokens", "", "List of Access Tokens")
	flag.BoolVar(&insecure, "insecure", false, "Skip Certificate Checking")
	flag.BoolVar(&version, "version", false, "Show Version")
	flag.Parse()

	if version {
		fmt.Printf("Jewbot %s\n", VERSION)
		os.Exit(0)
	}

	jew.config = gumble.Config{
		Username: username,
		Password: password,
		Address:  address + ":" + port,
		Tokens:   strings.Split(accesstokens, " "),
	}

	jew.client = gumble.NewClient(&jew.config)

	jew.config.TLSConfig.InsecureSkipVerify = true

	if pemCert != "" {
		if pemKey == "" {
			pemKey = pemCert
		}
		if certificate, err := tls.LoadX509KeyPair(pemCert, pemKey); err != nil {
			panic(err)
		} else {
			jew.config.TLSConfig.Certificates = append(jew.config.TLSConfig.Certificates, certificate)
		}
	}

	jew.defaultChannel = strings.Split(channel, "/")

	services = append(services, Mixcloud{})
	CheckAPIKeys()

	jew.client.Attach(gumbleutil.Listener{
		Connect:     jew.OnConnect,
		Disconnect:  jew.OnDisconnect,
		TextMessage: jew.OnTextMessage,
		UserChange:  jew.OnUserChange,
	})

	jew.client.Attach(gumbleutil.AutoBitrate)

	if err := jew.client.Connect(); err != nil {
		fmt.Printf("Can't connect")
		os.Exit(1)
	}

	<-jew.keepAlive
}
Example #12
0
File: main.go Project: wlcx/watbot
func main() {
	godotenv.Load()

	bot, err := tgbotapi.NewBotAPI(os.Getenv("TG_TOKEN"))
	if err != nil {
		log.Fatal("Error creating bot: " + err.Error())
	}

	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	updates, err := bot.GetUpdatesChan(u)
	if err != nil {
		log.Panic(err)
	}

	// Mumble config
	mumbleParsedURL, err := url.Parse(os.Getenv("MUMBLE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	if mumbleParsedURL.User.Username() == "" {
		log.Fatal("Mumble URL must include a username")
	}
	mumbleConf := gumble.NewConfig()
	if !strings.ContainsRune(mumbleParsedURL.Host, ':') { // If address does not specify port...
		mumbleConf.Address = mumbleParsedURL.Host + ":64738"
	} else {
		mumbleConf.Address = mumbleParsedURL.Host
	}
	mumbleConf.Username = mumbleParsedURL.User.Username()
	if pass, ok := mumbleParsedURL.User.Password(); ok {
		mumbleConf.Password = pass
	}
	client := gumble.NewClient(mumbleConf)

	client.Attach(gumbleutil.Listener{
		UserChange: func(e *gumble.UserChangeEvent) {
			if e.Type.Has(gumble.UserChangeConnected) {
				fmt.Println("User connected!")
				sendToChat(bot, fmt.Sprintf("%s connected #cgsnotify", e.User.Name))
			}
		},
		Disconnect: func(e *gumble.DisconnectEvent) {
			switch {
			case e.Type.Has(gumble.DisconnectError):
				sendToChat(bot, "Disconnected from mumble due to error, reconnecting in 5s")
				time.Sleep(5 * time.Second)
				e.Client.Connect()
			case e.Type.Has(gumble.DisconnectKicked):
				sendToChat(bot, "I just got kicked from mumble - rejoining out of spite")
				e.Client.Connect()
			case e.Type.Has(gumble.DisconnectBanned):
				sendToChat(bot, "I just got banned from mumble! Rude!")
			}
		},
	})
	if err := client.Connect(); err != nil {
		panic(err)
	}
	for update := range updates {
		log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
		switch update.Message.Text {
		case "/users":
			var users []string
			for _, user := range client.Users {
				if user.Session != client.Self.Session { // Skip adding ourself to the online users
					users = append(users, user.Name)
				}
			}
			if len(users) == 0 {
				users = []string{"Noone"}
			}

			var isare string
			if len(users) < 2 {
				isare = "is"
			} else {
				isare = "are"
			}

			bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf("%s %s online", prettyListify(users), isare)))

		case "/chatid":
			bot.Send(tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf("This chat's ID: %d", update.Message.Chat.ID)))
		}
	}
}
Example #13
0
func (b *BOT) create() {
	b.Client = gumble.NewClient(b.Config)

	e := gumbleutil.Listener{
		// runs when the bot connect
		Connect: func(e *gumble.ConnectEvent) {
			log.Println("[BOT]: ConnecTed")

			// get bot stats
			e.Client.Self.Request(gumble.RequestStats)
		},

		// user events
		UserChange: func(e *gumble.UserChangeEvent) {

			// user connected
			if e.Type.Has(gumble.UserChangeConnected) {
				log.Println(fmt.Sprintf("[Connected]: User[Name: %s ID: %s]",
					e.User.Name, mumble.UserIdToString(e.User.UserID)))
			}

			if e.Type.Has(gumble.UserChangeDisconnected) {
				log.Println(fmt.Sprintf("[Disconnected]: User[Name: %s ID: %s]",
					e.User.Name, mumble.UserIdToString(e.User.UserID)))
			}

			if e.Type.Has(gumble.UserChangeKicked) {
				log.Println("User kicked")
			}

			if e.Type.Has(gumble.UserChangeBanned) {
				log.Println("User banned")
			}

			// user change registered
			if e.Type.Has(gumble.UserChangeRegistered) {
				log.Println(fmt.Sprintf("[UserChangeRegistered]: User[Name: %s ID: %s Hash: %s]",
					e.User.Name, mumble.UserIdToString(e.User.UserID), e.User.Hash))
			}

			if e.Type.Has(gumble.UserChangeUnregistered) {
				log.Println("User unregistered")
			}

			if e.Type.Has(gumble.UserChangeName) {
				log.Println("User changed name")
			}

			// user change channel
			if e.Type.Has(gumble.UserChangeChannel) {
			}

			if e.Type.Has(gumble.UserChangeComment) {
				log.Println("User changed comment")
			}

			if e.Type.Has(gumble.UserChangeAudio) {
				log.Println("User changed audio")
			}

			if e.Type.Has(gumble.UserChangeTexture) {
				log.Println("User changed texture")
			}

			if e.Type.Has(gumble.UserChangePrioritySpeaker) {
				log.Println("User priority speaker")
			}

			if e.Type.Has(gumble.UserChangeRecording) {
				log.Println("User recording")
			}

			if e.Type.Has(gumble.UserChangeStats) {
				log.Println("[UserChangeStats]: User[" + e.User.Name + " @ " + e.User.Stats.IP.String() + "]")
			}
		},

		// runs when the bot disconnect
		Disconnect: func(e *gumble.DisconnectEvent) {
			log.Println("[BOT]: Disconnected -> " + e.String)
			b.KeepAlive <- true
		},

		PermissionDenied: func(e *gumble.PermissionDeniedEvent) {
			var dType string

			// text length
			if e.Type.Has(gumble.PermissionDeniedTextTooLong) {
				dType = "Text too long!"
			}

			// full channel
			if e.Type.Has(gumble.PermissionDeniedChannelFull) {
				dType = "Channel is full!"
			}

			// missing certificate
			if e.Type.Has(gumble.PermissionDeniedMissingCertificate) {
				dType = "User is missing certificate!"
			}

			// invalid channel name
			if e.Type.Has(gumble.PermissionDeniedInvalidChannelName) {
				dType = "Invalid channel name!"
			}

			// invalid user name
			if e.Type.Has(gumble.PermissionDeniedInvalidUserName) {
				dType = "Invalid user name!"
			}

			// permission
			if e.Type.Has(gumble.PermissionDeniedPermission) {
				dType = "You have no permission!"
			}

			// other
			if e.Type.Has(gumble.PermissionDeniedOther) {
				dType = "dunno"
			}

			log.Println("[BOT]: Permission Denied -> " + dType)
			log.Println(e.Permission)
		},
	}

	// insert events to event listener
	// and attach to gumble client
	el := gumble.EventListener(e)
	b.Client.Attach(el)
}