예제 #1
0
		private bool InitializeBot()
		{
			// Read Config File
			const string configFilePath = "configTS3AudioBot.cfg";
			ConfigFile cfgFile = ConfigFile.Open(configFilePath) ?? ConfigFile.Create(configFilePath) ?? ConfigFile.GetDummy();
			var afd = cfgFile.GetDataStruct<AudioFrameworkData>(typeof(AudioFramework), true);
			var bcd = cfgFile.GetDataStruct<BobControllerData>(typeof(BobController), true);
			var qcd = cfgFile.GetDataStruct<QueryConnectionData>(typeof(QueryConnection), true);
			var hmd = cfgFile.GetDataStruct<HistoryManagerData>(typeof(HistoryManager), true);
			var pmd = cfgFile.GetDataStruct<PluginManagerData>(typeof(PluginManager), true);
			var pld = cfgFile.GetDataStruct<PlaylistManagerData>(typeof(PlaylistManager), true);
			mainBotData = cfgFile.GetDataStruct<MainBotData>(typeof(MainBot), true);
			cfgFile.Close();

			if (consoleOutput)
			{
				Log.RegisterLogger("[%T]%L: %M", "", Console.WriteLine);
			}

			if (writeLog && !string.IsNullOrEmpty(mainBotData.logFile))
			{
				var encoding = new UTF8Encoding(false);
				logStream = new StreamWriter(File.Open(mainBotData.logFile, FileMode.Append, FileAccess.Write, FileShare.Read), encoding);
				Log.RegisterLogger("[%T]%L: %M\n" + (writeLogStack ? "%S\n" : ""), "", (msg) =>
				{
					if (logStream != null)
						try
						{
							logStream.Write(msg);
							logStream.Flush();
						}
						catch (IOException) { }
				});
			}

			Log.Write(Log.Level.Info, "[============ TS3AudioBot started =============]");
			string dateStr = DateTime.Now.ToLongDateString();
			Log.Write(Log.Level.Info, "[=== Date: {0}{1} ===]", new string(' ', Math.Max(0, 32 - dateStr.Length)), dateStr);
			string timeStr = DateTime.Now.ToLongTimeString();
			Log.Write(Log.Level.Info, "[=== Time: {0}{1} ===]", new string(' ', Math.Max(0, 32 - timeStr.Length)), timeStr);
			Log.Write(Log.Level.Info, "[==============================================]");

			Log.Write(Log.Level.Info, "[============ Initializing Commands ===========]");
			CommandManager = new CommandManager();
			CommandManager.RegisterMain(this);

			Log.Write(Log.Level.Info, "[============ Initializing Modules ============]");
			QueryConnection = new QueryConnection(qcd);
			var playlistManager = new PlaylistManager(pld);
			BobController = new BobController(bcd, QueryConnection);
			// old: new VLCConnection(afd.vlcLocation);
			// new: BobController
			AudioFramework = new AudioFramework(afd, BobController, playlistManager);
			SessionManager = new SessionManager();
			HistoryManager = new HistoryManager(hmd);
			PluginManager = new PluginManager(this, pmd);

			Log.Write(Log.Level.Info, "[=========== Initializing Factories ===========]");
			FactoryManager = new ResourceFactoryManager(AudioFramework);
			FactoryManager.DefaultFactorty = new MediaFactory();
			FactoryManager.AddFactory(new YoutubeFactory());
			FactoryManager.AddFactory(new SoundcloudFactory());
			FactoryManager.AddFactory(new TwitchFactory());

			Log.Write(Log.Level.Info, "[=========== Registering callbacks ============]");
			// Inform our HistoryManager when a new resource started successfully
			AudioFramework.OnResourceStarted += HistoryManager.LogAudioResource;
			// Inform the BobClient on start/stop
			AudioFramework.OnResourceStarted += BobController.OnResourceStarted;
			AudioFramework.OnResourceStopped += BobController.OnResourceStopped;
			// In own favor update the own status text to the current song title
			AudioFramework.OnResourceStarted += SongUpdateEvent;
			// Register callback for all messages happening
			QueryConnection.OnMessageReceived += TextCallback;
			// Register callback to remove open private sessions, when user disconnects
			QueryConnection.OnClientDisconnect += (s, e) => SessionManager.RemoveSession(e.InvokerId);


			Log.Write(Log.Level.Info, "[================= Finalizing =================]");
			// Create a default session for all users in all chat
			SessionManager.DefaultSession = new PublicSession(this);
			// Connect the query after everyting is set up
			try { QueryConnection.Connect(); }
			catch (QueryCommandException qcex)
			{
				Log.Write(Log.Level.Error, "There is either a problem with your connection configuration, or the query has not all permissions it needs. ({0})", qcex);
				return false;
			}

			Log.Write(Log.Level.Info, "[============== Connected & Done ==============]");
			return true;
		}
