private static async Task <Embed> BuildServerInfoEmbed(Server server, IDiscordClient client)
        {
            var ManualOrLaunched = server.IsManualServer ? " `📃Manual server`" : " `🚀Launched server`";
            var serverInfo       = server.ServerInfo;

            var random = new Random();
            var color  = new Color(random.Next(255), random.Next(255), random.Next(255));

            var user = await client.GetUserAsync(server.ServerInfo.OwnerId);

            var username = user == null ? "Missing" : user.Username;
            var Icon     = user == null ? "" : user.GetAvatarUrl();


            var builder = new EmbedBuilder()
                          .WithTitle(serverInfo.ServerName + ManualOrLaunched)
                          .WithDescription(serverInfo.Description)
                          .WithColor(color)
                          .WithImageUrl(serverInfo.Config.ThumbnailURL)
                          .WithAuthor(author =>
            {
                author.WithName(username);
                author.IconUrl = Icon;
            })
                          .AddField("Game:", serverInfo.Config.GameType)
                          .AddField("Version:", serverInfo.Config.GameVersion)
                          .AddField("Server IP:", serverInfo.ServerIP);

            return(builder.Build());
        }
예제 #2
0
            public CommandServiceWrapper(IDiscordClient client, ILogger <CommandService> logger,
                                         IOptions <CommandServiceConfig> cmdServiceConfig, IConfiguration config) : base(cmdServiceConfig.Value)
            {
                if (ulong.TryParse(config["LoggingChannelId"], out var loggingChannelId))
                {
                    var channel = (IMessageChannel)client.GetChannelAsync(loggingChannelId).Result;
                    Log += async message =>
                    {
                        if (message.Exception is CommandException commandException)
                        {
                            await channel.SendMessageAsync(
                                $"```{commandException.Message}\n{commandException.InnerException}```");
                        }
                    };
                }

                Log += message =>
                {
                    logger.Log(
                        (LogLevel)Math.Abs((int)message.Severity - 5),
                        eventId: 0,
                        message,
                        message.Exception,
                        delegate { return(message.ToString()); });

                    return(Task.CompletedTask);
                };
            }
예제 #3
0
 public MessageHandler(IDiscordClient client, CommandService commandService, ILogger <MessageHandler> logger, IHotKeyHandler hotKeyHandler)
 {
     _client         = client;
     _commandService = commandService;
     _logger         = logger;
     _hotKeyHandler  = hotKeyHandler;
 }
예제 #4
0
 public MessageRewardService(IDiscordClient client, IBotConfigurationService config, JsonDatabaseService db, LoggingService logger)
 {
     m_client = client as DiscordSocketClient;
     m_config = config;
     m_db     = db;
     m_logger = logger;
 }
예제 #5
0
 public RandomlySendMessageBehavior(BotConfig config, IDiscordClient client, ILogger <RandomlySendMessageBehavior> logger, RandomlyConfig randomlyConfig)
 {
     _globalConfig = config;
     _client       = client as DiscordSocketClient;
     _logger       = logger;
     _config       = randomlyConfig;
 }
예제 #6
0
 public SegmentEditReactionHandler(IDiscordClient client, TicTacZapController ticTacZapController, ISegmentRepository segmentRepository, IInventoryRepository inventoryRepository)
 {
     _client = client;
     _ticTacZapController = ticTacZapController;
     _segmentRepository   = segmentRepository;
     _inventoryRepository = inventoryRepository;
 }
예제 #7
0
 public LogChannelService(IDiscordClient client, EmbedService embed, ILogger logger, IDataStore data)
 {
     _client = client;
     _embed  = embed;
     _data   = data;
     _logger = logger.ForContext <LogChannelService>();
 }
예제 #8
0
 public GiveawayService(JsonDatabaseService db, IDiscordClient client, IBotConfigurationService config, SchedulerService scheduler)
 {
     m_db        = db;
     m_client    = client;
     m_config    = config;
     m_scheduler = scheduler;
 }
