/// <summary>
 /// Logs in to Stack Exchange using the provided credentials via Open Id 
 /// </summary>
 /// <param name="credentials"></param>
 private void LoginToStackExchange(BotCredentials credentials)
 {
     Response loginResponse = Client.Request("https://openid.stackexchange.com/account/login/").Get();
     string fkey = GetFKeyFromHtml(loginResponse.Content);
     string form = string.Format("email={0}&password={1}&fkey={2}", Uri.EscapeDataString(credentials.Username), Uri.EscapeDataString(credentials.Password), fkey);
     Client.Request("https://openid.stackexchange.com/account/login/submit/").Post(form, "application/x-www-form-urlencoded");
 }
 public void Login(BotCredentials credentials)
 {
     Client = new Client();
     try
     {
         LoginToStackExchange(credentials);
         LoginToStackOverflow();
         LoginToChat();
         IsLoggedIn = true;
     }
     catch
     {
         IsLoggedIn = false;
         throw;
     }
 }
        public NadekoBot(int shardId, int parentProcessId)
        {
            if (shardId < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(shardId));
            }

            LogSetup.SetupLogger();
            _log = LogManager.GetCurrentClassLogger();
            TerribleElevatedPermissionCheck();

            Cache       = new RedisCache();
            Credentials = new BotCredentials();
            _db         = new DbService(Credentials);
            Client      = new DiscordSocketClient(new DiscordSocketConfig
            {
                MessageCacheSize    = 10,
                LogLevel            = LogSeverity.Warning,
                ConnectionTimeout   = int.MaxValue,
                TotalShards         = Credentials.TotalShards,
                ShardId             = shardId,
                AlwaysDownloadUsers = false,
            });
            CommandService = new CommandService(new CommandServiceConfig()
            {
                CaseSensitiveCommands = false,
                DefaultRunMode        = RunMode.Sync,
            });

            using (var uow = _db.UnitOfWork)
            {
                _botConfig = uow.BotConfig.GetOrCreate();
                OkColor    = new Color(Convert.ToUInt32(_botConfig.OkColor, 16));
                ErrorColor = new Color(Convert.ToUInt32(_botConfig.ErrorColor, 16));
            }

            SetupShard(parentProcessId);

#if GLOBAL_NADEKO
            Client.Log += Client_Log;
#endif
        }
Example #4
0
        public MitternachtBot(int shardId, int parentProcessId, int?port = null)
        {
            if (shardId < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(shardId));
            }

            LogSetup.SetupLogger();
            _log = LogManager.GetCurrentClassLogger();
            TerribleElevatedPermissionCheck();

            Credentials = new BotCredentials();
            _db         = new DbService(Credentials);
            _fs         = new ForumService(Credentials);
            Client      = new DiscordSocketClient(new DiscordSocketConfig
            {
                MessageCacheSize    = 10,
                LogLevel            = LogSeverity.Warning,
                ConnectionTimeout   = int.MaxValue,
                TotalShards         = Credentials.TotalShards,
                ShardId             = shardId,
                AlwaysDownloadUsers = false
            });
            CommandService = new CommandService(new CommandServiceConfig {
                CaseSensitiveCommands = false,
                DefaultRunMode        = RunMode.Sync
            });

            port       = port ?? Credentials.ShardRunPort;
            _comClient = new ShardComClient(port.Value);

            using (var uow = _db.UnitOfWork)
            {
                _botConfig = uow.BotConfig.GetOrCreate();
                OkColor    = new Color(Convert.ToUInt32(_botConfig.OkColor, 16));
                ErrorColor = new Color(Convert.ToUInt32(_botConfig.ErrorColor, 16));
            }

            SetupShard(parentProcessId, port.Value);

            Client.Log += Client_Log;
        }
        private void LoadCredentials()
        {
            const string path = "Credentials.json";

            if (!File.Exists(path))
            {
                _logger.LogError("Can't load credentials, no Credentials.json found.");
                return;
            }

            try
            {
                string json = File.ReadAllText(path);
                _credentials = JsonConvert.DeserializeObject <BotCredentials>(json);
            }
            catch (Exception e)
            {
                _logger.LogException("BotCredentialsProvider", e);
            }
        }
