public MultiTextMarkovChainHelper(DiscordSocketClient client, DiscordContextFactory dbFactory, int depth) { _semaphore = new SemaphoreSlim(0, 1); _dbFactory = dbFactory; _db = _dbFactory.Create(new DbContextFactoryOptions()); _client = client; Depth = depth; if (depth > 0) { _markovChain = new StringMarkov(depth); } _timer = new Timer(async e => await SaveAsync().ConfigureAwait(false), null, 600000, 600000); }
public KiteChat(DiscordSocketClient client, DiscordContextFactory db, bool markovbool, string gBapi, string ytApi, int streamRefresh, bool silentStartup, int videoRefresh, int depth) { StartMarkovChain = markovbool; _greetings = File.ReadAllLines(GreetingFileLocation); RandomSeed = new Random(); YoutubeModuleService.Init(ytApi, client); if (streamRefresh > 3000) { StreamChecker = new LivestreamChecker(client, gBapi, streamRefresh, silentStartup); } if (videoRefresh > 3000) { GbVideoChecker = new GiantBombVideoChecker(client, gBapi, videoRefresh); } if (StartMarkovChain && depth > 0) { MultiDeepMarkovChains = new MultiTextMarkovChainHelper(client, db, depth); } }
internal static async Task SyncGuild(this DiscordContextFactory dbFactory, SocketGuild socketGuild) { using (var dbContext = dbFactory.Create(new DbContextFactoryOptions())) { Guild guild = await dbContext.Guilds .Include(g => g.Channels) .Include(g => g.Users) .SingleOrDefaultAsync(x => x.Id == socketGuild.Id).ConfigureAwait(false); //If guild does not exist, we create a new one and populate it with Users and Channels if (guild == null) { guild = new Guild { Id = socketGuild.Id, Channels = new List <Channel>(), Name = socketGuild.Name, Users = new List <User>() }; foreach (var textChannel in socketGuild.TextChannels) { Channel channel = new Channel { Id = textChannel.Id, Guild = guild, Name = textChannel.Name, Messages = new List <Message>() }; guild.Channels.Add(channel); } foreach (var socketUser in socketGuild.Users) //For now, Users are unique for each guild, this will cause me problems later I'm sure { User user = new User { Id = socketUser.Id, Guild = guild, LastActivityAt = DateTimeOffset.UtcNow, JoinedAt = socketUser.JoinedAt, Messages = new List <Message>(), Name = socketUser.Username }; guild.Users.Add(user); } dbContext.Add(guild); } else { //This should also probably track when channels no longer exist, but its probably not a big deal right now var channelsNotTracked = socketGuild.TextChannels.Where(x => guild.Channels.All(y => y.Id != x.Id)); var socketTextChannels = channelsNotTracked as IList <SocketTextChannel> ?? channelsNotTracked.ToList(); if (socketTextChannels.Any()) { foreach (var channelToTrack in socketTextChannels) { Channel channel = new Channel { Guild = guild, Id = channelToTrack.Id, Messages = new List <Message>(), Name = channelToTrack.Name }; guild.Channels.Add(channel); } dbContext.Update(guild); } var usersNotTracked = socketGuild.Users.Where(x => guild.Users.All(y => y.Id != x.Id)); var socketGuildUsers = usersNotTracked as IList <SocketGuildUser> ?? usersNotTracked.ToList(); if (socketGuildUsers.Any()) { foreach (var userToTrack in socketGuildUsers) { User user = new User { Id = userToTrack.Id, Guild = guild, LastActivityAt = DateTimeOffset.UtcNow, JoinedAt = userToTrack.JoinedAt, Messages = new List <Message>(), Name = userToTrack.Username }; guild.Users.Add(user); } dbContext.Update(guild); } } await dbContext.SaveChangesAsync().ConfigureAwait(false); //I could move this inside the branches, but its relatively cheap to call this if nothing has changed, and avoids multiple calls to it } }
public static async Task Main(string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.Async(a => a.RollingFile("rollinglog.log", fileSizeLimitBytes: 50000000).MinimumLevel.Information()) .WriteTo.LiterateConsole() .MinimumLevel.Debug() .CreateLogger(); if (args.Length != 0 && (args[0].Contains("--silent") || args[0].Contains("-s"))) { _silentStartup = true; } else { Log.Information("Are you sure you shouldn't be using the --silent argument?"); } Client = new DiscordSocketClient(new DiscordSocketConfig { LogLevel = LogSeverity.Debug, MessageCacheSize = 0, AlwaysDownloadUsers = true, HandlerTimeout = 2000 }); _settings = File.Exists(SettingsPath) ? JsonConvert.DeserializeObject <BotSettings>(File.ReadAllText(SettingsPath)) : new BotSettings { CommandPrefix = '!', DiscordEmail = "email", DiscordPassword = "******", DiscordToken = "Token", GiantBombApiKey = "GbAPIKey", YoutubeApiKey = "", DatabaseConnectionString = "", OwnerId = 0, MarkovChainStart = false, MarkovChainDepth = 2, GiantBombLiveStreamRefreshRate = 60000, GiantBombVideoRefreshRate = 60000 }; _rankConfigs = File.Exists(RankConfigPath) ? JsonConvert.DeserializeObject <RankConfigs>(File.ReadAllText(RankConfigPath)) : new RankConfigs { GuildConfigs = new Dictionary <ulong, GuildRanks>() }; _dbFactory = new DiscordContextFactory(); _kiteChat = new KiteChat(Client, _dbFactory, _settings.MarkovChainStart, _settings.GiantBombApiKey, _settings.YoutubeApiKey, _settings.GiantBombLiveStreamRefreshRate, _silentStartup, _settings.GiantBombVideoRefreshRate, _settings.MarkovChainDepth); _commandService = new CommandService(new CommandServiceConfig { CaseSensitiveCommands = false, DefaultRunMode = RunMode.Sync, LogLevel = LogSeverity.Verbose, SeparatorChar = ' ', ThrowOnError = true //Throws exceptions up to the commandhandler in sync commands }); Client.Log += LogDiscordMessage; _commandService.Log += LogDiscordMessage; Client.MessageReceived += (msg) => { Log.Verbose("MESSAGE {Channel}{tab}{User}: {Content}", msg.Channel.Name, "\t", msg.Author.Username, msg.ToString()); return(Task.CompletedTask); }; Client.GuildMembersDownloaded += async(guild) => { var sw = new Stopwatch(); sw.Start(); await _dbFactory.SyncGuild(guild).ConfigureAwait(false); sw.Stop(); }; Client.JoinedGuild += (server) => { Log.Information("Connected to {Name}", server.Name); return(Task.CompletedTask); }; Client.UserUnbanned += (user, guild) => { Console.WriteLine($"{user.Username}#{user.Discriminator}"); Console.WriteLine(user); return(Task.CompletedTask); }; int connections = 0; Client.Connected += () => { Console.WriteLine($"Connected for the {connections++} time."); return(Task.CompletedTask); }; int disconnections = 0; Client.Disconnected += (exception) => { Console.WriteLine($"Disconnected for the {disconnections++} time."); return(Task.CompletedTask); }; Console.WriteLine("LoginAsync"); await Client.LoginAsync(TokenType.Bot, _settings.DiscordToken).ConfigureAwait(false); Console.WriteLine("ConnectAsync"); await Client.StartAsync().ConfigureAwait(false); Client.Ready += OnReady; Client.UserUpdated += async(before, after) => await CheckUsername(before, after).ConfigureAwait(false); Client.GuildMemberUpdated += async(before, after) => await CheckNickname(before, after).ConfigureAwait(false); await Task.Delay(-1).ConfigureAwait(false); }