示例#1
0
 /// <summary>
 ///     Instantiates the MpGameService for the specified Game type.
 /// </summary>
 /// <param name="client">
 ///     The Discord client.
 /// </param>
 /// <param name="mpconfig">
 ///     An optional config type.
 /// </param>
 /// <param name="logger">
 ///     An optional logging method.
 /// </param>
 public MpGameService(
     BaseSocketClient client,
     IMpGameServiceConfig mpconfig  = null,
     Func <LogMessage, Task> logger = null)
     : base(client, mpconfig, logger)
 {
 }
        public InteractiveButtonsService(BaseSocketClient discord)
        {
            Discord = discord;

            //config = config ?? new InteractiveServiceConfig();
            // _defaultTimeout = config.DefaultTimeout;
        }
示例#3
0
        public static void Init(BaseSocketClient client, IConfiguration config)
        {
            VkApi.Init(config);
            _posts = new List <VkApi.GroupPost>();

            foreach (var guild in client.Guilds)
            {
                foreach (var channel in guild.Channels)
                {
                    if (channel.Name.Equals("streamer-feed"))
                    {
                        _channel = client.GetChannel(channel.Id) as IMessageChannel;
                    }
                }
            }

            _groups = new List <Group>();
            try
            {
                using var sr = new StreamReader("vk_groups.json");
                var text = sr.ReadToEnd();
                var dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(text);
                foreach (var(key, value) in dict)
                {
                    _groups.Add(new Group(key, value));
                }
            }
            catch (Exception e)
            {
                Logger.Fatal($"Can't load vk_groups.json: {e}");
            }

            _isRunning = true;
        }
示例#4
0
        /// <summary>
        /// Initializes a new <see cref="SocketSubmissionAdapter"/>.
        /// </summary>
        /// <param name="apiClient">The <see cref="DblClient"/> for this <see cref="SocketSubmissionAdapter"/> to use.</param>
        /// <param name="client">The <see cref="BaseDiscordClient"/> for this <see cref="SocketSubmissionAdapter"/> to use.</param>
        /// <param name="properties">The properties of this <see cref="SocketSubmissionAdapter"/>.</param>
        public SocketSubmissionAdapter(DblClient apiClient, BaseSocketClient client, AdapterProperties properties = null)
        {
            if (apiClient.CurrentUserId != client.CurrentUser.Id)
            {
                throw new ArgumentException("The DblClient must reference the specified current user in the IDiscordClient");
            }

            ApiClient  = apiClient;
            Client     = client;
            properties = properties ?? AdapterProperties.Default;

            Interval = properties.Interval;
            RunMode  = properties.RunMode;
            Message  = properties.Message;

            if (RunMode == AdapterRunMode.Async)
            {
                Timer = new Timer(UpdateInternal, this, Interval, Interval);
            }
            else
            {
                Client.JoinedGuild += UpdateAsync;
                Client.LeftGuild   += UpdateAsync;
            }
        }
示例#5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InteractivityService"/> class.
        /// </summary>
        /// <param name="client">The client to listen for messages from.</param>
        /// <param name="delayedActions">The delayed actions service.</param>
        public InteractivityService(BaseSocketClient client, DelayedActionService delayedActions)
        {
            this.Client     = client;
            _delayedActions = delayedActions;

            _trackedMessages = new List <IInteractiveMessage>();
        }
