Example #1
0
 public EmbedService(IDatabase db, ModelRepository repo, IDiscordCache cache, DiscordApiClient rest)
 {
     _db    = db;
     _repo  = repo;
     _cache = cache;
     _rest  = rest;
 }
Example #2
0
 public static async Task CreateReactionsBulk(this DiscordApiClient rest, Message msg, string[] reactions)
 {
     foreach (var reaction in reactions)
     {
         await rest.CreateReaction(msg.ChannelId, msg.Id, new() { Name = reaction });
     }
 }
Example #3
0
        public CacheClient(
            MessageClient messenger,
            ICacheClient cacheClient,
            DiscordApiClient discordClient)
        {
            _messenger     = messenger;
            _cacheClient   = cacheClient;
            _discordClient = discordClient;

            _messenger.ChannelCreate += OnChannelCreate;
            _messenger.ChannelDelete += OnChannelDelete;
            _messenger.ChannelUpdate += OnChannelUpdate;

            _messenger.GuildBanAdd    += OnGuildBanAdd;
            _messenger.GuildBanRemove += OnGuildBanRemove;

            _messenger.GuildCreate += OnGuildCreate;
            _messenger.GuildDelete += OnGuildDelete;
            _messenger.GuildUpdate += OnGuildUpdate;

            _messenger.UserUpdate += OnUserUpdate;

            _messenger.GuildRoleCreate += OnGuildRoleCreate;
            _messenger.GuildRoleDelete += OnGuildRoleDelete;
            _messenger.GuildRoleUpdate += OnGuildRoleUpdate;

            _messenger.GuildMemberAdd    += OnGuildMemberAdd;
            _messenger.GuildMemberRemove += OnGuildMemberRemove;
            _messenger.GuildMemberUpdate += OnGuildMemberUpdate;
        }
Example #4
0
        public DiscordClient(DiscordClientConfigurations config)
        {
            _apiClient = new DiscordApiClient(
                config.Token, config.CacheClient
                );

            _websocketClient = new MessageClient(
                new MessageClientConfiguration
            {
                Token                   = config.Token,
                DatabaseClient          = config.CacheClient,
                ExchangeName            = config.RabbitMQExchangeName,
                MessengerConfigurations = config.RabbitMQUri,
                QueueName               = config.RabbitMQQueueName
            }
                );

            _websocketClient.MessageCreate += OnMessageCreate;
            _websocketClient.MessageUpdate += OnMessageUpdate;

            _websocketClient.GuildCreate += OnGuildJoin;
            _websocketClient.GuildDelete += OnGuildLeave;

            _websocketClient.UserUpdate += OnUserUpdate;

            _websocketClient.Start();
        }
Example #5
0
        static async Task Main()
        {
            // Sets up Miki.Logging for internal library logging. Can be removed if you do not want to
            // see internal logs.
            ExampleHelper.InitLog(LogLevel.Information);

            // Fetches your token from environment values.
            var token = ExampleHelper.GetTokenFromEnv();

            var memCache = new InMemoryCacheClient(new ProtobufSerializer());

            var apiClient = new DiscordApiClient(token, memCache);

            // Discord direct gateway implementation.
            var gateway = new GatewayCluster(
                new GatewayProperties
            {
                ShardCount = 1,
                ShardId    = 0,
                Token      = token.ToString(),
            });

            var discordClient = new DiscordClient(apiClient, gateway, memCache);

            // Subscribe to ready event.
            discordClient.Events.MessageCreate.SubscribeTask(OnMessageReceived);

            // Start the connection to the gateway.
            await gateway.StartAsync();

            // Wait, else the application will close.
            await Task.Delay(-1);
        }
Example #6
0
 // todo: make sure everything uses the minimum amount of REST calls necessary
 public Checks(DiscordApiClient rest, IDiscordCache cache, BotConfig botConfig, ProxyService proxy, ProxyMatcher matcher)
 {
     _rest      = rest;
     _cache     = cache;
     _botConfig = botConfig;
     _proxy     = proxy;
     _matcher   = matcher;
 }
Example #7
0
 public WebhookCacheService(ILogger logger, IMetrics metrics, DiscordApiClient rest, IDiscordCache cache)
 {
     _metrics  = metrics;
     _rest     = rest;
     _cache    = cache;
     _logger   = logger.ForContext <WebhookCacheService>();
     _webhooks = new ConcurrentDictionary <ulong, Lazy <Task <Webhook> > >();
 }