예제 #9
0
 public CommandModuleBase(IDiscordClient discordClient, IDiscordBot discordBot, IServiceProvider serviceProvider, IBotConfiguration botConfiguration)
 {
     DiscordClient    = discordClient;
     DiscordBot       = discordBot;
     BotConfiguration = botConfiguration;
     ServiceProivder  = serviceProvider;
 }
예제 #10
0
 /// <summary>
 /// Creates a new <see cref="ModerationService"/>, with the given injected dependencies.
 /// </summary>
 public ModerationService(
     IDiscordClient discordClient,
     IAuthorizationService authorizationService,
     IChannelService channelService,
     IUserService userService,
     IModerationActionRepository moderationActionRepository,
     IDesignatedRoleMappingRepository designatedRoleMappingRepository,
     IInfractionRepository infractionRepository,
     IDeletedMessageRepository deletedMessageRepository,
     IDeletedMessageBatchRepository deletedMessageBatchRepository,
     IRoleService roleService,
     IDesignatedChannelService designatedChannelService,
     IDogStatsd stats = null)
 {
     DiscordClient                   = discordClient;
     AuthorizationService            = authorizationService;
     ChannelService                  = channelService;
     UserService                     = userService;
     ModerationActionRepository      = moderationActionRepository;
     DesignatedRoleMappingRepository = designatedRoleMappingRepository;
     InfractionRepository            = infractionRepository;
     DeletedMessageRepository        = deletedMessageRepository;
     DeletedMessageBatchRepository   = deletedMessageBatchRepository;
     RoleService                     = roleService;
     DesignatedChannelService        = designatedChannelService;
     Stats = stats;
 }
예제 #11
0
 public ModerationService(
     IDiscordClient discordClient,
     IAuthorizationService authorizationService,
     IChannelService channelService,
     IUserService userService,
     IModerationActionRepository moderationActionRepository,
     IDesignatedRoleMappingRepository designatedRoleMappingRepository,
     IInfractionRepository infractionRepository,
     IDeletedMessageRepository deletedMessageRepository,
     IDeletedMessageBatchRepository deletedMessageBatchRepository,
     IRoleService roleService,
     IDesignatedChannelService designatedChannelService,
     IDogStatsd dogStatsd)
 {
     _discordClient                   = discordClient;
     _authorizationService            = authorizationService;
     _channelService                  = channelService;
     _userService                     = userService;
     _moderationActionRepository      = moderationActionRepository;
     _designatedRoleMappingRepository = designatedRoleMappingRepository;
     _infractionRepository            = infractionRepository;
     _deletedMessageRepository        = deletedMessageRepository;
     _deletedMessageBatchRepository   = deletedMessageBatchRepository;
     _roleService                     = roleService;
     _designatedChannelService        = designatedChannelService;
     _dogStatsd = dogStatsd;
 }
        /// <summary>
        /// Get the discord channel that is attached to the Facebook WebHook
        /// </summary>
        /// <param name="_discordClient">THe discord client</param>
        /// <returns></returns>
        public static async Task <IMessageChannel> GetFacebookFeedChannel(this IDiscordClient _discordClient)
        {
            //  THe channel to post facebook-posts in
            IMessageChannel channel = await _discordClient.GetChannelAsync(ulong.Parse(FacebookHook.FacebookHandler.Instance.FacebookFeedChannelID)) as IMessageChannel;

            return(channel);
        }
예제 #13
0
        public static async Task Restore(MongoClient mongo, IDiscordClient client, SocketGuild guild)
        {
            var collection = mongo.GetCollection <Penalty>(client);
            var penalties  = await collection.GetPenaltiesAsync(guild.Id);

            var newPenalties = new List <Penalty>();

            if (penalties.All(p => p.PenaltyId != 1))
            {
                newPenalties.Add(new Penalty(guild.Id, 1, PenaltyType.Nothing, 1, autoDelete: true));
            }
            if (penalties.All(p => p.PenaltyId != 2))
            {
                newPenalties.Add(new Penalty(guild.Id, 2, PenaltyType.Warn, 3, autoDelete: true));
            }
            if (penalties.All(p => p.PenaltyId != 3))
            {
                newPenalties.Add(new Penalty(guild.Id, 3, PenaltyType.Kick, 5, autoDelete: true));
            }
            if (penalties.All(p => p.PenaltyId != 4))
            {
                newPenalties.Add(new Penalty(guild.Id, 4, PenaltyType.Ban, 6, autoDelete: true));
            }

            if (newPenalties.Any())
            {
                await collection.InsertManyAsync(newPenalties);

                Logger.Info($"Added default penalties to guild {guild}");
            }
        }