Example #6
0
        public InjhinuityInstance()
        {
            //Logging configuration for the local bot instance
            var logConfig     = new LoggingConfiguration();
            var consoleTarget = new ColoredConsoleTarget()
            {
                Layout = @"${date:format=HH\:mm\:ss} ${logger} | ${message}"
            };

            logConfig.AddTarget("Console", consoleTarget);
            logConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget));

            LogManager.Configuration = logConfig;
            _log = LogManager.GetCurrentClassLogger();

            //Creates the bot's loggin credentials for Discord
            BotCredentials = new BotCredentials();

            var fileReader = new JsonFileReader();
            var json       = fileReader.ReadFile(_botConfigPath);

            BotConfig = JsonConvert.DeserializeObject <BotConfig>(json);

            //Creates the client and hooks it up to our events for startup and logging
            Client = new DiscordSocketClient(new DiscordSocketConfig
            {
                MessageCacheSize    = 1000,
                LogLevel            = LogSeverity.Warning,
                ConnectionTimeout   = int.MaxValue,
                AlwaysDownloadUsers = false,
            });

            Client.Ready += OnClientReady;
            Client.Log   += ClientLog;

            //The command service handles the input the bot receives from text channels
            CommandService = new CommandService(new CommandServiceConfig()
            {
                CaseSensitiveCommands = false
            });
        }
        public static async Task InitializeHandler(DiscordSocketClient client, BotCredentials credentials, List <Type> commandClasses, Dictionary <ulong, char> collection, bool hasCleverbotApiKey)
        {
            CommandHandlerService.client             = client;
            CommandHandlerService.credentials        = credentials;
            CommandHandlerService.commandClasses     = commandClasses;
            CommandHandlerService.IdPrefixCollection = collection;
            HasCleverbotApiKey = hasCleverbotApiKey;
            commands           = new CommandService();
            services           = new ServiceCollection()
                                 .AddSingleton(client)
                                 .AddSingleton <InteractiveService>()
                                 .BuildServiceProvider();
            client.MessageReceived += CommandHandler;
            AppDomain appDomain = AppDomain.CurrentDomain;

            Assembly[] assemblies = appDomain.GetAssemblies();
            foreach (Assembly assembly in assemblies)
            {
                await commands.AddModulesAsync(assembly, services);
            }
        }
Example #8
0
        public virtual async Task <IBot> ConnectBotAsync(BotCredentials credentials, int reconnectIntervalSec)
        {
            var bot = await _twitchNETService.GetBotAsync(credentials.BotId);

            if (bot == null)
            {
                return(null);
            }

            var instance = await _twitchNETBotManager.AddBotAsync(credentials, bot, reconnectIntervalSec * 1000);

            instance.ConnectionBotEvent        += OnConnectionBotEvent;
            instance.ConnectionServerBotEvent  += OnConnectionServerBotEvent;
            instance.ConnectionServerUserEvent += OnConnectionServerUserEvent;
            instance.MessageServerChatEvent    += OnMessageServerChatEvent;
            instance.MessageServerCommandEvent += OnMessageServerCommandEvent;
            instance.MessageWhisperEvent       += OnMessageWhisperEvent;
            instance.FollowEvent += OnFollowEvent;
            instance.ErrorEvent  += OnErrorEvent;

            return(instance);
        }
Example #9
0
        static void Main(string[] args)
        {
            var SteamWebClient = new SteamWebClient();

            var bots = new BotCredentials[]
            {
                new BotCredentials() { Username = "******", Password = "******" }
            };

            var schemaCache = new ItemsSchema(SteamWebClient, STEAM_WEB_KEY);
            var schemas = schemaCache.LookupSchemas();
            schemaCache.Load(schemas);

            foreach(var botInfo in bots)
            {
                var bot = new Bot(Logger, schemaCache, botInfo);
                bot.Admins.Add(new SteamID(00000000000000000));

                bot.OnWebLoggedOn += (b) =>
                {
                    b.SteamFriends.SetPersonaName("SteamBot");
                    b.SteamFriends.SetPersonaState(EPersonaState.Online);
                };

                bot.Initialize(useUDP: true);
                bot.Connect();

                while (bot.IsRunning)
                {
                    bot.Update();
                    bot.UpdateIdlerBots();
                    Thread.Sleep(1);
                }

                Logger.WriteLine("Bot is shutting down");

                bot.Shutdown();
            }
        }
Example #10
0
 public RaceCommand(BotCredentials botCredentials, GamesService gamesService, RandomService randomService) :
     base(botCredentials, gamesService, randomService)
 {
 }