Example #8
0
        static async Task MainAsync(string[] args)
        {
            // Enables library wide logging for all Miki libraries. Consider using this logging for debugging or general information.
            new LogBuilder().SetLogHeader(x => $"[{DateTime.UtcNow.ToLongTimeString()}]")
            .AddLogEvent((msg, level) =>
            {
                if (level >= logLevel)
                {
                    Console.WriteLine($"{msg}");
                }
            }).Apply();

            // A cache client is needed to store ratelimits and entities.
            // This is an in-memory cache, and will be used as a local storage repository.
            IExtendedCacheClient cache = new InMemoryCacheClient(
                new ProtobufSerializer()
                );

            // Discord REST API implementation gets set up.
            IApiClient api = new DiscordApiClient(Token, cache);

            // Discord direct gateway implementation.
            IGateway gateway = new GatewayCluster(new GatewayProperties
            {
                ShardCount             = 1,
                ShardId                = 0,
                Token                  = Token,
                Compressed             = true,
                WebSocketClientFactory = () => new BasicWebSocketClient()
            });

            // This function adds additional utility, caching systems and more.
            DiscordClient bot = new DiscordClient(new DiscordClientConfigurations
            {
                ApiClient   = api,
                Gateway     = gateway,
                CacheClient = cache
            });

            // Add caching events for the gateway.
            new BasicCacheStage().Initialize(gateway, cache);

            // Hook up on the MessageCreate event. This will send every message through this flow.
            bot.MessageCreate += async(msg) => {
                if (msg.Content == "ping")
                {
                    IDiscordTextChannel channel = await msg.GetChannelAsync();

                    await channel.SendMessageAsync("pong!");
                }
            };

            // Start the connection to the gateway.
            await gateway.StartAsync();

            // Wait, else the application will close.
            await Task.Delay(-1);
        }
Example #9
0
 /// <summary>
 /// Initializes this Discord API client.
 /// </summary>
 /// <param name="config">Configuration for this client.</param>
 protected BaseDiscordClient(DiscordConfiguration config)
 {
     Configuration        = new DiscordConfiguration(config);
     ApiClient            = new DiscordApiClient(this);
     DebugLogger          = new DebugLogger(this);
     UserCache            = new ConcurrentDictionary <ulong, DiscordUser>();
     InternalVoiceRegions = new ConcurrentDictionary <string, DiscordVoiceRegion>();
     _voice_regions_lazy  = new Lazy <IReadOnlyDictionary <string, DiscordVoiceRegion> >(() => new ReadOnlyDictionary <string, DiscordVoiceRegion>(InternalVoiceRegions));
 }
Example #10
0
    public ErrorMessageService(BotConfig botConfig, IMetrics metrics, ILogger logger, DiscordApiClient rest)
    {
        _botConfig = botConfig;
        _metrics   = metrics;
        _logger    = logger;
        _rest      = rest;

        lastErrorTime = SystemClock.Instance.GetCurrentInstant();
    }
Example #11
0
 public MessageEdit(IDatabase db, ModelRepository repo, IClock clock, DiscordApiClient rest, WebhookExecutorService webhookExecutor, LogChannelService logChannel)
 {
     _db              = db;
     _repo            = repo;
     _clock           = clock;
     _rest            = rest;
     _webhookExecutor = webhookExecutor;
     _logChannel      = logChannel;
 }
 public LogChannelService(EmbedService embed, ILogger logger, IDatabase db, ModelRepository repo, IDiscordCache cache, DiscordApiClient rest, Bot bot)
 {
     _embed  = embed;
     _db     = db;
     _repo   = repo;
     _cache  = cache;
     _rest   = rest;
     _bot    = bot;
     _logger = logger.ForContext <LogChannelService>();
 }
 public WebhookExecutorService(IMetrics metrics, WebhookCacheService webhookCache, ILogger logger,
                               HttpClient client, IDiscordCache cache, DiscordApiClient rest)
 {
     _metrics      = metrics;
     _webhookCache = webhookCache;
     _client       = client;
     _cache        = cache;
     _rest         = rest;
     _logger       = logger.ForContext <WebhookExecutorService>();
 }