예제 #14
0
        /// <summary>
        /// Check if user id exists.
        /// </summary>
        /// <param name="client">N/A</param>
        /// <param name="userId">Id of user you want to check</param>
        /// <returns>Name of user if exists otherwise returns "Unknown Role."</returns>
        public static string CheckUser(this IDiscordClient client, ulong userId)
        {
            var clientDiscord = client as DiscordSocketClient;
            var user          = clientDiscord?.GetUser(userId);

            return(user == null ? "Unknown User." : user.Username);
        }
예제 #15
0
        public DatadogRoutine(
            AccountService accounts,
            AchievementService achievements,
            IAsyncEventingExecutor <IDiscordMessage> commandPipeline,
            Config config,
            IDiscordClient discordClient)
        {
            if (string.IsNullOrWhiteSpace(config.DatadogHost))
            {
                Log.Warning("Metrics are not being collected");
                return;
            }

            DogStatsd.Configure(new StatsdConfig
            {
                StatsdServerName = config.DatadogHost,
                StatsdPort       = 8125,
                Prefix           = "miki"
            });

            CreateAchievementsMetrics(achievements);
            CreateAccountMetrics(accounts);
            CreateEventSystemMetrics(commandPipeline);
            CreateDiscordMetrics(discordClient);
            Log.Message("Datadog set up!");
        }
예제 #16
0
        /// <summary>
        /// Sends the text to the specified guild's channel using a connected Discord client
        /// </summary>
        /// <param name="client">Connected Discord Client connection</param>
        /// <param name="guildID">Id of the Discord guild</param>
        /// <param name="channelID">Id of the Discord channel</param>
        /// <param name="text">Text to post</param>
        public static async Task <RestUserMessage> SendChannelMessageAsync(IDiscordClient client, ulong guildID, ulong channelID, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null)
        {
            var guild   = await(client?.GetGuildAsync(guildID)).ConfigureAwait(false);
            var channel = await(guild?.GetChannelAsync(channelID)).ConfigureAwait(false) as SocketTextChannel;

            return(await(channel?.SendMessageAsync(text, isTTS, embed, options)).ConfigureAwait(false));
        }
예제 #17
0
        /**
         * -u   = user's name
         * -um  = user's mention
         * -s   = server's name
         * -o   = owner's nickname
         * -sc  = server count
         * -now = current time
         * -uc  = user count
         */

        public LoggingModule(MikiApp app, IDiscordClient client, ISentryClient sentryClient = null)
        {
            this.app          = app;
            this.sentryClient = sentryClient;
            client.Events.GuildMemberCreate.SubscribeTask(OnClientOnGuildMemberCreateAsync);
            client.Events.GuildMemberDelete.SubscribeTask(OnClientOnGuildMemberDeleteAsync);
        }
예제 #18
0
        public static bool Check(IMessage message, AutoModerationConfig config, IDiscordClient _)
        {
            if (config.Limit == null)
            {
                return(false);
            }
            if (string.IsNullOrEmpty(config.CustomWordFilter))
            {
                return(false);
            }
            if (string.IsNullOrEmpty(message.Content))
            {
                return(false);
            }

            int matches = 0;

            foreach (string word in config.CustomWordFilter.Split('\n'))
            {
                if (string.IsNullOrWhiteSpace(word))
                {
                    continue;
                }
                try
                {
                    matches += Regex.Matches(message.Content, word, RegexOptions.IgnoreCase).Count;
                }
                catch { }
                if (matches > config.Limit)
                {
                    break;
                }
            }
            return(matches > config.Limit);
        }