예제 #2
0
        internal R SetupRights(string key, MainBotData mainBotData)
        {
            try
            {
                // Check all own server groups
                var groups = GetClientServerGroups(me.DatabaseId);

                // Add self to master group (via token)
                if (!string.IsNullOrEmpty(key))
                {
                    tsBaseClient.PrivilegeKeyUse(key);
                }

                // Remember new group (or check if in new group at all)
                var groupsNew = GetClientServerGroups(me.DatabaseId);
                var groupDiff = groupsNew.Except(groups).ToArray();

                if (mainBotData.BotGroupId == 0)
                {
                    // Create new Bot group
                    var botGroup = tsBaseClient.ServerGroupAdd("ServerBot");
                    mainBotData.BotGroupId = botGroup.ServerGroupId;

                    // Add self to new group
                    tsBaseClient.ServerGroupAddClient(botGroup.ServerGroupId, me.DatabaseId);
                }

                const int max = 75;
                // Add various rights to the bot group
                tsBaseClient.ServerGroupAddPerm(mainBotData.BotGroupId,
                                                new[] {
                    PermissionId.i_client_whisper_power,                         // + Required for whisper channel playing
                    PermissionId.i_client_private_textmessage_power,             // + Communication
                    PermissionId.b_client_server_textmessage_send,               // + Communication
                    PermissionId.b_client_channel_textmessage_send,              // (+) Communication, could be used but not yet

                    PermissionId.b_client_modify_dbproperties,                   // ? Dont know but seems also required for the next one
                    PermissionId.b_client_modify_description,                    // + Used to change the description of our bot
                    PermissionId.b_client_info_view,                             // (+) only used as fallback usually
                    PermissionId.b_virtualserver_client_list,                    // ? Dont know but seems also required for the next one

                    PermissionId.i_channel_subscribe_power,                      // + Required to find user to communicate
                    PermissionId.b_virtualserver_client_dbinfo,                  // + Required to get basic user information for history, api, etc...
                    PermissionId.i_client_talk_power,                            // + Required for normal channel playing
                    PermissionId.b_client_modify_own_description,                // ? not sure if this makes b_client_modify_description superfluous

                    PermissionId.b_group_is_permanent,                           // + Group should stay even if bot disconnects
                    PermissionId.i_client_kick_from_channel_power,               // + Optional for kicking
                    PermissionId.i_client_kick_from_server_power,                // + Optional for kicking
                    PermissionId.i_client_max_clones_uid,                        // + In case that bot times out and tries to join again

                    PermissionId.b_client_ignore_antiflood,                      // + The bot should be resistent to forced spam attacks
                    PermissionId.b_channel_join_ignore_password,                 // + The noble bot will not abuse this power
                    PermissionId.b_channel_join_permanent,                       // + Allow joining to all channel even on strict servers
                    PermissionId.b_channel_join_semi_permanent,                  // + Allow joining to all channel even on strict servers

                    PermissionId.b_channel_join_temporary,                       // + Allow joining to all channel even on strict servers
                    PermissionId.b_channel_join_ignore_maxclients,               // + Allow joining full channels
                    PermissionId.i_channel_join_power,                           // + Allow joining to all channel even on strict servers
                },
                                                new[] {
                    max, max, 1, 1,
                    1, 1, 1, 1,
                    max, 1, max, 1,
                    1, max, max, 4,
                    1, 1, 1, 1,
                    1, 1, max,
                },
                                                new[] {
                    false, false, false, false,
                    false, false, false, false,
                    false, false, false, false,
                    false, false, false, false,
                    false, false, false, false,
                    false, false, false,
                },
                                                new[] {
                    false, false, false, false,
                    false, false, false, false,
                    false, false, false, false,
                    false, false, false, false,
                    false, false, false, false,
                    false, false, false,
                });

                // Leave master group again
                if (groupDiff.Length > 0)
                {
                    foreach (var grp in groupDiff)
                    {
                        tsBaseClient.ServerGroupDelClient(grp, me.DatabaseId);
                    }
                }

                return(R.OkR);
            }
            catch (Ts3CommandException cex)
            {
                Log.Write(Log.Level.Warning, cex.ErrorStatus.ErrorFormat());
                return("Auto setup failed! (See logs for more details)");
            }
        }