Example #14
0
 public ReactionAdded(ILogger logger, IDatabase db, ModelRepository repo, CommandMessageService commandMessageService, IDiscordCache cache, Bot bot, DiscordApiClient rest, EmbedService embeds)
 {
     _db   = db;
     _repo = repo;
     _commandMessageService = commandMessageService;
     _cache  = cache;
     _bot    = bot;
     _rest   = rest;
     _embeds = embeds;
     _logger = logger.ForContext <ReactionAdded>();
 }
Example #15
0
 public ProxiedMessage(EmbedService embeds, IClock clock,
                       DiscordApiClient rest,
                       WebhookExecutorService webhookExecutor, LogChannelService logChannel, IDiscordCache cache)
 {
     _embeds          = embeds;
     _clock           = clock;
     _rest            = rest;
     _webhookExecutor = webhookExecutor;
     _logChannel      = logChannel;
     // _cache = cache;
 }
Example #16
0
 public MessageEdited(LastMessageCacheService lastMessageCache, ProxyService proxy, IDatabase db, IMetrics metrics, ModelRepository repo, Cluster client, IDiscordCache cache, Bot bot, DiscordApiClient rest, ILogger logger)
 {
     _lastMessageCache = lastMessageCache;
     _proxy            = proxy;
     _db      = db;
     _metrics = metrics;
     _repo    = repo;
     _client  = client;
     _cache   = cache;
     _bot     = bot;
     _rest    = rest;
     _logger  = logger.ForContext <MessageEdited>();
 }
Example #17
0
 public ProxyService(LogChannelService logChannel, ILogger logger,
                     WebhookExecutorService webhookExecutor, IDatabase db, ProxyMatcher matcher, IMetrics metrics, ModelRepository repo, IDiscordCache cache, DiscordApiClient rest)
 {
     _logChannel      = logChannel;
     _webhookExecutor = webhookExecutor;
     _db      = db;
     _matcher = matcher;
     _metrics = metrics;
     _repo    = repo;
     _cache   = cache;
     _rest    = rest;
     _logger  = logger.ForContext <ProxyService>();
 }
Example #18
0
 public ProxiedMessage(EmbedService embeds,
                       DiscordApiClient rest, IMetrics metrics, ModelRepository repo, ProxyService proxy,
                       WebhookExecutorService webhookExecutor, LogChannelService logChannel, IDiscordCache cache)
 {
     _embeds          = embeds;
     _rest            = rest;
     _webhookExecutor = webhookExecutor;
     _repo            = repo;
     _logChannel      = logChannel;
     // _cache = cache;
     _metrics = metrics;
     _proxy   = proxy;
 }
Example #19
0
        public DiscordBotManager(DiscordApiClient apiClient, DiscordGatewayClient gatewayClient, DatabaseContext databaseContext,
                                 CommandHandler commandHandler, ILogger logger, IOptions <BotSettingsConfiguration> options)
        {
            ApiClient     = apiClient;
            GatewayClient = gatewayClient;

            DbContext      = databaseContext;
            BotUser        = new DiscordBotUser();
            CommandHandler = commandHandler;
            Logger         = logger;
            OwnerID        = options.Value.AdminID;

            GatewayClient.AddMessageCallback(HandleGatewayEvent);
        }
Example #20
0
 public Misc(BotConfig botConfig, IMetrics metrics, CpuStatService cpu, ShardInfoService shards, EmbedService embeds, ModelRepository repo, IDatabase db, IDiscordCache cache, DiscordApiClient rest, Bot bot, Cluster cluster)
 {
     _botConfig = botConfig;
     _metrics   = metrics;
     _cpu       = cpu;
     _shards    = shards;
     _embeds    = embeds;
     _repo      = repo;
     _db        = db;
     _cache     = cache;
     _rest      = rest;
     _bot       = bot;
     _cluster   = cluster;
 }
Example #21
0
        public CommandHandler(IOptions <BotSettingsConfiguration> options, CommandService commandService,
                              DiscordApiClient discordApiClient, ILogger logger)
        {
            CommandIdentifiers = options.Value.CommandIdentifiers;
            adminID            = options.Value.AdminID;

            BotCommands = new Dictionary <string, BotCommand>();
            TemporaryCommandHandlers = new Dictionary <string, TemporaryCommandHandler>();

            ApiClient = discordApiClient;
            Logger    = logger;

            LoadCommands(commandService);
        }