예제 #19
0
        public async Task ExecuteCommandAsync(IDiscordClient client, SocketMessage socketMessage)
        {
            try
            {
                var command          = GetCommand(socketMessage.Content);
                var services         = provider.GetServices <ICommandService>();
                var filteredServices = services.Where(s => s.ImplementedCommands.Any(c => c.name == command)).ToArray();

                var args = new ExecuteCommandArgs()
                {
                    Command  = command,
                    Client   = client,
                    OurGuild = await client.GetGuildAsync(this.serverId),
                    Message  = socketMessage
                };

                if (filteredServices.Length == 0)
                {
                    args.IsCustom    = true;
                    filteredServices = services.Where(s => s.CanExecuteCustomCommand).ToArray();
                }

                await Task.WhenAll(filteredServices.Select(s => s.ExecuteCommand(args)).ToArray());
            }
            catch (Exception ex)
            {
                (socketMessage.Channel as IMessageChannel)?.SendMessageAsync($"Произошла ошибка: {ex.Message}");
            }
        }
예제 #20
0
 public AuthorizationService(IServiceProvider serviceProvider, IDiscordClient discordClient, IClaimMappingRepository claimMappingRepository)
 {
     DiscordClient = discordClient;
     // Workaround for circular dependency.
     _lazyUserService       = new Lazy <IUserService>(() => serviceProvider.GetRequiredService <IUserService>());
     ClaimMappingRepository = claimMappingRepository;
 }
예제 #21
0
        public AccountsModule(
            MikiApp app,
            Config config,
            IDiscordClient discordClient,
            AccountService accountsService,
            AchievementService achievementService,
            AchievementEvents achievementEvents,
            TransactionEvents transactionEvents)
        {
            this.app = app;
            this.achievementService = achievementService;
            this.discordClient      = discordClient;
            if (!string.IsNullOrWhiteSpace(config.ImageApiUrl))
            {
                client = new HttpClient(config.ImageApiUrl);
            }
            else
            {
                Log.Warning("Image API can not be loaded in AccountsModule");
            }

            discordClient.Events.MessageCreate.SubscribeTask(OnMessageCreateAsync);

            accountsService.OnLocalLevelUp          += OnUserLevelUpAsync;
            accountsService.OnLocalLevelUp          += OnLevelUpAchievementsAsync;
            transactionEvents.OnTransactionComplete += CheckCurrencyAchievementUnlocksAsync;

            achievementEvents.OnAchievementUnlocked
            .SubscribeTask(SendAchievementNotificationAsync);
            achievementEvents.OnAchievementUnlocked
            .SubscribeTask(CheckAchievementUnlocksAsync);
        }
예제 #22
0
        public async Task OnMessageDeleteEvent(MessageDeleteEvent e, IDiscordClient client)
        {
            if (!e.GuildId.HasValue)
            {
                return;
            }

            var channelId = await _consoleService.GetChannelId(e.GuildId.Value);

            if (e.ChannelId != channelId)
            {
                return;
            }

            var warning = await _warningRepository.GetWarningByMessageId(e.GuildId.Value, e.MessageId);

            if (warning == null)
            {
                return;
            }

            warning.ConsoleMessageId = null;
            warning.ConsoleChannelId = null;
            await _warningRepository.UpdateAsync(warning);

            var user = await client.GetUserAsync(warning.UserId);

            var moderator = await client.GetUserAsync(warning.ModeratorId);

            await _consoleService.UpdateWarningMessageAsync(e.GuildId.Value, e.ChannelId, warning, user, moderator);
        }
예제 #23
0
 public EvalService(SendingService sender, DiscordSocketClient client,
                    IMongoDatabase db)
 {
     _sender = sender;
     _client = client;
     _db     = db;
 }
