public async Task MainAsync() { using (var services = ConfigureServices()) { _client = services.GetRequiredService <DiscordSocketClient>(); _client.Log += LogAsync; // Login await _client.LoginAsync(TokenType.Bot, Environment.GetEnvironmentVariable("rtBotToken")); await _client.SetGameAsync("/rt", type : ActivityType.Watching); await _client.StartAsync(); // Crate Discord Bot List client (Top.gg) var discordBotList = new AuthDiscordBotListApi(477287091798278145, Environment.GetEnvironmentVariable("rtBotListToken")); _dblApi = await discordBotList.GetMeAsync(); // Initialize HttpClient WebUtils.http = new HttpClient(); // These events will update the current amount of guilds the bot is in on Top.gg (_dblApi) _client.Ready += OnReady; _client.JoinedGuild += OnGuildJoined; _client.LeftGuild += OnGuildLeft; // Register commands await services.GetRequiredService <CommandHandlingService>().InitializeAsync(); // Run forever await Task.Delay(Timeout.Infinite); } }
public StatisticManager(DiscordShardedClient client) { client.GuildDownloadCompleted += Client_GuildDownloadCompleted; client.GuildCreated += Client_GuildCreated; client.GuildDeleted += Client_GuildDeleted; if (!string.IsNullOrEmpty(Program.Config.Apis.TopGg)) { client.Ready += e => { DiscordBotListApi = new AuthDiscordBotListApi(client.CurrentUser.Id, Program.Config.Apis.TopGg); return(Task.CompletedTask); }; } var aTimer = new Timer(TimeSpan.FromMinutes(1).TotalMilliseconds); // elapse every 1 min var lastHour = DateTime.Now.Hour; aTimer.Elapsed += async(source, e) => { if (lastHour < DateTime.Now.Hour || (lastHour == 23 && DateTime.Now.Hour == 0)) { lastHour = DateTime.Now.Hour; // every hour await Update(); } }; aTimer.Start(); }
private async Task ClientReady() { if (_firstConnect) { if (!IsDebugMode) { InviteLink = $"https://discord.com/oauth2/authorize?client_id={_client.CurrentUser.Id}&scope=bot&permissions={(ulong)Constants.InvitePermissions}"; if (string.IsNullOrEmpty(Config.DblApiToken)) { await _logService.LogAsync(new LogMessage(LogSeverity.Info, "Stats", "Top.gg API token is empty or not set. Bot server count will not be sent to the API.")); } else { _dblApi = new AuthDiscordBotListApi(_client.CurrentUser.Id, Config.DblApiToken); DblBotPage = $"https://top.gg/bot/{_client.CurrentUser.Id}"; } if (string.IsNullOrEmpty(Config.DiscordBotsApiToken)) { await _logService.LogAsync(new LogMessage(LogSeverity.Info, "Stats", "DiscordBots API token is empty or not set. Bot server count will not be sent to the API.")); } else { _discordBots = new DiscordBotsApi(Config.DiscordBotsApiToken); } await UpdateBotListStatsAsync(); } Uptime = DateTimeOffset.UtcNow; _firstConnect = false; } await _logService.LogAsync(new LogMessage(LogSeverity.Info, "Bot", $"{_client.CurrentUser.Username} is online!")); }
private async Task UpdateBotListStatsAsync() { try { if (_dblApi != null && _dblBot == null) { try { _dblBot = await _dblApi.GetMeAsync(); } catch (NullReferenceException) { _dblApi = null; await _logService.LogAsync(new LogMessage(LogSeverity.Warning, "Stats", "Could not get the bot info from DBL API, make sure the bot is listed in DBL and the token is valid")); await _logService.LogAsync(new LogMessage(LogSeverity.Info, "Stats", "Bot server count will not be sent to DBL API.")); } } if (_dblBot != null) { await _dblBot.UpdateStatsAsync(_client.Guilds.Count); } if (_discordBots != null) { await _discordBots.UpdateStatsAsync(_client.CurrentUser.Id, _client.Guilds.Count); } } catch (Exception e) when(e is HttpRequestException || e is TaskCanceledException) { await _logService.LogAsync(new LogMessage(LogSeverity.Warning, "Stats", "Could not update the DBL/DiscordBots bot stats", e)); } }
public async Task Update_DiscordBotList() { try { var config = this.BOT.Config; if (string.IsNullOrEmpty(config.DBL_Token)) { return; } AuthDiscordBotListApi DblApi = new AuthDiscordBotListApi(config.BotId, config.DBL_Token); var me = await DblApi.GetMeAsync(); var c = this.Client as IDiscordClient; var guilds = await c.GetGuildsAsync(); var count = guilds.Count; // Update stats guildCount await me.UpdateStatsAsync(guilds.Count); } catch (Exception ex) { await Log.Error(null, ex, nameof(Update_DiscordBotList)); } }
public override async Task Initialize() { await base.Initialize(); try { var token = await _configuration.GetDblToken(); var clientId = await _configuration.GetClientId(); DblApi = new AuthDiscordBotListApi(clientId, token); } catch (InvalidTokenException e) { Console.WriteLine(e.Message); return; } catch (InvalidIdException e) { Console.WriteLine(e.Message); return; } Client.JoinedGuild += OnGuildJoined; Client.LeftGuild += OnGuildLeft; }
public async static Task MainAsync(string Token) { MGXStatistics.StartedAt = DateTime.UtcNow; var config = new DiscordSocketConfig { MessageCacheSize = 5, TotalShards = 1 }; Client = new DiscordShardedClient(config); DiscordBotListClient = new AuthDiscordBotListApi(534193192329805854, "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjUzNDE5MzE5MjMyOTgwNTg1NCIsImJvdCI6dHJ1ZSwiaWF0IjoxNTg3NDI3NzQxfQ.lU-e43AqYswMC3UZsc145RgadqEhrrrelKoSCvT8UXg"); //(await DiscordBotListClient.GetMeAsync()). CustomResponses.UpdateResponses(); await Client.LoginAsync(TokenType.Bot, Token); await Client.StartAsync(); Client.MessageReceived += Client_MessageReceived; Client.MessageReceived += globalchat.MessageReceived; Client.MessageReceived += snipe.OnReceived; Client.MessageReceived += Secondary.MyClient_MessageReceived; Client.ShardReady += Client_Ready; Client.JoinedGuild += Client_JoinedGuild; Client.LeftGuild += Client_LeftGuild; Client.MessageDeleted += snipe.OnDelete; new Thread(async x => { await Secondary.Secondary_Thread(); }).Start(); await Task.Delay(-1); }
public static async Task Initialize() { var timer = new Timer(900000); timer.Enabled = true; timer.AutoReset = true; timer.Elapsed += async(s, e) => { DiscordShardedClient client = ConfigProperties.Client; AuthDiscordBotListApi api = ConfigProperties.TopGgApi; int guildCount = client.Guilds.Count; int shardCount = client.Shards.Count; try { await api.UpdateStats(guildCount, shardCount); } catch (Exception exception) { await ConsoleLogger.LogAsync(exception, "An exception occurred when trying to update the " + "Top.GG guild and shard stats."); } await ConsoleLogger.LogAsync($"Guild and shard counts have been " + $"posted to Top.GG. [Guilds: {guildCount:N0} | " + $"Shards: {shardCount:N0}]", LogLvl.INFO); }; }
public async Task Initialize(DiscordSocketClient client, ConfigData config) { _client = client; DblApi = new AuthDiscordBotListApi(config.ClientId, config.DiscordBotsToken); client.Ready += OnClientReady; client.JoinedGuild += OnGuildJoined; client.LeftGuild += OnGuildLeft; }
public static async Task UpdateStats(ulong selfId) { AuthDiscordBotListApi DblApi = new AuthDiscordBotListApi(selfId, apiKey); var me = await DblApi.GetMeAsync(); // Update stats guildCount await me.UpdateStatsAsync(Program._client.Guilds.Count); }
public Stats(ILoggerFactory loggerFactory, DiscordShardedClient client, Web web) { _logger = loggerFactory.CreateLogger(nameof(Stats)); _web = web; IsReady = false; _id = client.CurrentUser.Id; _topGG = new AuthDiscordBotListApi(_id, Config.Instance.Tokens.BotList.TopGG); _calculateStats = new Timer(CalculateStats !, client, TimeSpan.FromSeconds(60), TimeSpan.FromHours(1)); }
/*private Task _client_GuildAvailable(SocketGuild arg) * { * _ = arg.DownloadUsersAsync(); * return Task.CompletedTask; * }*/ private async Task Client_Ready() { //await Start(); _vMem.Start(); Ext._vMem.instance._run(); Modules.Currency.SetEmoji(); DblApiBot = new AuthDiscordBotListApi(_client.CurrentUser.Id, JSON.Getdbo()); Ready = true; await Task.CompletedTask; }
private async Task Connected() { if (_topGGToken == null) { return; } _topGGAPI = new AuthDiscordBotListApi(Client.CurrentUser.Id, _topGGToken); await UpdateDiscordBots(null); }
private static async Task UpdateTopGGStats() { if (bot.CurrentUser.Id == 729696788097007717) // make sure we are only setting this on the main bot, not test bot! { AuthDiscordBotListApi DblApi = GetTopGGClient(); IDblSelfBot me = await DblApi.GetMeAsync(); await me.UpdateStatsAsync(bot.Guilds.Count); } }
/// <summary> /// Main program method /// </summary> /// <returns></returns> private static async Task MainAsync() { Discord = new DiscordClient(new DiscordConfiguration { Token = SettingsManager.Config.Token, TokenType = TokenType.Bot, UseInternalLogHandler = true, LogLevel = LogLevel.Info }); DblApi = new AuthDiscordBotListApi(683421360352919599, SettingsManager.Config.TopGgToken); Discord.MessageCreated += async e => { if (e.Message.Content.ToLower().StartsWith(SettingsManager.Config.CommandPrefix)) { await Discord.UpdateStatusAsync(null, DSharpPlus.Entities.UserStatus.Online); } }; Discord.Heartbeated += async e => { var me = await DblApi.GetMeAsync(); await me.UpdateStatsAsync(Discord.Guilds.Count); }; _commands = Discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = SettingsManager.Config.CommandPrefix }); Discord.UseInteractivity(new InteractivityConfiguration { // default pagination behaviour to just ignore the reactions PaginationBehaviour = TimeoutBehaviour.Ignore, // default pagination timeout to 5 minutes PaginationTimeout = TimeSpan.FromMinutes(5), // default timeout for other actions to 1 minute Timeout = TimeSpan.FromMinutes(1) }); _commands.RegisterCommands <MainCommands>(); _commands.RegisterCommands <LimitingCommands>(); _commands.RegisterCommands <OwnerCommands>(); _commands.RegisterCommands <AdminCommands>(); _commands.RegisterCommands <YotubeCommands>(); await Discord.ConnectAsync(); //Creating all the observers that will check for updated on specific service YouTubeObserver = new YouTubeObserver(); YouTubeObserver.Start(); await Task.Delay(-1); }
// Update the bot shard and guild count for DiscordBotList public async Task DBLGet() { AuthDiscordBotListApi DblApi = new AuthDiscordBotListApi(Config.bot.selfID, Config.bot.dblToken); IDblSelfBot me = await DblApi.GetMeAsync(); // Update stats sharded indexShard shardCount shards //await me.UpdateStatsAsync(24, 50, new[] { 12, 421, 62, 241, 524, 534 }); // Update stats guildCount await me.UpdateStatsAsync(_client.Guilds.Count); }
public DBLPinger() { string dblToken = _lib.GetDBLToken(); if (string.IsNullOrEmpty(dblToken)) { return; } dblApi = new AuthDiscordBotListApi(_lib.GetBotId(), dblToken); }
public static void SetUpDbl(ulong id) { try { string token = AppSettings.DiscordBotListToken; DblApi = new AuthDiscordBotListApi(id, token); } catch { Logger.Log("No DBL token", LogSeverity.Warning); } }
public EnergizeClient(string token, string prefix, char separator) { Console.Clear(); Console.Title = "Energize's Logs"; this.Token = token; this.Prefix = prefix; this.Separator = separator; this.Logger = new Logger(); this.MessageSender = new MessageSender(this.Logger); this.DiscordClient = new DiscordShardedClient(new DiscordSocketConfig { MessageCacheSize = 100, ExclusiveBulkDelete = false, LogLevel = LogSeverity.Verbose, }); this.DiscordRestClient = new DiscordRestClient(); this.ServiceManager = new ServiceManager(this); this.UpdateTimer = new Timer(this.OnUpdateTimer); if (this.HasToken) { AppDomain.CurrentDomain.UnhandledException += (sender, args) => { Exception e = (Exception)args.ExceptionObject; this.Logger.LogTo("crash.log", e.ToString()); }; this.DiscordClient.Log += async log => this.Logger.LogTo("dnet_socket.log", log.Message); this.DiscordClient.ShardReady += this.OnShardReady; this.DiscordRestClient.Log += async log => this.Logger.LogTo("dnet_rest.log", log.Message); this.DiscordBotList = new AuthDiscordBotListApi(Config.Instance.Discord.BotID, Config.Instance.Discord.BotListToken); this.DisplayAsciiArt(); this.Logger.Nice("Config", ConsoleColor.Yellow, $"Environment => [ {this.Environment} ]"); this.Logger.Notify("Initializing"); try { this.ServiceManager.InitializeServices(); } catch (Exception e) { this.Logger.Nice("Init", ConsoleColor.Red, $"Something went wrong: {e}"); } } else { this.Logger.Warning("No token was used! You NEED a token to connect to Discord!"); } }
public DBLService(LogService log, BotConfig config, DiscordShardedClient client) { Log = log; Config = config; Client = client; UnauthAPI = new DiscordBotListApi(); if (config.Dbl != null) { AuthAPI = new AuthDiscordBotListApi(client.CurrentUser.Id, Config.Dbl); } Log.LogString("Connected to DBL"); }
public async Task UpdateCount() { var token = Config.Load().DBLToken; if (token == null) { return; } var DblApi = new AuthDiscordBotListApi(Context.Client.CurrentUser.Id, Config.Load().DBLToken); var me = await DblApi.GetMeAsync(); await me.UpdateStatsAsync(Context.Socket.Client.Guilds.Count); }
public static async Task UpdateTopGgAsync() { if (DblToken != null) { if (DblApi == null) { DblApi = new AuthDiscordBotListApi(ClientId, DblToken); } if (DblLastSend.AddMinutes(10).CompareTo(DateTime.Now) < 0) // Make sure to not spam the API { DblLastSend = DateTime.Now; await DblApi.UpdateStats(Client.Guilds.Count); } } }
private async Task MainAsync() { if (!File.Exists("Keys/Credentials.json")) { throw new FileNotFoundException("Missing Keys/Credentials.json"); } dynamic json = JsonConvert.DeserializeObject(File.ReadAllText("Keys/Credentials.json")); if (json.botToken == null) { throw new NullReferenceException("Missing botToken in Credentials file"); } _commandManager = new((ulong?)json.debugGuildId); statsWebsite = json.statsWebsite; statsToken = json.statsToken; lastDiscordBotsSent = DateTime.MinValue; if (json.dblId != null & json.dblToken != null) { dblApi = new AuthDiscordBotListApi(ulong.Parse((string)json.dblId), (string)json.dblToken); } else { dblApi = null; } db = new Db(); await db.InitAsync(); client.MessageReceived += HandleCommandAsync; client.ReactionAdded += ReactionAdded; client.GuildAvailable += InitGuild; client.JoinedGuild += InitGuild; client.JoinedGuild += GuildCountChange; client.LeftGuild += GuildCountChange; client.Connected += UpdateDiscordBots; client.Ready += Ready; client.SlashCommandExecuted += SlashCommandExecuted; await client.LoginAsync(TokenType.Bot, (string)json.botToken); StartTime = DateTime.Now; await client.StartAsync(); await Task.Delay(-1); }
private async Task MainAsync() { #if DEV const string dt = "atoken"; #else const string dt = "token"; #endif Discord = new DiscordClient(new DiscordConfiguration { Token = ConfigurationManager.AppSettings[dt], TokenType = TokenType.Bot, MinimumLogLevel = LogLevel.Debug }); Commands = Discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefixes = new[] { "w+" } }); Commands.RegisterCommands <WordHooksCommands>(); Commands.RegisterCommands <ServerCommands>(); Commands.RegisterCommands <MiscCommands>(); Database = new Database("storage.st"); OptedOut = Database.GetTable <bool>("optedout"); Guilds = Database.GetTable <Guild>("guilds"); Discord.MessageCreated += HandleMessage; Discord.GuildAvailable += e => { Discord.Logger.Log(LogLevel.Debug, $"Guild '{e.Guild.Name}' is available", DateTime.Now); return(Task.CompletedTask); }; await Discord.ConnectAsync(new DiscordActivity($" for messages | prefix w+", ActivityType.Watching)); #if !DEV DblApi = new AuthDiscordBotListApi(Discord.CurrentUser.Id, ConfigurationManager.AppSettings["dbltoken"]); DblSelfBot = await DblApi.GetMeAsync(); #endif await Update(); await Task.Delay(-1); }
internal async Task Connect() { if (connected) { return; } try { DblApiAuth = new AuthDiscordBotListApi(botID, accountKey); await DblApiAuth.GetMeAsync(); connected = true; } catch (Exception _) { return; } }
public static Func <SocketGuild, Task> Joined(DataBase db, string token) { Func <SocketGuild, Task> convert = async delegate(SocketGuild guild) { IConfiguration configuration = LoadConfig.Instance.config; FindOrCreateGuild.Perform(guild, db); var view = Views.Info.JoinedGuild.Response(); await guild.TextChannels.First().SendMessageAsync(text: view.Item1, embed: view.Item2); AuthDiscordBotListApi DblApi = new AuthDiscordBotListApi(425833927517798420, token); var me = await DblApi.GetMeAsync(); await me.UpdateStatsAsync(db.Guilds.Count()); }; return(convert); }
public async Task OnReady() { var botID = ulong.TryParse(Config.bot.BotUserID, out ulong ID); var mutualGuilds = _client.GetUser(ID).MutualGuilds; AuthDiscordBotListApi dblAPI = new AuthDiscordBotListApi(ID, Config.bot.DblApiKey); Console.WriteLine("\nRetrieving bot from DBL API..."); IDblSelfBot me = await dblAPI.GetMeAsync(); Console.WriteLine("Pushing stats to DBL API..."); await me.UpdateStatsAsync(mutualGuilds.Count()); Console.WriteLine("Success."); var serverCountValue = new Dictionary <string, string> { { "server_count", $"{mutualGuilds.Count()}" } }; int i = 0; foreach (var guild in mutualGuilds) { for (int j = 0; j <= guild.MemberCount; j++) { i++; } } Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"\nAce Pilot Kaguya cleared for takeoff. Servicing {mutualGuilds.Count()} guilds" + $" and {i.ToString("N0")} members." + "\nBegin Logging\n"); Console.WriteLine("--------------------------------------------"); }
public TimerService(DiscordShardedClient client, Logger.Logger logger, ILastfmApi lastfmApi) { this._logger = logger; this._lastfmApi = lastfmApi; this._client = client; this._lastFMService = new LastFMService(this._lastfmApi); this._userService = new UserService(); this._guildService = new GuildService(); this._timer = new Timer(async _ => { var random = new Random(); var randomAvatarMode = random.Next(1, 4); var randomAvatarModeDesc = ""; switch (randomAvatarMode) { case 1: randomAvatarModeDesc = "Recent listens"; break; case 2: randomAvatarModeDesc = "Weekly albums"; break; case 3: randomAvatarModeDesc = "Monthly albums"; break; case 4: randomAvatarModeDesc = "Overall albums"; break; } Log.Information($"Featured: Picked mode {randomAvatarMode} - {randomAvatarModeDesc}"); try { var lastFMUserName = await this._userService.GetRandomLastFMUserAsync(); Log.Information($"Featured: Picked user {lastFMUserName}"); switch (randomAvatarMode) { // Recent listens case 1: var tracks = await this._lastFMService.GetRecentScrobblesAsync(lastFMUserName, 25); var trackList = tracks .Select(s => new CensoredAlbum(s.ArtistName, s.AlbumName)) .Where(w => !string.IsNullOrEmpty(w.AlbumName) && !GlobalVars.CensoredAlbums.Select(s => s.ArtistName).Contains(w.ArtistName) && !GlobalVars.CensoredAlbums.Select(s => s.AlbumName).Contains(w.AlbumName)); var currentTrack = trackList.First(); var albumImages = await this._lastFMService.GetAlbumImagesAsync(currentTrack.ArtistName, currentTrack.AlbumName); this._trackString = $"{currentTrack.AlbumName} \n" + $"by {currentTrack.ArtistName} \n \n" + $"{randomAvatarModeDesc} from {lastFMUserName}"; Log.Information("Featured: Changing avatar to: " + this._trackString); if (albumImages?.Large != null) { ChangeToNewAvatar(client, albumImages.Large.AbsoluteUri); } else { Log.Information("Featured: Album had no image, switching to alternative avatar mode"); goto case 3; } break; // Weekly albums case 2: case 3: case 4: var timespan = LastStatsTimeSpan.Week; switch (randomAvatarMode) { case 3: timespan = LastStatsTimeSpan.Month; break; case 4: timespan = LastStatsTimeSpan.Overall; break; } var albums = await this._lastFMService.GetTopAlbumsAsync(lastFMUserName, timespan, 10); if (!albums.Any()) { Log.Information($"Featured: User {lastFMUserName} had no albums, switching to different user."); lastFMUserName = await this._userService.GetRandomLastFMUserAsync(); albums = await this._lastFMService.GetTopAlbumsAsync(lastFMUserName, timespan, 10); } var albumList = albums .Select(s => new CensoredAlbum(s.ArtistName, s.Name)) .Where(w => !GlobalVars.CensoredAlbums.Select(s => s.ArtistName).Contains(w.ArtistName) && !GlobalVars.CensoredAlbums.Select(s => s.AlbumName).Contains(w.AlbumName)) .ToList(); var albumFound = false; var i = 0; while (!albumFound) { var currentAlbum = albumList[i]; var albumImage = await this._lastFMService.GetAlbumImagesAsync(currentAlbum.ArtistName, currentAlbum.AlbumName); this._trackString = $"{currentAlbum.AlbumName} \n" + $"by {currentAlbum.ArtistName} \n \n" + $"{randomAvatarModeDesc} from {lastFMUserName}"; if (albumImage?.Large != null) { Log.Information($"Featured: Album {i} success, changing avatar to: \n" + $"{this._trackString}"); ChangeToNewAvatar(client, albumImage.Large.AbsoluteUri); albumFound = true; } else { Log.Information($"Featured: Album {i} had no image, switching to alternative album"); i++; } } break; } } catch (Exception e) { Log.Error("ChangeFeaturedAvatar", e); } }, null, TimeSpan.FromSeconds(ConfigData.Data.Bot.BotWarmupTimeInSeconds + ConfigData.Data.Bot.FeaturedTimerStartupDelayInSeconds), // 4) Time that message should fire after the timer is created TimeSpan.FromMinutes(ConfigData.Data.Bot.FeaturedTimerRepeatInMinutes)); // 5) Time after which message should repeat (use `Timeout.Infinite` for no repeat) this._internalStatsTimer = new Timer(async _ => { Log.Information("Updating metrics"); Statistics.DiscordServerCount.Set(client.Guilds.Count); try { Statistics.RegisteredUsers.Set(await this._userService.GetTotalUserCountAsync()); Statistics.RegisteredGuilds.Set(await this._guildService.GetTotalGuildCountAsync()); } catch (Exception e) { Console.WriteLine(e); } if (string.IsNullOrEmpty(ConfigData.Data.Bot.Status)) { Log.Information("Updating status"); await client.SetGameAsync($"{ConfigData.Data.Bot.Prefix} | {client.Guilds.Count} servers | fmbot.xyz"); } }, null, TimeSpan.FromSeconds(ConfigData.Data.Bot.BotWarmupTimeInSeconds + 5), TimeSpan.FromMinutes(2)); this._externalStatsTimer = new Timer(async _ => { if (client.CurrentUser.Id.Equals(Constants.BotProductionId) && ConfigData.Data.BotLists != null && !string.IsNullOrEmpty(ConfigData.Data.BotLists.TopGgApiToken)) { Log.Information("Updating top.gg server count"); var dblApi = new AuthDiscordBotListApi(Constants.BotProductionId, ConfigData.Data.BotLists.TopGgApiToken); try { var me = await dblApi.GetMeAsync(); await me.UpdateStatsAsync(client.Guilds.Count); } catch (Exception e) { Log.Error("Exception while updating top.gg count!", e); } } else { Log.Information("Non-production bot found or top.gg token not entered, cancelling top.gg server count updater"); this._externalStatsTimer.Change(Timeout.Infinite, Timeout.Infinite); } }, null, TimeSpan.FromSeconds(ConfigData.Data.Bot.BotWarmupTimeInSeconds + 10), TimeSpan.FromMinutes(5)); this._timerEnabled = true; }
public Bot() { Panda PandaClass = new Panda(this); //attaches all exta classes with their specific methos to the bot task (and the "this" is to allow usage of form things in there) ducumentes in Xeddd.cs Xeddd XedddClass = new Xeddd(this); My MyClass = new My(this); PandaClass.pUp(); XedddClass.xedddUp(); MyClass.myUp(); bot = new DiscordClient(new DiscordConfiguration() { AutoReconnect = true, //EnableCompression = true, LogLevel = LogLevel.Debug, Token = "", TokenType = TokenType.Bot, UseInternalLogHandler = true }); interactivity = bot.UseInteractivity(new InteractivityConfiguration { }); //add the ineractivity stuff to it commands = bot.UseCommandsNext(new CommandsNextConfiguration() { //StringPrefixes = new[] { "m!" }, EnableDefaultHelp = false, IgnoreExtraArguments = false, CaseSensitive = false, PrefixResolver = PreGet }); commands.RegisterCommands <Random>(); //registers all the coammds from the different classes commands.RegisterCommands <YouTube>(); commands.RegisterCommands <Wiki>(); commands.RegisterCommands <Help>(); commands.RegisterCommands <VUTDB>(); commands.RegisterCommands <YTDLC>(); commands.RegisterCommands <Commands.RanImg.Derpy>(); commands.RegisterCommands <Commands.RanImg.MeekMoe>(); commands.RegisterCommands <Commands.RanImg.Nadeko>(); commands.RegisterCommands <Commands.RanImg.NekosLife>(); commands.RegisterCommands <Commands.RanImg.Other>(); commands.RegisterCommands <XedddSpec>(); commands.RegisterCommands <VoWiki>(); commands.RegisterCommands <Commands.Music>(); commands.CommandErrored += Bot_CMDErr; llink = bot.UseLavalink(); llink.NodeDisconnected += async le => { while (!le.LavalinkNode.IsConnected) { await Task.Delay(5000); var ok = await llink.ConnectAsync(lcfg); } }; bot.Ready += OnReadyAsync; bot.MessageCreated += this.Bot_MessageCreated; bot.MessageCreated += PandaClass.Bot_PandaMessageCreated; bot.MessageCreated += XedddClass.Bot_XedddMessageCreated; bot.MessageCreated += MyClass.Bot_MyMessageCreated; bot.MessageCreated += XedddClass.Bot_Dump; bot.MessageUpdated += this.Bot_MessageEdited; bot.MessageUpdated += PandaClass.Bot_PandaMessageEdited; bot.MessageUpdated += XedddClass.Bot_XedddMessageEdited; bot.MessageUpdated += MyClass.Bot_MyMessageEdited; bot.GuildMemberRemoved += XedddClass.Bot_XedddBoiLeave; bot.MessageReactionAdded += PandaClass.Bot_PandaGumiQuotes; bot.ClientErrored += this.Bot_ClientErrored; bot.VoiceStateUpdated += async e => { try { var con = guit[0].LLinkCon; var pos = guit.FindIndex(x => x.GID == e.Guild.Id); if (pos == -1 || !con.IsConnected || con == null) { await Task.CompletedTask; return; } var norm = e?.Channel?.Id; var afte = e?.After?.Channel?.Id; var befo = e?.Before?.Channel?.Id; if (norm == guit[pos].LLGuild?.Channel?.Id || afte == guit[pos].LLGuild?.Channel?.Id || befo == guit[pos].LLGuild?.Channel?.Id) { if (guit[pos].LLGuild?.Channel?.Users.Where(x => !x.IsBot).Count() == 0) { guit[pos].paused = true; await Task.Run(() => guit[pos].AudioFunctions.Pause(pos)); await e.Guild.GetChannel(guit[pos].cmdChannel).SendMessageAsync("Playback was paused since everybodey left the channel! uns ``m!resume`` to resume, otherwise I'll also disconnect in ~5min uwu"); var haDi = handleVoidisc(pos); haDi.Wait(millisecondsTimeout: 2500); } } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } await Task.CompletedTask; }; bot.GuildMemberAdded += async e => { if (e.Guild.Id == 483279257431441410) { await e.Member.GrantRoleAsync(e.Guild.GetRole(483280207927574528)); } await Task.CompletedTask; }; bot.Heartbeated += async e => { AuthDiscordBotListApi DblApi = new AuthDiscordBotListApi(465675368775417856, ""); var me = await DblApi.GetMeAsync(); await me.UpdateStatsAsync(e.Client.Guilds.Count); }; bot.GuildDownloadCompleted += async e => { DiscordActivity test = new DiscordActivity { Name = "m!help for commands uwu", ActivityType = ActivityType.Playing }; await bot.UpdateStatusAsync(activity : test, userStatus : UserStatus.Online); await Task.Delay(500); try { guit.Add(new Gsets { GID = 0, prefix = new List <string>(new string[] { "m!" }), LLinkCon = await llink.ConnectAsync(lcfg) }); foreach (var guilds in e.Client.Guilds) { guit.Add(new Gsets { GID = guilds.Value.Id, prefix = new List <string>(new string[] { "m!" }), queue = new List <Gsets2>(), playnow = new Gsets3(), repeat = false, offtime = DateTime.Now, shuffle = false, LLGuild = null, playing = false, rAint = 0, repeatAll = false, AudioEvents = new LLEvents(), AudioFunctions = new Functions(), AudioQueue = new Queue(), sstop = false, paused = false }); } Console.WriteLine("GuildList done!"); await Task.CompletedTask; } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } }; bot.GuildCreated += async e => { var pos = guit.FindIndex(x => x.GID == e.Guild.Id); if (pos == -1) { guit.Add(new Gsets { GID = e.Guild.Id, prefix = new List <string>(new string[] { "m!" }), queue = new List <Gsets2>(), playnow = new Gsets3(), repeat = false, offtime = DateTime.Now, shuffle = false, LLGuild = null, playing = false, rAint = 0, repeatAll = false, AudioEvents = new LLEvents(), AudioFunctions = new Functions(), AudioQueue = new Queue(), sstop = false, paused = false }); } await Task.CompletedTask; }; }
public ShardedSubmissionAdapter(AuthDiscordBotListApi api, DiscordShardedClient client, TimeSpan updateTime) : base(api, client, updateTime) { }