public ShardedDiscordClient (DiscordSocketConfig discordSocketConfig) { _log = LogManager.GetCurrentClassLogger(); this.discordSocketConfig = discordSocketConfig; var clientList = new List<DiscordSocketClient>(); for (int i = 0; i < discordSocketConfig.TotalShards; i++) { discordSocketConfig.ShardId = i; var client = new DiscordSocketClient(discordSocketConfig); clientList.Add(client); client.UserJoined += async arg1 => await UserJoined(arg1); client.MessageReceived += async arg1 => await MessageReceived(arg1); client.UserLeft += async arg1 => await UserLeft(arg1); client.UserUpdated += async (arg1, gu2) => await UserUpdated(arg1, gu2); client.MessageUpdated += async (arg1, m2) => await MessageUpdated(arg1, m2); client.MessageDeleted += async (arg1, arg2) => await MessageDeleted(arg1, arg2); client.UserBanned += async (arg1, arg2) => await UserBanned(arg1, arg2); client.UserPresenceUpdated += async (arg1, arg2, arg3) => await UserPresenceUpdated(arg1, arg2, arg3); client.UserVoiceStateUpdated += async (arg1, arg2, arg3) => await UserVoiceStateUpdated(arg1, arg2, arg3); client.ChannelCreated += async arg => await ChannelCreated(arg); client.ChannelDestroyed += async arg => await ChannelDestroyed(arg); client.ChannelUpdated += async (arg1, arg2) => await ChannelUpdated(arg1, arg2); _log.Info($"Shard #{i} initialized."); } Clients = clientList.AsReadOnly(); }
public async Task StartAsync() { var client = new DiscordSocketClient(); Bot.Client = client; Bot.Client.Log += Client_Log; _commands = new CommandsPlugin(Bot.Client); _admincommands = new CommandsPlugin(Bot.Client, (e, s) => { return BotTools.Tools.GetPerms(s, e as IGuildUser); }, '-'); _commands.CreateCommandGroup("", group => BuildCommands(group)); _admincommands.CreateCommandGroup("", adminGroup => BuildAdminCommands(adminGroup)); BotTools.Setup.GetProgramInfo(); Bot.Client.UserJoined += BotTools.ChatEventActions.UserJoinedAsync; Bot.Client.UserLeft += BotTools.ChatEventActions.UserLeftAsync; Bot.Client.UserBanned += BotTools.ChatEventActions.UserBannedAsync; Bot.Client.MessageReceived += BotTools.ChatEventActions.MessageReceivedAsync; Bot.Client.Disconnected += BotTools.ChatEventActions.DisconnectedAsync; _commands.CommandError += async (s, e) => { if (e.Command.Text == "ayy") return; var ex = e.Exception; if (ex is PermissionException) await BotTools.Tools.ReplyAsync(e, "Sorry, you do not have the permissions to use this command!"); else await BotTools.Tools.ReplyAsync(e, $"Error: {ex.Message}."); }; await Modules.AnimeTools.AuthorizeAnilistAsync(); await LoginAsync(); await Task.Delay(-1); }
static async Task Main(string[] args) { // Configure services var services = configureServices(new ServiceCollection()).BuildServiceProvider(); using (services.CreateScope()) { _logger = services.GetService <ILogger <Program> >(); _discord = services.GetService <DiscordSocketClient>(); // Load configuration await LoadConfigAsync(); // Register events _discord.Log += handleLogAsync; _discord.MessageReceived += handleMessageAsync; // Login var connectionSource = new TaskCompletionSource <object>(); _discord.Connected += handleConnect; Task handleConnect() { connectionSource.SetResult(null); return(Task.CompletedTask); } await _discord.LoginAsync(TokenType.User, _config.AuthToken); await _discord.StartAsync(); await connectionSource.Task; _discord.Connected -= handleConnect; // Keep the bot running // TODO: graceful shutdown? while (true) { if (_config.AutoRollInterval.HasValue) { await Task.Delay(TimeSpan.FromMinutes(_config.AutoRollInterval.Value)); await sendRollAsync(); } else { await Task.Delay(1000); } } // Unregister events _discord.Log -= handleLogAsync; _discord.MessageReceived -= handleMessageAsync; // Logout await _discord.StopAsync(); await _discord.LogoutAsync(); } }
internal async Task ConnectAsync(NaggerknifeBotConfig config) { _client = new DiscordSocketClient(config.SocketConfig); _client.Log += _logger.Log; }
public StatsService(DiscordSocketClient client, CommandHandler cmdHandler, IBotCredentials creds, EvilMortyBot evilMorty, IDataCache cache) { _log = LogManager.GetCurrentClassLogger(); _client = client; _creds = creds; _redis = cache.Redis; _started = DateTime.UtcNow; _client.MessageReceived += _ => Task.FromResult(Interlocked.Increment(ref _messageCounter)); cmdHandler.CommandExecuted += (_, e) => Task.FromResult(Interlocked.Increment(ref _commandsRan)); _client.ChannelCreated += (c) => { var _ = Task.Run(() => { if (c is ITextChannel) { Interlocked.Increment(ref _textChannels); } else if (c is IVoiceChannel) { Interlocked.Increment(ref _voiceChannels); } }); return(Task.CompletedTask); }; _client.ChannelDestroyed += (c) => { var _ = Task.Run(() => { if (c is ITextChannel) { Interlocked.Decrement(ref _textChannels); } else if (c is IVoiceChannel) { Interlocked.Decrement(ref _voiceChannels); } }); return(Task.CompletedTask); }; _client.GuildAvailable += (g) => { var _ = Task.Run(() => { var tc = g.Channels.Count(cx => cx is ITextChannel); var vc = g.Channels.Count - tc; Interlocked.Add(ref _textChannels, tc); Interlocked.Add(ref _voiceChannels, vc); }); return(Task.CompletedTask); }; _client.JoinedGuild += (g) => { var _ = Task.Run(() => { var tc = g.Channels.Count(cx => cx is ITextChannel); var vc = g.Channels.Count - tc; Interlocked.Add(ref _textChannels, tc); Interlocked.Add(ref _voiceChannels, vc); }); return(Task.CompletedTask); }; _client.GuildUnavailable += (g) => { var _ = Task.Run(() => { var tc = g.Channels.Count(cx => cx is ITextChannel); var vc = g.Channels.Count - tc; Interlocked.Add(ref _textChannels, -tc); Interlocked.Add(ref _voiceChannels, -vc); }); return(Task.CompletedTask); }; _client.LeftGuild += (g) => { var _ = Task.Run(() => { var tc = g.Channels.Count(cx => cx is ITextChannel); var vc = g.Channels.Count - tc; Interlocked.Add(ref _textChannels, -tc); Interlocked.Add(ref _voiceChannels, -vc); }); return(Task.CompletedTask); }; if (_client.ShardId == 0) { _carbonitexTimer = new Timer(async(state) => { if (string.IsNullOrWhiteSpace(_creds.CarbonKey)) { return; } try { using (var http = new HttpClient()) { using (var content = new FormUrlEncodedContent( new Dictionary <string, string> { { "servercount", evilMorty.GuildCount.ToString() }, { "key", _creds.CarbonKey } })) { content.Headers.Clear(); content.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); await http.PostAsync("https://www.carbonitex.net/discord/data/botdata.php", content).ConfigureAwait(false); } } } catch { // ignored } }, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1)); } _botlistTimer = new Timer(async(state) => { if (string.IsNullOrWhiteSpace(_creds.BotListToken)) { return; } try { using (var http = new HttpClient()) { using (var content = new FormUrlEncodedContent( new Dictionary <string, string> { { "shard_count", _creds.TotalShards.ToString() }, { "shard_id", client.ShardId.ToString() }, { "server_count", client.Guilds.Count().ToString() } })) { content.Headers.Clear(); content.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); http.DefaultRequestHeaders.Add("Authorization", _creds.BotListToken); await http.PostAsync($"https://discordbots.org/api/bots/{client.CurrentUser.Id}/stats", content).ConfigureAwait(false); } } } catch (Exception ex) { _log.Error(ex); // ignored } }, null, TimeSpan.FromMinutes(5), TimeSpan.FromHours(1)); var platform = "other"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { platform = "linux"; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { platform = "osx"; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { platform = "windows"; } _dataTimer = new Timer(async(state) => { try { using (var http = new HttpClient()) { using (var content = new FormUrlEncodedContent( new Dictionary <string, string> { { "id", string.Concat(MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(_creds.ClientId.ToString())).Select(x => x.ToString("X2"))) }, { "guildCount", evilMorty.GuildCount.ToString() }, { "version", BotVersion }, { "platform", platform } })) { content.Headers.Clear(); content.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); await http.PostAsync("https://selfstats.evilMortybot.me/", content).ConfigureAwait(false); } } } catch { // ignored } }, null, TimeSpan.FromSeconds(1), TimeSpan.FromHours(1)); }
public CommandHandler(DiscordSocketClient client, CommandService commands, IServiceProvider services) { _client = client; _commands = commands; _services = services; } // end Constructor
public Watcher(DiscordSocketClient client) : base(client) { _autoPastebin = new AutoPastebin(); _imageParser = new ImageParser(); }
public ChannelController(DiscordSocketClient client, IAuthorizationService modixAuth, IDesignatedChannelService channelService) : base(client, modixAuth) { ChannelService = channelService; }
public static async Task <SocketMessage> WaitForMessageAsync(this SocketChannel channel, DiscordSocketClient client, TimeSpan timeout, Func <SocketMessage, bool> filter) { return(await client.WaitForMessageAsync(timeout, (message) => (message.Channel.Id == channel.Id && filter(message)))); }
public DiscordAccessor(DiscordSocketClient Client, DiscordRestClient RClient) { this.Client = Client; this.RClient = RClient; }
public DiscordReactionHandler(DiscordSocketClient client, RecipeService recipeService) { _client = client; _recipeService = recipeService; }
public DiscordBotContext(DiscordSocketClient client, SocketUserMessage message) { this.Client = client; this.Message = message; this.MessageData = BotMessageData.Create(Message, this.Settings); }
public HangmanCommands(DiscordSocketClient client) { _client = client; }
public TicTacToeCommands(DiscordSocketClient client) { _client = client; }
public EventService(IServiceProvider _services) { services = _services; client = services.GetRequiredService <DiscordSocketClient>(); }
private async Task MainAsync(string[] args, ILogger logger) { this.logger = logger; this.args = args; logger.Information("[Geekbot] Initing Stuff"); client = new DiscordSocketClient(new DiscordSocketConfig { LogLevel = LogSeverity.Verbose, MessageCacheSize = 1000, AlwaysDownloadUsers = true }); client.Log += DiscordLogger; commands = new CommandService(); try { var redisMultiplexer = ConnectionMultiplexer.Connect("127.0.0.1:6379"); redis = redisMultiplexer.GetDatabase(6); logger.Information($"[Redis] Connected to db {redis.Database}"); } catch (Exception e) { logger.Fatal(e, "[Redis] Redis Connection Failed"); Environment.Exit(102); } if (args.Contains("--migrate")) { Console.WriteLine("\nYou are about to migrate the database, this will overwrite an already migrated database?"); Console.Write("Are you sure [y:N]: "); var migrateDbConfirm = Console.ReadKey(); Console.WriteLine(); if (migrateDbConfirm.Key == ConsoleKey.Y) { logger.Warning("[Geekbot] Starting Migration"); await DbMigration.MigrateDatabaseToHash(redis, logger); logger.Warning("[Geekbot] Finished Migration"); } else { logger.Information("[Geekbot] Not Migrating db"); } } token = redis.StringGet("discordToken"); if (token.IsNullOrEmpty) { Console.Write("Your bot Token: "); var newToken = Console.ReadLine(); redis.StringSet("discordToken", newToken); redis.StringSet("Game", "Ping Pong"); token = newToken; firstStart = true; } services = new ServiceCollection(); userRepository = new UserRepository(redis, logger); var errorHandler = new ErrorHandler(logger); var RandomClient = new Random(); var fortunes = new FortunesProvider(RandomClient, logger); var checkEmImages = new CheckEmImageProvider(RandomClient, logger); var pandaImages = new PandaProvider(RandomClient, logger); var malClient = new MalClient(redis, logger); services.AddSingleton <IErrorHandler>(errorHandler); services.AddSingleton(redis); services.AddSingleton <ILogger>(logger); services.AddSingleton <IUserRepository>(userRepository); services.AddSingleton(RandomClient); services.AddSingleton <IFortunesProvider>(fortunes); services.AddSingleton <ICheckEmImageProvider>(checkEmImages); services.AddSingleton <IPandaProvider>(pandaImages); services.AddSingleton <IMalClient>(malClient); logger.Information("[Geekbot] Connecting to Discord"); await Login(); await Task.Delay(-1); }
public GameActionsModule(Game game, DiscordSocketClient client, DiscordClientWrapper clientWrapper) { _game = game; _client = client; _clientWrapper = clientWrapper; }
public DiggingJobProvider(IDataStorage dataStorage, GlobalUserDataProvider userProvider, DiscordSocketClient client) { _client = client; _ds = dataStorage; _gudp = userProvider; try { _activeJobs = dataStorage.Get <List <DiggingJob> >(DataStorageKey); } catch (DataStorageKeyDoesNotExistException) { _activeJobs = new List <DiggingJob>(); dataStorage.Store(_activeJobs, DataStorageKey); } }
public static async Task <bool> IsBotOwner([NotNull] this ClaimsPrincipal user, DiscordSocketClient client) { var discordUser = user.TryGetDiscordUser(client); if (discordUser == null) { return(false); } var info = await client.GetApplicationInfoAsync(); if (info.Owner == null) { return(false); } return(info.Owner.Id == discordUser.Id); }
public Connect4Commands(DiscordSocketClient client, ICurrencyService cs, GamblingConfigService gamb) : base(gamb) { _client = client; _cs = cs; }
public static async Task <bool> IsInBotGuild([NotNull] this ClaimsPrincipal user, DiscordSocketClient client) { var discordUser = user.TryGetDiscordUser(client); if (discordUser == null) { return(false); } return(discordUser.MutualGuilds.Count > 0); }
public ReadyEvent(bool addToAll, DiscordSocketClient discord, ILogger logger) { _addToAll = addToAll; _discord = discord; _manager = new Manager(Assets.MONGO_DB_CONNECTION_QUERY); _logger = logger; }
public static SocketUser TryGetDiscordUser([NotNull] this ClaimsPrincipal user, DiscordSocketClient client) { var idClaim = user.FindFirst(c => c.Type == ClaimTypes.NameIdentifier && c.Issuer == "Discord"); if (idClaim == null) { return(null); } if (!ulong.TryParse(idClaim.Value ?? "", out var id)) { return(null); } return(client.GetUser(id)); }
public static void Main(string[] args) { ApplicationBase = Path.GetDirectoryName(new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath); if (!File.Exists(Path.Combine(ApplicationBase, "Opux.db"))) { File.Copy(ApplicationBase + "/Opux.def.db", Path.Combine(ApplicationBase, "Opux.db")); } //_zKillhttpClient.Timeout = new TimeSpan(0, 0, 10); //_zKillhttpClient.DefaultRequestHeaders.Add("User-Agent", "OpuxBot"); UpdateSettings(); Client = new DiscordSocketClient(new DiscordSocketConfig() { }); Commands = new CommandService(); EveLib = new EveLib(); MainAsync().GetAwaiter().GetResult(); var headless = Convert.ToBoolean(Settings.GetSection("config")["Systemd_Support"]); if (!headless) { var dockerMode = Environment.GetEnvironmentVariable("DOCKER_MODE"); if (dockerMode != null) { Logger.DiscordClient_Log(new LogMessage(LogSeverity.Info, "Docker", "Docker mode enabled")).Wait(); if (dockerMode == "debug") { Logger.DiscordClient_Log(new LogMessage(LogSeverity.Info, "Docker", "Debug mode enabled")).Wait(); debug = true; } System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx => { Logger.DiscordClient_Log(new LogMessage(LogSeverity.Info, "Docker", "Received termination signal")).Wait(); lock (ExitLock) { Monitor.Pulse(ExitLock); } ended.Wait(); }; lock (ExitLock) { Logger.DiscordClient_Log(new LogMessage(LogSeverity.Info, "Docker", "Waiting for termination")).Wait(); Monitor.Wait(ExitLock); Logger.DiscordClient_Log(new LogMessage(LogSeverity.Info, "Docker", "Exiting")).Wait(); quit = true; } } while (!quit) { var command = Console.ReadLine(); switch (command.Split(" ")[0]) { case "quit": Console.WriteLine($"Quitting Opux"); quit = true; break; case "debug": if (!debug) { Console.WriteLine($"Debug mode Active"); debug = true; } else { Console.WriteLine($"Debug mode Disabled"); debug = false; } break; case "admin": var guild = Client.GetGuild(Convert.ToUInt64(Settings.GetSection("config")["guildId"])); var rolesToAdd = new List <SocketRole>(); var GuildRoles = guild.Roles; guild.GetUser(Convert.ToUInt64(command.Split(" ")[2])).AddRoleAsync(GuildRoles.FirstOrDefault(x => x.Name == command.Split(" ")[1])); break; } } } else { Logger.DiscordClient_Log(new LogMessage(LogSeverity.Info, "Headless", "Headless mode enabled")).Wait(); System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx => { Logger.DiscordClient_Log(new LogMessage(LogSeverity.Info, "Headless", "Received termination signal")).Wait(); lock (ExitLock) { Monitor.Pulse(ExitLock); } ended.Wait(); }; lock (ExitLock) { Logger.DiscordClient_Log(new LogMessage(LogSeverity.Info, "Headless", "Waiting for termination")).Wait(); Monitor.Wait(ExitLock); Logger.DiscordClient_Log(new LogMessage(LogSeverity.Info, "Headless", "Exiting")).Wait(); quit = true; } } Client.StopAsync(); ended.Set(); }
public async Task Start() { Console.Title = "Kratos"; // Set up our Discord client _client = new DiscordSocketClient(new DiscordSocketConfig() { LogLevel = LogSeverity.Verbose, MessageCacheSize = 100 }); _client.Log += Log; // Set up the config directory and core config if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "config"))) { Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "config")); } if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "config", "core.json"))) { _config = await CoreConfig.UseCurrentAsync(); } else { _config = await CoreConfig.CreateNewAsync(); } // Set up services _mod = new ModerationService(); await _mod.LoadConfigurationAsync(); _usernotes = new UsernoteService(); _records = new RecordService(); _tags = new TagService(); _log = new LogService(_client); await _log.LoadConfigurationAsync(); _unpunish = new UnpunishService(_client, _blacklist, _log, _records, _config); await _unpunish.GetRecordsAsync(); _slowmode = new SlowmodeService(_client, _log, _unpunish, _records, _config); _ratelimit = new RatelimitService(_client, _config, _records, _unpunish, _log); await _ratelimit.LoadConfigurationAsync(); if (_ratelimit.IsEnabled) { _ratelimit.Enable(_ratelimit.Limit); } _blacklist = new BlacklistService(_client, _unpunish, _records, _log, _config); _aliases = new AliasTrackingService(_client); await _aliases.LoadConfigurationAsync(); _permissions = new PermissionsService(); _permissions.LoadPermissions(Assembly.GetEntryAssembly()); await _permissions.LoadConfigurationAsync(); // Instantiate the dependency map and add our services and client to it. var serviceProvider = ConfigureServices(); // Set up command handler _commands = new CommandHandler(serviceProvider); await _commands.InstallAsync(); // Set up an event handler to execute some state-reliant startup tasks _client.Ready += async() => { await _blacklist.LoadConfigurationAsync(); }; // Connect to Discord await _client.LoginAsync(TokenType.Bot, _config.Token); await _client.StartAsync(); // Start unpunisher loop await _unpunish.StartAsync(); // Hang indefinitely await Task.Delay(-1); }
public DiscordTasksService(IDiscordUserService discordUserService, DiscordSocketClient discord, IConfigurationRoot config) { this._discordUserService = discordUserService; this._discord = discord; this._config = config; }
public async Task MainAsync() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); InitializeDirectories(); StartTime = DateTime.Now; string[] moods = { "Sad", "Meh", "Happy", "Extatic" }; //download content using (var client = new WebClient()) { foreach (string item in moods) { if (!File.Exists($"mood/{item}.png")) { client.DownloadFile($"https://cdn.its-sally.net/content/{item}.png", $"mood/{item}.png"); } if (!File.Exists($"mood/{item}.json")) { client.DownloadFile($"https://cdn.its-sally.net/content/{item}.json", $"mood/{item}.json"); } } } BotConfiguration = JsonConvert.DeserializeObject <BotCredentials>(File.ReadAllText("config/configuration.json")); await DatabaseAccess.InitializeAsync(BotConfiguration.DbUser, BotConfiguration.DbPassword, BotConfiguration.Db, BotConfiguration.DbHost); CredentialManager = new ConfigManager(BotConfiguration); if (!File.Exists("meta/prefix.json")) { File.Create("meta/prefix.json").Dispose(); } //store in database prefixDictionary = new Dictionary <ulong, char>(); prefixDictionary = JsonConvert.DeserializeObject <Dictionary <ulong, char> >(File.ReadAllText("meta/prefix.json")); if (prefixDictionary == null) { prefixDictionary = new Dictionary <ulong, char>(); } if (!File.Exists("ApiRequests.txt")) { // Create a file to write to. using (StreamWriter sw = File.CreateText("ApiRequests.txt")) { sw.WriteLine("0"); sw.Close(); } } RequestCounter = Int32.Parse(File.ReadAllText("ApiRequests.txt")); Client = new DiscordSocketClient(); Client.Ready += Client_Ready; Client.Log += Log; await Client.LoginAsync(TokenType.Bot, BotConfiguration.Token); await Client.StartAsync(); // Block this task until the program is closed. await Task.Delay(-1); }
public CommandHandler(DiscordSocketClient client, CommandService commands) { _commands = commands; _client = client; }
public ModerationLogService(DataService data, DiscordSocketClient client, LoggingService log) { _data = data; _client = client; _log = log; }
public async Task MainAsync() { _client = new DiscordSocketClient(); _commands = new CommandService(); _services = new ServiceCollection() .AddSingleton(_client) .AddSingleton(_commands) .BuildServiceProvider(); var token = "paste your token here"; events = new Events.Events(_client, _commands, _services); _client.Log += events.Log; _client.ReactionAdded += events.ReactionAdded; _client.ReactionRemoved += events.ReactionRemoved; _client.UserVoiceStateUpdated += events.UserVoiceStateUpdated; await _client.SetGameAsync("Among Us", null, ActivityType.Playing); await RegisterCommandsAsync(); await _client.LoginAsync(TokenType.Bot, token); await _client.StartAsync(); await Task.Delay(2500); foreach (var guild in _client.Guilds) { bool deleted = false; ulong _categoryId = 0; foreach (var category in guild.CategoryChannels.ToList()) { if (string.Compare(category.Name, Config.LobbyCategoryName, true) == 0) { _categoryId = category.Id; break; } } if (_categoryId > 0 && guild.VoiceChannels.Count > 0) { foreach (var vChan in guild.VoiceChannels) { if (vChan.CategoryId == _categoryId && vChan.Name != Config.VoiceChannelHub) { deleted = true; await vChan.DeleteAsync(); } } } var ranks = guild.Roles.Where(x => x.Name.StartsWith(Config.VoiceRoomPrefix)); if (ranks.Count() > 0) { foreach (var rank in ranks) { deleted = true; await rank.DeleteAsync(); } } if (_categoryId > 0 && deleted) { foreach (var chan in guild.TextChannels) { if (chan.Name == Config.LobbyCategoryName && chan.CategoryId == _categoryId) { await chan.SendMessageAsync(Strings.AutoRestartMessageWhenCrash(guild.Roles.Max().Mention)); } } } } // Block this task until the program is closed. await Task.Delay(-1); }
public AutoReactService(HttpClient httpClient, DiscordSocketClient client, IConfigProvider configProvider) { this.httpClient = httpClient; this.client = client; this.configProvider = configProvider; }
public CommandsPlugin(DiscordSocketClient client, Func<SocketUser, ulong, int> getPermissions = null, char commandChar = '/') { _client = client; _getPermissions = getPermissions; Commands = new List<Command>(); CommandChar = commandChar; UseCommandChar = true; var timeValues = new Dictionary<SocketUser, Dictionary<Command, DateTime>>(); client.MessageReceived += async (message) => { //Don't bother to process if there are no commands. if (Commands.Count == 0) return; //Ignore ourselves. if (message.Author.Id == _client.CurrentUser.Id) return; string msg = message.Content; if (UseCommandChar) { if (msg.Length == 0) return; if (msg[0] == CommandChar) msg = msg.Substring(1); else return; } CommandPart[] args; if (!CommandParser.ParseArgs(msg, out args)) return; try { foreach (var command in Commands) { if (args.Length < command.Parts.Length) continue; bool isValid = true; for (int i = 0; i < command.Parts.Length; i++) { if (!string.Equals(args[i].Value, command.Parts[i], StringComparison.OrdinalIgnoreCase)) { isValid = false; break; } } //Check if alias if (command.alias != null) { foreach (var alias in command.alias) { if (args[0].Value == alias) { isValid = true; break; } } } if (!isValid) continue; //Check Arg Count. int argCount = args.Length - command.Parts.Length; if (argCount < command.MinArgs || argCount > command.MaxArgs) continue; //Clean Args brb getting drinks got milk kek string[] newArgs = new string[argCount]; for (int i = 0; i < newArgs.Length; i++) newArgs[i] = args[i + command.Parts.Length].Value; //Get ArgText string argText; if (argCount == 0) argText = String.Empty; else argText = msg.Substring(args[command.Parts.Length].Index); //Check perms int permissions = getPermissions != null ? getPermissions(message.Author, ((Discord.ITextChannel)message.Channel).Guild.Id) : 0; var eventArgs = new CommandArgs(message, command, msg, argText, permissions, newArgs); if (permissions < command.MinPerms) { await BotTools.Tools.ReplyAsync(message.Author, message.Channel, "You do not have the correct permissions to use this command.", true); return; } //try to delete the message if the parameter is set. try { if (command.IsHidden && (message.Channel as IPrivateChannel) == null) await message.DeleteAsync(); } catch (Exception) { } if (message.Channel as IPrivateChannel == null) { //check if admin, if so he can ignore the time constraint and shit. bool timeCheck = true; if (!command.DelayUnignorable) { var info = BotTools.Tools.GetServerInfo(((ITextChannel)message.Channel).GuildId); if (info.roleImportancy.Count > 0) { for (int i = 0; i < info.roleImportancy.Count; i++) { ulong importantRole = info.roleImportancy.Keys.ToArray()[i]; int importantRoleAmnt = info.roleImportancy.Values.ToArray()[i]; SocketRole role = (message.Channel as ITextChannel)?.Guild.GetRole(importantRole) as SocketRole; if (role == null) continue; if ((message.Author as IGuildUser).RoleIds.Contains(role.Id) && importantRoleAmnt >= 15) { timeCheck = false; break; } } } } //Check if outside of time limit if (command.CommandDelay != null) { if (timeCheck) { Dictionary<Command, DateTime> dict; DateTime time; //if the user does not have a key, make one. Then get the key. if (!timeValues.ContainsKey(message.Author)) timeValues.Add(message.Author, new Dictionary<Command, DateTime>()); dict = timeValues[message.Author]; bool skipTimeCheck = false; //The above gets the time, and if that returns null it adds the current command with the current time to the dict. Then exit the while function. if (!dict.ContainsKey(command)) { dict.Add(command, DateTime.UtcNow); skipTimeCheck = true; } if (!skipTimeCheck) { time = dict[command]; double test = (DateTime.UtcNow - time).TotalSeconds; if ((DateTime.UtcNow - time).TotalSeconds < command.CommandDelay) { string waitTime = String.Empty; int seconds = (int)(command.CommandDelay - (DateTime.UtcNow - time).TotalSeconds); #region time calculator int days, hours, minutes = 0; minutes = seconds / 60; seconds %= 60; hours = minutes / 60; minutes %= 60; days = hours / 24; hours %= 24; if (days > 0) { string postfix; if (days == 1) postfix = "day"; else postfix = "days"; waitTime += $"{days} {postfix}"; } if (hours > 0) { if (waitTime.Length > 0) waitTime += ", "; string postfix; if (hours == 1) postfix = "hour"; else postfix = "hours"; waitTime += $"{hours} {postfix}"; } if (minutes > 0) { if (waitTime.Length > 0) waitTime += ", "; string postfix; if (minutes == 1) postfix = "minute"; else postfix = "minutes"; waitTime += $"{minutes} {postfix}"; } if (seconds > 0) { if (waitTime.Length > 0) waitTime += " and "; string postfix; if (seconds == 1) postfix = "second"; else postfix = "seconds"; waitTime += $"{seconds} {postfix}"; } #endregion if (command.FailHandler == null) await ((ITextChannel)eventArgs.Channel).SendMessageAsync($"{message.Author.Mention}: You need to wait {waitTime} before you can use /{command.Parts[0]}."); else { try { //why is this here } catch (Exception ex) { RaiseCommandError(eventArgs, ex); } } return; } } dict[command] = DateTime.UtcNow; } } } //Run Command Console.WriteLine($"[CommandEvent] {message.Author.Username} used command: {String.Join("", eventArgs.Command.Parts)}."); RaiseRanCommand(eventArgs); try { var task = command.Handler(eventArgs); if (task != null) await task; } catch (Exception ex) { RaiseCommandError(eventArgs, ex); Console.WriteLine(ex); } break; } } catch (Exception ex) { await BotTools.Tools.ReplyAsync(message.Author, message.Channel, $"Plugin error: {ex.Message}", true); BotTools.Tools.LogError("Error with plugin or something.", ex.Message); } }; }
public ReactionRoleCommands(InteractivityService interactivity, IGuildConfigRepository repo, ILoggingService logging, DiscordSocketClient client, ReactionRoleService rrService, IReactionRoleRuleRepository rrRepo) { logging.Info("Initialising Reaction Role Command Service"); _interactivity = interactivity; _repo = repo; _rrService = rrService; _rrRepo = rrRepo; _logging = new SourcedLoggingService(logging, "RRCmds"); _client = client.Rest; }