Example #11
0
        public ShardsCoordinator()
        {
            //load main stuff
            LogSetup.SetupLogger(-1);
            _log   = LogManager.GetCurrentClassLogger();
            _creds = new BotCredentials();

            _log.Info("Starting NadekoBot v" + StatsService.BotVersion);

            _key   = _creds.RedisKey();
            _redis = ConnectionMultiplexer.Connect("127.0.0.1");

            new RedisImagesCache(_redis, _creds).Reload(); //reload images into redis

            //setup initial shard statuses
            _defaultShardState = new ShardComMessage()
            {
                ConnectionState = Discord.ConnectionState.Disconnected,
                Guilds          = 0,
                Time            = DateTime.UtcNow
            };
            var db = _redis.GetDatabase();

            //clear previous statuses
            db.KeyDelete(_key + "_shardstats");

            _shardProcesses = new Process[_creds.TotalShards];
            for (int i = 0; i < _creds.TotalShards; i++)
            {
                //add it to the list of shards which should be started
#if DEBUG
                if (i > 0)
                {
                    _shardStartQueue.Enqueue(i);
                }
                else
                {
                    _shardProcesses[i] = Process.GetCurrentProcess();
                }
#else
                _shardStartQueue.Enqueue(i);
#endif
                //set the shard's initial state in redis cache
                var msg = _defaultShardState.Clone();
                msg.ShardId = i;
                //this is to avoid the shard coordinator thinking that
                //the shard is unresponsive while starting up
                var delay = 45;
#if GLOBAL_NADEKO
                delay = 180;
#endif
                msg.Time = DateTime.UtcNow + TimeSpan.FromSeconds(delay * (i + 1));
                db.ListRightPush(_key + "_shardstats",
                                 JsonConvert.SerializeObject(msg),
                                 flags: CommandFlags.FireAndForget);
            }

            _curProcessId = Process.GetCurrentProcess().Id;

            //subscribe to shardcoord events
            var sub = _redis.GetSubscriber();

            //send is called when shard status is updated. Every 7.5 seconds atm
            sub.Subscribe(_key + "_shardcoord_send",
                          OnDataReceived,
                          CommandFlags.FireAndForget);

            //called to stop the shard, although the shard will start again when it finds out it's dead
            sub.Subscribe(_key + "_shardcoord_stop",
                          OnStop,
                          CommandFlags.FireAndForget);

            //called kill the bot
            sub.Subscribe(_key + "_die",
                          (ch, x) => Environment.Exit(0),
                          CommandFlags.FireAndForget);
        }
Example #12
0
 protected GameModule(BotCredentials botCredentials, GamesService gamesService, RandomService randomService)
 {
     _botCredentials = botCredentials;
     _gamesService   = gamesService;
     _randomService  = randomService;
 }
Example #13
0
        public ShardsCoordinator()
        {
            //load main stuff
            LogSetup.SetupLogger(-1);
            _log   = LogManager.GetCurrentClassLogger();
            _creds = new BotCredentials();

            _log.Info("Starting NadekoBot v" + StatsService.BotVersion);

            _key = _creds.RedisKey();
            _log.Info("Redis options: " + _creds.RedisOptions);
            var conf = ConfigurationOptions.Parse(_creds.RedisOptions);

            _redis = ConnectionMultiplexer.Connect(conf);

            var imgCache = new RedisImagesCache(_redis, _creds);   //reload images into redis

            if (!imgCache.AllKeysExist().GetAwaiter().GetResult()) // but only if the keys don't exist. If images exist, you have to reload them manually
            {
                imgCache.Reload().GetAwaiter().GetResult();
            }
            else
            {
                _log.Info("Images are already present in redis. Use .imagesreload to force update if needed.");
            }

            //setup initial shard statuses
            _defaultShardState = new ShardComMessage()
            {
                ConnectionState = Discord.ConnectionState.Disconnected,
                Guilds          = 0,
                Time            = DateTime.UtcNow
            };
            var db = _redis.GetDatabase();

            //clear previous statuses
            db.KeyDelete(_key + "_shardstats");

            _shardProcesses = new Process[_creds.TotalShards];
            var shardIds = Enumerable.Range(1, _creds.TotalShards - 1)
                           .Shuffle()
                           .Prepend(0)
                           .ToArray();

            for (var i = 0; i < shardIds.Length; i++)
            {
                var id = shardIds[i];
                //add it to the list of shards which should be started
#if DEBUG
                if (id > 0)
                {
                    _shardStartQueue.Enqueue(id);
                }
                else
                {
                    _shardProcesses[id] = Process.GetCurrentProcess();
                }
#else
                _shardStartQueue.Enqueue(id);
#endif
                //set the shard's initial state in redis cache
                var msg = _defaultShardState.Clone();
                msg.ShardId = id;
                //this is to avoid the shard coordinator thinking that
                //the shard is unresponsive while starting up
                var delay = 45;
#if GLOBAL_NADEKO
                delay = 180;
#endif
                msg.Time = DateTime.UtcNow + TimeSpan.FromSeconds(delay * (id + 1));
                db.ListRightPush(_key + "_shardstats",
                                 JsonConvert.SerializeObject(msg),
                                 flags: CommandFlags.FireAndForget);
            }

            _curProcessId = Process.GetCurrentProcess().Id;

            //subscribe to shardcoord events
            var sub = _redis.GetSubscriber();

            //send is called when shard status is updated. Every 7.5 seconds atm
            sub.Subscribe(_key + "_shardcoord_send",
                          OnDataReceived,
                          CommandFlags.FireAndForget);

            //called to stop the shard, although the shard will start again when it finds out it's dead
            sub.Subscribe(_key + "_shardcoord_stop",
                          OnStop,
                          CommandFlags.FireAndForget);

            //called kill the bot
            sub.Subscribe(_key + "_die",
                          (ch, x) => Environment.Exit(0),
                          CommandFlags.FireAndForget);
        }