예제 #24
0
        /// <summary>
        /// Constructs a new <see cref="ModerationLoggingBehavior"/> object, with injected dependencies.
        /// </summary>
        public ModerationLoggingBehavior(IServiceProvider serviceProvider, IDiscordClient discordClient, IDesignatedChannelService designatedChannelService)
        {
            DiscordClient            = discordClient;
            DesignatedChannelService = designatedChannelService;

            _lazyModerationService = new Lazy <IModerationService>(() => serviceProvider.GetRequiredService <IModerationService>());
        }
예제 #25
0
        /// <summary>
        /// Constructs a new <see cref="PromotionLoggingHandler"/> object, with injected dependencies.
        /// </summary>
        public PromotionLoggingHandler(IServiceProvider serviceProvider, IDiscordClient discordClient, IDesignatedChannelService designatedChannelService)
        {
            DiscordClient            = discordClient;
            DesignatedChannelService = designatedChannelService;

            _lazyPromotionsService = new Lazy <IPromotionsService>(() => serviceProvider.GetRequiredService <IPromotionsService>());
        }
예제 #26
0
 /// <summary>
 /// Constructs a new <see cref="UserService"/> with the given injected dependencies.
 /// </summary>
 /// <param name="discordClient">The value to use for <see cref="DiscordClient"/>.</param>
 /// <param name="authorizationService">The value to use for <see cref="AuthorizationService"/>.</param>
 /// <param name="guildService">The value to use for <see cref="GuildService"/>.</param>
 /// <param name="userRepository">The value to use for <see cref="UserRepository"/>.</param>
 /// <exception cref="ArgumentNullException">Throws for all parameters.</exception>
 public UserService(IDiscordClient discordClient, IAuthorizationService authorizationService, IGuildService guildService, IUserRepository userRepository)
 {
     DiscordClient        = discordClient ?? throw new ArgumentNullException(nameof(discordClient));
     AuthorizationService = authorizationService ?? throw new ArgumentNullException(nameof(authorizationService));
     GuildService         = guildService ?? throw new ArgumentNullException(nameof(guildService));
     UserRepository       = userRepository ?? throw new ArgumentNullException(nameof(userRepository));
 }
예제 #27
0
        public static string CheckUser(IDiscordClient client, ulong UserId)
        {
            var Client = client as DiscordSocketClient;
            var User   = Client.GetUser(UserId);

            return(User == null ? "Unknown User." : User.Username);
        }
예제 #28
0
 public AdminList(IDiscordClient client)
 {
     _admins = new HashSet <User>(new UserEqualityComparer());
     _client = client;
     _lock   = new object();
     Message = "Admin list not initialized.";
 }
예제 #29
0
 public LogChannelService(IDiscordClient client, DbConnectionFactory conn, EmbedService embed, ILogger logger)
 {
     this._client = client;
     this._conn   = conn;
     this._embed  = embed;
     _logger      = logger.ForContext <LogChannelService>();
 }
예제 #30
0
        async Task NotifyAsync(IDiscordClient client, SyncDbContext db, CancellationToken cancellationToken = default)
        {
            var time = DateTimeOffset.UtcNow;

            while (true)
            {
                var notifications = await db.Notifications.Include(n => n.User).Where(n => n.Time <= time).OrderBy(n => n.Time).Take(50).ToListAsync(cancellationToken);

                if (notifications.Count == 0)
                {
                    break;
                }

                await Task.WhenAll(notifications.Select(async notification =>
                {
                    try
                    {
                        await SendAsync(client, notification);
                    }
                    catch (Exception e)
                    {
                        _logger.LogWarning(e, $"Could not send notification '{notification.Key}' to user {notification.User.DiscordUserId}.");
                    }
                }));

                db.RemoveRange(notifications);

                await db.SaveChangesAsync(cancellationToken);

                _logger.LogInformation($"Removed {notifications.Count} notifications from queue.");
            }
        }
예제 #31
0
        private async Task SetupAsync(IDiscordClient client)
        {
            this._client = client;

            foreach (var server in await client.GetGuildsAsync())
            {
                timedoutUsers.Add(server.Id, new List<TimedoutUser>());
            }
        }
예제 #32
0
 public Timeout(IDiscordClient client)
 {
     SetupAsync(client).Wait();
 }