示例#6
0
        /// <summary>
        ///     Create a confirmation dialog and wait for user input asynchronously.
        /// </summary>
        /// <param name="client">Client that should be listened to for the <see cref="BaseSocketClient.InteractionCreated"/> event.</param>
        /// <param name="channel">Send the confirmation prompt to this channel.</param>
        /// <param name="timeout">Timeout duration of this operation.</param>
        /// <param name="message">Optional custom prompt message.</param>
        /// <param name="cancellationToken">Token for canceling the wait operation.</param>
        /// <returns>
        ///     A Task representing the asyncronous waiting operation with a <see cref="bool"/> result,
        ///     the result is <see langword="false"/> if the user declined the prompt or didnt answer in time, <see langword="true"/> if the user confirmed the prompt.
        /// </returns>
        public static async Task <bool> ConfirmAsync(BaseSocketClient client, IMessageChannel channel, TimeSpan timeout, string message = null,
                                                     CancellationToken cancellationToken = default)
        {
            message ??= "Would you like to continue?";
            var confirmId = $"confirm";
            var declineId = $"decline";

            var component = new ComponentBuilder()
                            .WithButton("Confirm", confirmId, ButtonStyle.Success)
                            .WithButton("Cancel", declineId, ButtonStyle.Danger)
                            .Build();

            var prompt = await channel.SendMessageAsync(message, components : component).ConfigureAwait(false);

            var response = await WaitForMessageComponentAsync(client, prompt, timeout, cancellationToken).ConfigureAwait(false) as SocketMessageComponent;

            await prompt.DeleteAsync().ConfigureAwait(false);

            if (response != null && response.Data.CustomId == confirmId)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
示例#7
0
 public ExampleGameService(
     BaseSocketClient client,
     IMpGameServiceConfig?config    = null,
     Func <LogMessage, Task>?logger = null)
     : base(client, config, logger)
 {
 }
示例#8
0
        /// <summary>
        ///     Wait for an Interaction event for a given amount of time as an asynchronous opration.
        /// </summary>
        /// <param name="client">Client that should be listened to for the <see cref="BaseSocketClient.InteractionCreated"/> event.</param>
        /// <param name="timeout">Timeout duration for this operation.</param>
        /// <param name="predicate">Delegate for cheking whether an Interaction meets the requirements.</param>
        /// <param name="cancellationToken">Token for canceling the wait operation.</param>
        /// <returns>
        ///     A Task representing the asyncronous waiting operation. If the user responded in the given amount of time, Task result contains the user response,
        ///     otherwise the Task result is <see langword="null"/>.
        /// </returns>
        public static async Task <SocketInteraction> WaitForInteractionAsync(BaseSocketClient client, TimeSpan timeout,
                                                                             Predicate <SocketInteraction> predicate, CancellationToken cancellationToken = default)
        {
            var tcs = new TaskCompletionSource <SocketInteraction>();

            var  waitCancelSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            Task wait             = Task.Delay(timeout, waitCancelSource.Token)
                                    .ContinueWith((t) =>
            {
                if (!t.IsCanceled)
                {
                    tcs.SetResult(null);
                }
            });

            cancellationToken.Register(() => tcs.SetCanceled());

            client.InteractionCreated += HandleInteraction;
            var result = await tcs.Task.ConfigureAwait(false);

            client.InteractionCreated -= HandleInteraction;

            return(result);

            Task HandleInteraction(SocketInteraction interaction)
            {
                if (predicate(interaction))
                {
                    waitCancelSource.Cancel();
                    tcs.SetResult(interaction);
                }

                return(Task.CompletedTask);
            }
        }
示例#9
0
        protected async Task InitializeAsync(BaseSocketClient baseSocketClient, Configuration configuration)
        {
            this._baseSocketClient = baseSocketClient;
            var shards = baseSocketClient switch
            {
                DiscordSocketClient socketClient
                => await socketClient.GetRecommendedShardCountAsync(),

                DiscordShardedClient shardedClient
                => shardedClient.Shards.Count,

                _ => 1
            };

            this.Configuration       = configuration.SetInternals(baseSocketClient.CurrentUser.Id, shards);
            Players                  = new ConcurrentDictionary <ulong, LavaPlayer>();
            _cancellationTokenSource = new CancellationTokenSource();
            baseSocketClient.UserVoiceStateUpdated += OnUserVoiceStateUpdated;
            baseSocketClient.VoiceServerUpdated    += OnVoiceServerUpdated;

            _socketHelper            = new SocketHelper(configuration, Log);
            _socketHelper.OnMessage += OnMessage;
            _socketHelper.OnClosed  += OnClosedAsync;

            await _socketHelper.ConnectAsync().ConfigureAwait(false);
        }
示例#10
0
 public CommandHandlingService(IServiceProvider provider, BaseSocketClient discord, CommandService commands, IConfiguration config)
 {
     _commands = commands;
     _config   = config;
     _discord  = discord;
     _provider = provider;
 }
示例#11
0
        public RotatingStatusService(BaseSocketClient socket, Queue <string> statuses = null)
        {
            StatusValues = statuses ?? new Queue <string>();
            Socket       = socket;

            rotationTimer = new Timer(async _ =>
            {
                if (StatusValues.Count <= 0)
                {
                    return;
                }

                var status = StatusValues.Dequeue();
                if (status.EqualsIgnoreCase(Socket.Activity?.Name ?? ""))
                {
                    return;
                }

                StatusValues.Enqueue(status);
                await Socket.SetGameAsync(await VariableFormatting.FormatStatus(Socket, status));
            },
                                      null,
                                      Timeout.Infinite,
                                      Timeout.Infinite);
        }
示例#12
0
        public LavalinkManager(DiscordShardedClient discordShardedClient, LavalinkManagerConfig config = null)
        {
            this.config       = config ?? new LavalinkManagerConfig();
            baseDiscordClient = discordShardedClient;

            SetupManager();
        }
示例#13
0
        internal async Task <bool> HandleResponseAsync(BaseSocketClient client, T1 response)
        {
            bool valid = false;

            if (response is SocketMessage s)
            {
                valid = await RunChecksAsync(client, response).ConfigureAwait(false) && (IsUserRestricted || Users.Contains(s.Author));

                if (Deletion.HasFlag(DeletionOptions.Invalids) == true && !valid)
                {
                    await s.DeleteAsync().ConfigureAwait(false);
                }
                if (Deletion.HasFlag(DeletionOptions.Valid) == true && valid == true)
                {
                    await s.DeleteAsync().ConfigureAwait(false);
                }
            }
            if (response is SocketReaction r)
            {
                var user = r.User.Value as SocketUser ?? client.GetUser(r.UserId);
                valid = await RunChecksAsync(client, response).ConfigureAwait(false) && (IsUserRestricted || Users.Contains(user));

                if (Deletion.HasFlag(DeletionOptions.Invalids) == true && !valid)
                {
                    await r.DeleteAsync(client).ConfigureAwait(false);
                }
                if (Deletion.HasFlag(DeletionOptions.Valid) == true && valid == true)
                {
                    await r.DeleteAsync(client).ConfigureAwait(false);
                }
            }
            return(valid);
        }
示例#14
0
 public NewcomerHandler(BaseSocketClient client, ICachedRepo <NewcomerSetting> settingsRepo,
                        ICachedDbEntity <NewcomerConfig> config)
 {
     _client       = client;
     _settingsRepo = settingsRepo;
     _config       = config;
 }
示例#15
0
 public DiscordBot()
 {
     Scheduler       = new TaskScheduler();
     GuildManager    = new GuildManager();
     client          = new DiscordSocketClient();
     CommandExecutor = new Executor(this);
     EventHandler    = new EventHandler(this);
 }
示例#16
0
 public async ValueTask <int> GetShardsAsync(BaseSocketClient baseClient)
 {
     baseClient switch
     {
         DiscordSocketClient socketClient
         => await socketClient.GetRecommendedShardCountAsync().ConfigureAwait(false);;
     };
 }
示例#17
0
        /// <summary>
        ///    Wait for an Message Component Interaction event for a given amount of time as an asynchronous opration .
        /// </summary>
        /// <param name="client">Client that should be listened to for the <see cref="BaseSocketClient.InteractionCreated"/> event.</param>
        /// <param name="fromMessage">The message that <see cref="BaseSocketClient.ButtonExecuted"/> or <see cref="BaseSocketClient.SelectMenuExecuted"/> should originate from.</param>
        /// <param name="timeout">Timeout duration for this operation.</param>
        /// <param name="cancellationToken">Token for canceling the wait operation.</param>
        /// <returns>
        ///     A Task representing the asyncronous waiting operation with a <see cref="IDiscordInteraction"/> result,
        ///     the result is null if the process timed out before receiving a valid Interaction.
        /// </returns>
        public static Task <SocketInteraction> WaitForMessageComponentAsync(BaseSocketClient client, IUserMessage fromMessage, TimeSpan timeout,
                                                                            CancellationToken cancellationToken = default)
        {
            bool Predicate(SocketInteraction interaction) => interaction is SocketMessageComponent component &&
            component.Message.Id == fromMessage.Id;

            return(WaitForInteractionAsync(client, timeout, Predicate, cancellationToken));
        }
示例#18
0
 public StatusService(ServersClient api, BaseSocketClient discord, IConfiguration config,
                      ILoggerFactory loggerFactory)
 {
     _api     = api;
     _config  = config;
     _discord = discord;
     _logger  = loggerFactory.CreateLogger("Status updater");
     _hidden  = new HashSet <string>();
 }
示例#19
0
        public ResponseAwaiter(BaseSocketClient client, IConfiguration config)
        {
            _client  = client;
            _config  = config;
            _timeout = int.Parse(config["messageTimeout"]);

            _client.MessageReceived += ProcessMessage;
            _taskDictionary          = new ConcurrentDictionary <string, TaskCompletionSource <Response <string> > >();
        }
示例#20
0
        public InteractiveService(BaseSocketClient discord, InteractiveServiceConfig config = null)
        {
            Discord = discord;
            Discord.ReactionAdded += HandleReactionAsync;

            config          = config ?? new InteractiveServiceConfig();
            _defaultTimeout = config.DefaultTimeout;

            _callbacks = new Dictionary <ulong, IReactionCallback>();
        }
示例#21
0
        protected BaseInteractiveService(BaseSocketClient client, InteractiveServiceConfig config = null)
        {
            Discord = client;

            Discord.ReactionAdded      += HandleReactionAsync;
            Discord.InteractionCreated += HandleInteractionAsync;
            Discord.MessageDeleted     += HandleMessageDeleteAsync;

            config ??= new InteractiveServiceConfig();
            DefaultTimeout = config.DefaultTimeout;
        }
示例#22
0
        /// <summary>
        /// Creates a new instance of <see cref="InteractivityService"/>.
        /// </summary>
        /// <param name="client">Your instance of <see cref="BaseSocketClient"/>.</param>
        /// <param name="defaultTimeout">The default timeout for this <see cref="InteractivityService"/>.</param>
        public InteractivityService(BaseSocketClient client, TimeSpan?defaultTimeout = null)
        {
            Client          = client;
            UptimeStartTime = DateTime.Now;

            DefaultTimeout = defaultTimeout ?? TimeSpan.FromSeconds(45);
            if (DefaultTimeout <= TimeSpan.Zero)
            {
                throw new Exception("Timespan cannot be negative or zero");
            }
        }
        public DServicesClient(BaseSocketClient client, string token)
        {
            Discord    = client;
            this.token = token;

            Timer = new Timer
            {
                Interval = 600000,
                Enabled  = false
            };
            Timer.Elapsed += Timer_Elapsed;
        }
 public DiscordBotHostedService(BaseSocketClient baseSocketClient,
                                IOptions <DiscordSettings> options,
                                IGithubService githubService,
                                ILogger <DiscordBotHostedService> logger,
                                IServiceScopeFactory serviceScopeFactory)
 {
     _client              = baseSocketClient;
     _discordSettings     = options.Value;
     _logger              = logger;
     _githubService       = githubService;
     _serviceScopeFactory = serviceScopeFactory;
 }
        /// <summary>
        /// Creates a new instance of <see cref="InteractivityService"/>.
        /// </summary>
        /// <param name="client">Your instance of <see cref="BaseSocketClient"/>.</param>
        /// <param name="defaultTimeout">The default timeout for this <see cref="InteractivityService"/>.</param>
        /// <param name="runOnGateway">Whether to run the internal event handlers used for interactivity in a seperate task.</param>
        public InteractivityService(BaseSocketClient client, TimeSpan?defaultTimeout = null, bool runOnGateway = true)
        {
            Client       = client ?? throw new ArgumentNullException("client cannot be null");
            RunOnGateway = runOnGateway;

            DefaultTimeout = defaultTimeout ?? TimeSpan.FromSeconds(45);

            if (DefaultTimeout <= TimeSpan.Zero)
            {
                throw new Exception("Timespan cannot be negative or zero");
            }
        }
 public DiscordClientWorker(
     ILogger <DiscordClientWorker> logger,
     BaseSocketClient client,
     DiscordConfiguration discordConfiguration,
     IEnumerable <ISocketHandler> handlers
     )
 {
     _logger = logger;
     _client = client;
     _discordConfiguration = discordConfiguration;
     _handlers             = handlers;
 }
示例#27
0
        public KotmapModule(IConfiguration configuration, BaseSocketClient discord)
        {
            _discord = discord;

            var kotmapChannelId = configuration.GetValue <ulong>("KotmapChannelId");

            if (kotmapChannelId == default(ulong))
            {
                throw new ArgumentNullException("KotmapChannelId is not specified in config");
            }

            _kotmapChannelId = kotmapChannelId;
        }
示例#28
0
        protected async Task InitializeAsync(BaseSocketClient baseSocketClient, Configuration configuration)
        {
            this.baseSocketClient = baseSocketClient;
            logSeverity           = configuration.LogSeverity.Value;
            _players = new ConcurrentDictionary <ulong, LavaPlayer>();
            baseSocketClient.UserVoiceStateUpdated += OnUserVoiceStateUpdated;
            baseSocketClient.VoiceServerUpdated    += OnVoiceServerUpdated;

            socketHelper            = new SocketHelper(configuration, _log);
            socketHelper.OnMessage += OnMessage;

            await socketHelper.ConnectAsync().ConfigureAwait(false);
        }
示例#29
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="DiscordClientWrapper"/> class.
        /// </summary>
        /// <param name="baseSocketClient">the discord client</param>
        /// <param name="shards">the number of shards</param>
        /// <exception cref="ArgumentNullException">
        ///     thrown if the specified <paramref name="baseSocketClient"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     thrown if the specified shard count is less than 1.
        /// </exception>
        public DiscordClientWrapper(BaseSocketClient baseSocketClient, int shards)
        {
            if (shards < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(shards), shards, "Shard count must be at least 1.");
            }

            _baseSocketClient = baseSocketClient ?? throw new ArgumentNullException(nameof(baseSocketClient));
            _baseSocketClient.VoiceServerUpdated    += OnVoiceServerUpdated;
            _baseSocketClient.UserVoiceStateUpdated += OnVoiceStateUpdated;

            ShardCount = shards;
        }
示例#30
0
        public static async Task DeleteAsync(this SocketReaction reaction, BaseSocketClient client)
        {
            var channel = reaction.Channel;
            var message = reaction.Message.IsSpecified
                ? reaction.Message.Value
                :await channel.GetMessageAsync(reaction.MessageId).ConfigureAwait(false) as SocketUserMessage;

            var user = reaction.User.IsSpecified
                ? reaction.User.Value
                : client.GetUser(reaction.UserId);

            await message.RemoveReactionAsync(reaction.Emote, user).ConfigureAwait(false);
        }