Example #14
0
 /// <summary>
 /// The <c>Initialize</c> method initialize this service with specific bot credentials.
 /// </summary>
 /// <param name="credentials">
 /// Botcredentials with set values
 /// </param>
 /// <returns></returns>
 public static void Initialize(BotCredentials credentials)
 {
     ApiRequestService.credentials = credentials;
 }
Example #15
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="memoryCache">memory cache service</param>
 /// <param name="botCredentials">bot credentials</param>
 public MessagesController(IMemoryCache memoryCache, IOptions <BotCredentials> botCredentials)
 {
     this._memoryCache    = memoryCache;
     this._botCredentials = botCredentials.Value;
 }
Example #16
0
        public async Task RunAsync(params string[] args)
        {
            SetupLogger();
            _log = LogManager.GetCurrentClassLogger();

            _log.Info("Starting NadekoBot v" + StatsService.BotVersion);


            Credentials = new BotCredentials();

            //create client
            Client = new ShardedDiscordClient(new DiscordSocketConfig
            {
                AudioMode         = Discord.Audio.AudioMode.Outgoing,
                MessageCacheSize  = 10,
                LogLevel          = LogSeverity.Warning,
                TotalShards       = Credentials.TotalShards,
                ConnectionTimeout = int.MaxValue
            });

            //initialize Services
            CommandService = new CommandService();
            Localizer      = new Localization();
            Google         = new GoogleApiService();
            CommandHandler = new CommandHandler(Client, CommandService);
            Stats          = new StatsService(Client, CommandHandler);

            //setup DI
            var depMap = new DependencyMap();

            depMap.Add <ILocalization>(Localizer);
            depMap.Add <ShardedDiscordClient>(Client);
            depMap.Add <CommandService>(CommandService);
            depMap.Add <IGoogleApiService>(Google);


            //setup typereaders
            CommandService.AddTypeReader <PermissionAction>(new PermissionActionTypeReader());
            CommandService.AddTypeReader <Command>(new CommandTypeReader());
            CommandService.AddTypeReader <Module>(new ModuleTypeReader());
            CommandService.AddTypeReader <IGuild>(new GuildTypeReader());

            //connect
            await Client.LoginAsync(TokenType.Bot, Credentials.Token).ConfigureAwait(false);

            await Client.ConnectAsync().ConfigureAwait(false);

            await Client.DownloadAllUsersAsync().ConfigureAwait(false);

            _log.Info("Connected");

            //load commands and prefixes
            using (var uow = DbHandler.UnitOfWork())
            {
                ModulePrefixes = new ConcurrentDictionary <string, string>(uow.BotConfig.GetOrCreate().ModulePrefixes.ToDictionary(m => m.ModuleName, m => m.Prefix));
            }
            // start handling messages received in commandhandler
            await CommandHandler.StartHandling().ConfigureAwait(false);

            await CommandService.LoadAssembly(this.GetType().GetTypeInfo().Assembly, depMap).ConfigureAwait(false);

#if !GLOBAL_NADEKO
            await CommandService.Load(new Music(Localizer, CommandService, Client, Google)).ConfigureAwait(false);
#endif
            Ready = true;
            Console.WriteLine(await Stats.Print().ConfigureAwait(false));
        }
Example #17
0
 public Moderation(BotCredentials botCredentials)
 {
     _botCredentials = botCredentials;
 }
Example #18
0
 public Fun(BotCredentials botCredentials, RandomService randomService)
 {
     _botCredentials = botCredentials;
     _randomService  = randomService;
 }
Example #19
0
 public BotConnector(BotCredentials botCredentials, IMemoryCache memoryCache, ILogger <BotConnector> logger)
 {
     _botCredentials = botCredentials;
     _memoryCache    = memoryCache;
     _logger         = logger;
 }
Example #20
0
 public YouTube(BotCredentials botCredentials)
 {
     _botCredentials = botCredentials;
 }