예제 #3
0
파일: Bot.cs 프로젝트: HellBz/TS3AudioBot
        public R InitializeBot()
        {
            Log.Info("Bot connecting...");

            // Read Config File
            var afd  = Config.GetDataStruct <AudioFrameworkData>("AudioFramework", true);
            var tfcd = Config.GetDataStruct <Ts3FullClientData>("QueryConnection", true);
            var hmd  = Config.GetDataStruct <HistoryManagerData>("HistoryManager", true);
            var pld  = Config.GetDataStruct <PlaylistManagerData>("PlaylistManager", true);

            mainBotData = Config.GetDataStruct <MainBotData>("MainBot", true);

            AudioValues.audioFrameworkData = afd;

            Injector.RegisterType <Bot>();
            Injector.RegisterType <BotInjector>();
            Injector.RegisterType <PlaylistManager>();
            Injector.RegisterType <TeamspeakControl>();
            Injector.RegisterType <SessionManager>();
            Injector.RegisterType <HistoryManager>();
            Injector.RegisterType <PlayManager>();
            Injector.RegisterType <IPlayerConnection>();
            Injector.RegisterType <ITargetManager>();
            Injector.RegisterType <Ts3BaseFunctions>();

            Injector.RegisterModule(this);
            Injector.RegisterModule(Injector);
            Injector.RegisterModule(new PlaylistManager(pld));
            var teamspeakClient = new Ts3Full(tfcd);

            Injector.RegisterModule(teamspeakClient);
            Injector.RegisterModule(teamspeakClient.GetLowLibrary <Ts3FullClient>());
            Injector.RegisterModule(new SessionManager());
            HistoryManager historyManager = null;

            if (hmd.EnableHistory)
            {
                Injector.RegisterModule(historyManager = new HistoryManager(hmd), x => x.Initialize());
            }
            Injector.RegisterModule(new PlayManager());
            Injector.RegisterModule(teamspeakClient.TargetPipe);

            if (!Injector.AllResolved())
            {
                Log.Warn("Cyclic bot module dependency");
                Injector.ForceCyclicResolve();
                if (!Injector.AllResolved())
                {
                    Log.Error("Missing bot module dependency");
                    return("Could not load all bot modules");
                }
            }

            PlayerConnection.OnSongEnd        += PlayManager.SongStoppedHook;
            PlayManager.BeforeResourceStarted += BeforeResourceStarted;
            // In own favor update the own status text to the current song title
            PlayManager.AfterResourceStarted += LoggedUpdateBotStatus;
            PlayManager.AfterResourceStopped += LoggedUpdateBotStatus;
            // Log our resource in the history
            if (hmd.EnableHistory)
            {
                PlayManager.AfterResourceStarted += (s, e) => historyManager.LogAudioResource(new HistorySaveData(e.PlayResource.BaseData, e.Owner));
            }
            // Update our thumbnail
            PlayManager.AfterResourceStarted += GenerateStatusImage;
            PlayManager.AfterResourceStopped += GenerateStatusImage;
            // Register callback for all messages happening
            QueryConnection.OnMessageReceived += TextCallback;
            // Register callback to remove open private sessions, when user disconnects
            QueryConnection.OnClientDisconnect += OnClientDisconnect;
            QueryConnection.OnBotDisconnect    += (s, e) => Dispose();
            QueryConnection.OnBotConnected     += OnBotConnected;
            BadgesString = tfcd.ClientBadges;

            // Connect the query after everyting is set up
            try { QueryConnection.Connect(); }
            catch (Ts3Exception qcex)
            {
                Log.Info(qcex, "There is either a problem with your connection configuration, or the query has not all permissions it needs.");
                return("Query error");
            }
            return(R.OkR);
        }