Example #22
0
    private Timer _periodicTask; // Never read, just kept here for GC reasons

    public Bot(ILifetimeScope services, ILogger logger, PeriodicStatCollector collector, IMetrics metrics,
               BotConfig config,
               ErrorMessageService errorMessageService, CommandMessageService commandMessageService,
               Cluster cluster, DiscordApiClient rest, IDiscordCache cache)
    {
        _logger                = logger.ForContext <Bot>();
        _services              = services;
        _collector             = collector;
        _metrics               = metrics;
        _config                = config;
        _errorMessageService   = errorMessageService;
        _commandMessageService = commandMessageService;
        _cluster               = cluster;
        _rest  = rest;
        _cache = cache;
    }
Example #23
0
    public static async ValueTask <User?> GetOrFetchUser(this IDiscordCache cache, DiscordApiClient rest,
                                                         ulong userId)
    {
        if (await cache.TryGetUser(userId) is User cacheUser)
        {
            return(cacheUser);
        }

        var restUser = await rest.GetUser(userId);

        if (restUser != null)
        {
            await cache.SaveUser(restUser);
        }
        return(restUser);
    }
Example #24
0
        public async Task Setup(string Token)
        {
            if (await cacheManger.ExistAsync("DBHost"))
            {
                mysqlHandler = new MysqlHandler(new MysqlConfig()
                {
                    DBHost     = await cacheManger.GetAsync("DBHost"),
                    DBUser     = await cacheManger.GetAsync("DBUser"),
                    DBPassword = await cacheManger.GetAsync("DBPassword"),
                    DBName     = await cacheManger.GetAsync("DBName")
                });
            }


            Log.OnLog += (string msg, LogLevel level) =>
            {
                if (level >= LogLevel.Information)
                {
                    Console.WriteLine(msg);
                }
            };

            IExtendedCacheClient cache = new InMemoryCacheClient(
                new ProtobufSerializer()
                );

            DiscordApiClient api = new DiscordApiClient(Token, cache);

            _gateway = new CentralizedGatewayShard(new GatewayConfiguration
            {
                ShardCount      = 1,
                ShardId         = 0,
                Token           = Token,
                WebSocketClient = new BasicWebSocketClient()
            });

            DiscordClient bot = new DiscordClient(new DiscordClientConfigurations
            {
                ApiClient   = api,
                Gateway     = _gateway,
                CacheClient = cache
            });

            new BasicCacheStage().Initialize(_gateway, cache);
            this.bot            = bot;
            DiscordBot.Instance = this;
        }
Example #25
0
 public ProxyService(LogChannelService logChannel, ILogger logger, WebhookExecutorService webhookExecutor,
                     DispatchService dispatch, IDatabase db, ProxyMatcher matcher, IMetrics metrics, ModelRepository repo,
                     NodaTime.IClock clock, IDiscordCache cache, DiscordApiClient rest, LastMessageCacheService lastMessage)
 {
     _logChannel      = logChannel;
     _webhookExecutor = webhookExecutor;
     _dispatch        = dispatch;
     _db          = db;
     _matcher     = matcher;
     _metrics     = metrics;
     _repo        = repo;
     _cache       = cache;
     _lastMessage = lastMessage;
     _rest        = rest;
     _clock       = clock;
     _logger      = logger.ForContext <ProxyService>();
 }
Example #26
0
 public MessageCreated(LastMessageCacheService lastMessageCache, LoggerCleanService loggerClean,
                       IMetrics metrics, ProxyService proxy,
                       CommandTree tree, ILifetimeScope services, IDatabase db, BotConfig config, ModelRepository repo, IDiscordCache cache, Bot bot, DiscordApiClient rest)
 {
     _lastMessageCache = lastMessageCache;
     _loggerClean      = loggerClean;
     _metrics          = metrics;
     _proxy            = proxy;
     _tree             = tree;
     _services         = services;
     _db     = db;
     _config = config;
     _repo   = repo;
     _cache  = cache;
     _bot    = bot;
     _rest   = rest;
 }
        public static void Main(string[] args)
        {
            // Timer that will run the match history check every 10 seconds.
            var checkMatchHistoryTimer = new Timer(10000);
            var riot    = new RiotApiClient();
            var discord = new DiscordApiClient(riot);

            // Register Ctrl-C and process exit handlers
            //AppDomain.CurrentDomain.ProcessExit += new EventHandler((object sender, EventArgs args) => {discord.programExitHandler();});
            Console.CancelKeyPress += new ConsoleCancelEventHandler((object sender, ConsoleCancelEventArgs args) => { discord.programExitHandler(); });

            // Register the match history check to its timer
            checkMatchHistoryTimer.Elapsed += riot.checkMatchHistories;
            checkMatchHistoryTimer.Enabled  = true;

            // Log in the discord client.
            discord.DiscordInitAsync().GetAwaiter().GetResult();
        }
Example #28
0
 public Context(ILifetimeScope provider, Shard shard, Guild?guild, Channel channel, MessageCreateEvent message, int commandParseOffset,
                PKSystem senderSystem, MessageContext messageContext)
 {
     _message               = message;
     _shard                 = shard;
     _guild                 = guild;
     _channel               = channel;
     _senderSystem          = senderSystem;
     _messageContext        = messageContext;
     _cache                 = provider.Resolve <IDiscordCache>();
     _db                    = provider.Resolve <IDatabase>();
     _repo                  = provider.Resolve <ModelRepository>();
     _metrics               = provider.Resolve <IMetrics>();
     _provider              = provider;
     _commandMessageService = provider.Resolve <CommandMessageService>();
     _parameters            = new Parameters(message.Content?.Substring(commandParseOffset));
     _rest                  = provider.Resolve <DiscordApiClient>();
     _cluster               = provider.Resolve <Cluster>();
 }
Example #29
0
        /// <summary>
        /// Creates a new webhook client, with specified HTTP proxy, timeout, and logging settings.
        /// </summary>
        /// <param name="proxy">Proxy to use for HTTP connections.</param>
        /// <param name="timeout">Timeout to use for HTTP requests. Set to <see cref="System.Threading.Timeout.InfiniteTimeSpan"/> to disable timeouts.</param>
        /// <param name="useRelativeRateLimit">Whether to use the system clock for computing rate limit resets. See <see cref="DiscordConfiguration.UseRelativeRatelimit"/> for more details.</param>
        /// <param name="loggerFactory">The optional logging factory to use for this client.</param>
        /// <param name="minimumLogLevel">The minimum logging level for messages.</param>
        /// <param name="logTimestampFormat">The timestamp format to use for the logger.</param>
        public DiscordWebhookClient(IWebProxy proxy = null, TimeSpan?timeout = null, bool useRelativeRateLimit = true,
                                    ILoggerFactory loggerFactory = null, LogLevel minimumLogLevel = LogLevel.Information, string logTimestampFormat = "yyyy-MM-dd HH:mm:ss zzz")
        {
            this._minimumLogLevel    = minimumLogLevel;
            this._logTimestampFormat = logTimestampFormat;

            if (loggerFactory == null)
            {
                loggerFactory = new DefaultLoggerFactory();
                loggerFactory.AddProvider(new DefaultLoggerProvider(this));
            }

            this.Logger = loggerFactory.CreateLogger <DiscordWebhookClient>();

            var parsedTimeout = timeout ?? TimeSpan.FromSeconds(10);

            this._apiclient = new DiscordApiClient(proxy, parsedTimeout, useRelativeRateLimit, this.Logger);
            this._hooks     = new List <DiscordWebhook>();
            this.Webhooks   = new ReadOnlyCollection <DiscordWebhook>(this._hooks);
        }
Example #30
0
 /// <summary>
 /// Creates a new webhook client, with specified HTTP proxy and timeout settings.
 /// </summary>
 /// <param name="proxy">Proxy to use for HTTP connections.</param>
 /// <param name="timeout">Timeout to use for HTTP requests. Set to <see cref="System.Threading.Timeout.InfiniteTimeSpan"/> to disable timeouts.</param>
 public DiscordWebhookClient(IWebProxy proxy, TimeSpan timeout)
 {
     this._apiclient = new DiscordApiClient(proxy, timeout);
     this._hooks     = new List <DiscordWebhook>();
     this.Webhooks   = new ReadOnlyCollection <DiscordWebhook>(this._hooks);
 }