public override IMessage PostReceive(IMessage message, IMessageChannel channel)
 {
     if(!_transformOnSend) {
         message = _transformer.Transform(message);
     }
     return message;
 }
 public override void PostSend(IMessage message, IMessageChannel channel, bool sent)
 {
     if (sent)
     {
         _sentCount.IncrementValueAndReturn();
     }
 }
Ejemplo n.º 3
0
		public virtual void Configure(IMessageDispatcherSettings settings)
		{
			if (settings.InputChannel.Value == null)
			{
				throw new NoInputChannelConfiguredException("You must specify an input channel for a message dispatcher");
			}

			if (settings.InvalidChannel.Value == null)
			{
				throw new NoInputChannelConfiguredException("You must specify an invalid message channel for a message dispatcher");
			}

			if (settings.MessageProcessorTypes.Value == null || settings.MessageProcessorTypes.Value.Count == 0)
			{
				throw new NoMessageProcessorsConfiguredException(
					"You must specify one or more message processors for a message dispatcher");
			}

			if (settings.DurationOfDispatchingSlice.Value.TotalMilliseconds == 0)
			{
				throw new NoDispatchingSliceDurationConfiguredException(
					"You must specify a duration for the dispatcher to dispatch messages during.");
			}

			if (settings.NumberOfMessagesToDispatchPerSlice.Value == 0)
			{
				throw new NoNumberOfMessagesPerSliceConfiguredException(
					"You must specify the maximum number of messages to be dispatched during a slice of time.");
			}

			CurrentSettings = settings;

			InputChannel = settings.InputChannel.Value;
			InvalidChannel = settings.InvalidChannel.Value;

			MessageProcessors = new List<IMessageProcessor>();

			foreach (var type in CurrentSettings.MessageProcessorTypes.Value)
			{
				var processor = Container.GetInstance(type) as IMessageProcessor;

				if (processor == null)
				{
					continue;
				}

				this.WriteInfoMessage(string.Format("Adding processor {0} to dispatcher.", processor.GetType().Name));

				MessageProcessors.Add(processor);
			}

			this.WriteInfoMessage(
				string.Format(
					"Dispatcher configured with input channel {0}({1}) and {2} message processors.",
					InputChannel.GetType().Name,
					InputChannel.ChannelName,
					MessageProcessors.Count()));

			Configured = true;
		}
 public override IMessage PreSend(IMessage message, IMessageChannel channel)
 {
     if(_transformOnSend) {
         message = _transformer.Transform(message);
     }
     return message;
 }
 public override IMessage PostReceive(IMessage message, IMessageChannel channel)
 {
     if (message != null)
     {
         _receivedCount.IncrementValueAndReturn();
     }
     return message;
 }
Ejemplo n.º 6
0
		public PublicationTests()
		{
			_serializer = new JsonMessageSerializer();
			_blobStorage = new InMemoryBlobStorage();
			_mapper = new InMemoryRecordMapper<FakePublicationRecord>();
			_publicationRegistry = new FakeRegistry(_mapper, _blobStorage, _serializer);
			_channel = new InMemoryMessageChannel();
		}
Ejemplo n.º 7
0
		private static void SendMessages(IMessageChannel channel, int numberOfMessagesToCreate)
		{
			for (var i = 0; i < numberOfMessagesToCreate; i++)
			{
				var msg = TestTransport.GetNewMessage();
				channel.Send(msg);
			}
		}
 /// <summary>
 /// ask each <see cref="IMessageSelector"/> whether it acceppts the <see cref="IMessage"/>
 /// </summary>
 /// <param name="message">the message to send</param>
 /// <param name="channel">ignored</param>
 /// <returns>the message, if all <see cref="IMessageSelector"/>s accept the message</returns>
 /// <exception cref="MessageDeliveryException">if one <see cref="IMessageSelector"/> does not accept the <paramref name="message"/></exception>
 public override IMessage PreSend(IMessage message, IMessageChannel channel)
 {
     foreach(IMessageSelector selector in _selectors) {
         if(!selector.Accept(message)) {
             throw new MessageDeliveryException(message, "selector '" + selector + "' did not accept message");
         }
     }
     return message;
 }
 private static void StartResponder(IPollableChannel requestChannel, IMessageChannel replyChannel)
 {
     Executors.NewSingleThreadExecutor().Execute(delegate
                                                     {
                                                         IMessage request = requestChannel.Receive();
                                                         IMessage reply =
                                                             MessageBuilder.FromMessage(request).SetCorrelationId
                                                                 (request.Headers.Id).Build();
                                                         replyChannel.Send(reply);
                                                     });
 }
        /// <summary>
        /// Releases all resources held by the object.
        /// </summary>
        /// <param name="disposing"><see langword="True"/> if managed objects should be disposed, otherwise <see langword="false"/>.</param>
        public override void Dispose( bool disposing )
        {
            if ( disposing && !IsDisposed )
            {
                _channel = null;
                _subscriber = null;
                _injector = null;
            }

            base.Dispose( disposing );
        }
Ejemplo n.º 11
0
		public static void StateTransitions(IMessageChannel channel)
		{
			Assert.AreNotEqual(ChannelState.Closed, channel.State);

			var newState = channel.Open();
			channel.Clear();

			Assert.AreEqual(ChannelState.Open, newState);

			newState = channel.Close();

			Assert.AreEqual(ChannelState.Closed, newState);
		}
        public void InitializeSample()
        {
            _mocks = new MockRepository();
            _requestChannel = _mocks.StrictMock<IMessageChannel>();

            _replyChannel = _mocks.StrictMock<IPollableChannel>();
            _messageMock = _mocks.StrictMock<IMessage>();

            _simpleMessagingGateway = new SimpleMessagingGateway();
            _simpleMessagingGateway.RequestChannel = _requestChannel;
            _simpleMessagingGateway.ReplyChannel = _replyChannel;
            _simpleMessagingGateway.ObjectFactory = TestUtils.CreateTestApplicationContext();
            //reset(_allmocks);
        }
Ejemplo n.º 13
0
        public DriverCatalog(IMessageStore messageStore, IMessageChannel messageChannel)
        {
            this.MessageStores = new List<IMessageStore>();
            this.MessageChannels = new List<IMessageChannel>();

            if (messageStore != null)
            {
                this.MessageStores.Add(messageStore);
            }
            if (messageChannel != null)
            {
                this.MessageChannels.Add(messageChannel);
            }
            InitializeComposition();
        }
Ejemplo n.º 14
0
		/// <summary>
		/// Initializes a new instance of the <see cref="ChannelMessageAdapter"/>.
		/// </summary>
		/// <param name="innerAdapter">Underlying adapter.</param>
		/// <param name="inputChannel">Incomming messages channgel.</param>
		/// <param name="outputChannel">Outgoing message channel.</param>
		public ChannelMessageAdapter(IMessageAdapter innerAdapter, IMessageChannel inputChannel, IMessageChannel outputChannel)
			: base(innerAdapter)
		{
			if (inputChannel == null)
				throw new ArgumentNullException(nameof(inputChannel));

			if (outputChannel == null)
				throw new ArgumentNullException(nameof(outputChannel));

			InputChannel = inputChannel;
			OutputChannel = outputChannel;

			InputChannel.NewOutMessage += InputChannelOnNewOutMessage;
			OutputChannel.NewOutMessage += OutputChannelOnNewOutMessage;
		}
Ejemplo n.º 15
0
		public static void SendAndReceiveSingleMessage(IMessageChannel channel)
		{
			channel.Open();
			channel.Clear();

			var m = GetNewMessage();

			channel.Send(m);

			var m2 = channel.ReceiveSingle(TimeSpan.MaxValue);

			Assert.NotNull(m2);

			Assert.AreEqual(m.Identifier, m2.Identifier);

			channel.Close();
		}
Ejemplo n.º 16
0
		public static void Clear(IMessageChannel channel)
		{
			channel.Open();

			for (var i = 0; i < 5; i++)
			{
				var m = new FakeMessage();
				channel.Send(m);
			}

			channel.Clear();

			var messages = channel.ReceiveMany(5, TimeSpan.MaxValue);

			Assert.AreEqual(0, messages.Count());

			channel.Close();
		}
Ejemplo n.º 17
0
		/// <summary>
		/// Создать <see cref="ChannelMessageAdapter"/>.
		/// </summary>
		/// <param name="adapter">Адаптер.</param>
		/// <param name="inputChannel">Транспортный канал входящих сообщений.</param>
		/// <param name="outputChannel">Транспортный канал исходящих сообщений.</param>
		public ChannelMessageAdapter(IMessageAdapter adapter, IMessageChannel inputChannel, IMessageChannel outputChannel)
		{
			if (adapter == null)
				throw new ArgumentNullException("adapter");

			if (inputChannel == null)
				throw new ArgumentNullException("inputChannel");

			Adapter = adapter;

			InputChannel = inputChannel;
			OutputChannel = outputChannel;

			InputChannel.NewOutMessage += InputChannelOnNewOutMessage;
			OutputChannel.NewOutMessage += OutputChannelOnNewOutMessage;

			Adapter.NewOutMessage += AdapterOnNewOutMessage;
		}
Ejemplo n.º 18
0
        public MessageQueue(string id, IMessageStore store, IMessageChannel channel)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentException("id");
            }

            if (store == null)
            {
                throw new ArgumentNullException("store");
            }

            if (channel == null)
            {
                throw new ArgumentNullException("channel");
            }

            this.Id = id;
            this.store = store;
            this.channel = channel;
        }
Ejemplo n.º 19
0
		public static void ReceiveTimeout(IMessageChannel channel)
		{
			var ts = new TimeSpan(0, 0, 0, 0, 500);

			channel.Open();
			channel.Clear();

			var m = new FakeMessage();
			var m2 = new FakeMessage();

			channel.Send(m);
			channel.Send(m2);

			var count = 0;
			foreach (var msg in channel.ReceiveMany(2, ts))
			{
				count++;
				Thread.Sleep(500);
			}

			Assert.AreEqual(1, count);
		}
Ejemplo n.º 20
0
 //Typing
 public static async Task TriggerTypingAsync(IMessageChannel channel, BaseDiscordClient client,
                                             RequestOptions options = null)
 {
     await client.ApiClient.TriggerTypingIndicatorAsync(channel.Id, options).ConfigureAwait(false);
 }
Ejemplo n.º 21
0
        public static async Task <IUserMessage> PlayersRemoved(IMessageChannel channel, InhouseQueue queue, List <Player> list)
        {
            string players = string.Join("\r\n", queue.Players.Select(p => p.Value.Username));

            return(await channel.SendMessageAsync($"Players were removed succesfully!\r\n\r\n Queue: {players}"));
        }
Ejemplo n.º 22
0
        private Task ShowCommandHelp(CommandMap map, IUser user, IMessageChannel channel, IMessageChannel replyChannel = null)
        {
            EmbedBuilder output = EmbedBuilder();

            IEnumerable <Command> cmds = map.Commands;
            bool   isFirstCmd          = true;
            string error;

            if (cmds.Any())
            {
                foreach (var cmd in cmds)
                {
                    if (!cmd.CanRun(user, channel, out error))
                    {
                    }
                    //output.AppendLine(error ?? DefaultPermissionError);
                    else
                    {
                        if (isFirstCmd)
                        {
                            isFirstCmd = false;
                        }
                        ShowCommandHelpInternal(cmd, user, channel, output);
                    }
                }
            }
            else
            {
                output.WithTitle(map.FullName);
            }

            bool isFirstSubCmd = true;

            var field = new EmbedFieldBuilder();

            foreach (var subCmd in map.SubGroups.Where(x => x.CanRun(user, channel, out error) && x.IsVisible))
            {
                if (isFirstSubCmd)
                {
                    isFirstSubCmd = false;
                    field.WithName("Sub Commands");
                }
                else
                {
                    field.Value += ", ";
                }
                field.Value += $"`{subCmd.Name}";
                if (subCmd.SubGroups.Any())
                {
                    field.Value += "*";
                }
                field.Value += "`";
            }
            if (!string.IsNullOrEmpty(field.Name))
            {
                output.AddField(field);
            }

            if (isFirstCmd && isFirstSubCmd) //Had no commands and no subcommands
            {
                output = EmbedBuilder().WithDescription("There are no commands you have permission to run.");
            }

            return((replyChannel ?? channel).SendMessageAsync(string.Empty, embed: output.Build()));
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Create a new wire tap with the provided <see cref="IMessageSelector"/>.
 /// </summary>
 /// <param name="channel">the <see cref="IMessageChannel"/> to which intercepted messages will be sent</param>
 /// <param name="selector">the <see cref="IMessageSelector"/> that must accept a message for it to be sent to the intercepting channel</param>
 public WireTap(IMessageChannel channel, IMessageSelector selector)
 {
     AssertUtils.ArgumentNotNull(channel, "_channel", "_channel must not be null");
     _channel = channel;
     _selector = selector;
 }
Ejemplo n.º 24
0
 public static IDisposable EnterTypingState(IMessageChannel channel, BaseDiscordClient client,
                                            RequestOptions options)
 => new TypingNotifier(client, channel, options);
Ejemplo n.º 25
0
 public Reversi(IGuild guild, IMessageChannel chan, Config config, ulong playerId) : base(guild, chan, null, config, playerId, true)
 {
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="StandardMessageSubscription"/> class.
        /// </summary>
        /// <param name="channel">The channel associated with the subscription.</param>
        /// <param name="subscriber">The object that will receive the channel events.</param>
        /// <param name="injector">The injector that will be triggered an event occurs.</param>
        /// <param name="deliveryThread">The thread context that should be used to deliver the message.</param>
        public StandardMessageSubscription( IMessageChannel channel, object subscriber, MethodInjector injector,
                                            DeliveryThread deliveryThread )
        {
            _channel = channel;
            _subscriber = subscriber;
            _injector = injector;
            _deliveryThread = deliveryThread;

#if !SILVERLIGHT && !NETCF
            if ( deliveryThread == DeliveryThread.UserInterface )
            {
                _syncContext = SynchronizationContext.Current;
            }
#endif
        }
Ejemplo n.º 27
0
 public static Func <string, string, Task <IUserMessage> > SendMessageToChannel(IMessageChannel channel, bool replyable, ShardedCommandContext context)
 {
     if (!replyable)
     {
         return(async(username, message) =>
         {
             message = CheckForMentions(channel, message);
             if (string.IsNullOrEmpty(username))
             {
                 return await SendMessageAndCatchError(() => { return channel.SendMessageAsync(message); }, context);
             }
             return await SendMessageAndCatchError(() => { return channel.SendMessageAsync($"**{username}**: {message}"); }, context);
         });
     }
     return(async(username, message) =>
     {
         var key = LoadConfig.Instance.config["encryptionKey"];
         var replyHash = Rijndael.Encrypt(context.User.Id.ToString(), key, KeySize.Aes256);
         var view = Views.ReplyableMessage.Response(username, message, replyHash.ToString());
         return await SendMessageAndCatchError(() => { return channel.SendMessageAsync(view.Item1, embed: view.Item2); }, context);
     });
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Plays a song in a given voice channel
        /// </summary>
        /// <param name="guild">The <see cref="SocketGuild"/> where we are playing in</param>
        /// <param name="channel">The <see cref="IMessageChannel"/> to log messages to</param>
        /// <param name="target">The target <see cref="IVoiceChannel"/> to play music in</param>
        /// <param name="user">The <see cref="IUser"/> who requested this command</param>
        /// <param name="search">The query to search for</param>
        /// <returns></returns>
        public async Task SendAudio(SocketGuild guild, IMessageChannel channel, IVoiceChannel target, IUser user,
                                    string search)
        {
            //Join the voice channel the user is in if we are already not in a voice channel
            if (!CheckIfServerIsPlayingMusic(guild, out ServerMusicItem serverMusicList))
            {
                await JoinAudio(guild, target, channel, user);

                serverMusicList = GetMusicList(guild.Id);
            }

            //Check to see if the user is in the playing audio channel
            if (!await CheckIfUserInChat(user, channel, serverMusicList))
            {
                return;
            }

            //Make sure the search isn't empty or null
            if (string.IsNullOrWhiteSpace(search))
            {
                await channel.SendMessageAsync("You need to input a search!");

                return;
            }

            IUserMessage message =
                await channel.SendMessageAsync($":musical_note: Preparing to search for '{search}'");

            string songFileLocation;
            string songName;

            search.RemoveIllegalChars();

            try
            {
                songFileLocation = await GetOrDownloadSong(search, message, guild, serverMusicList);

                //It failed
                if (songFileLocation == null)
                {
                    return;
                }

                Logger.Log($"Playing song from {songFileLocation}", LogVerbosity.Debug);

                //This is so we say "Now playing 'Epic Song'" instead of "Now playing 'Epic Song.mp3'"
                songName = Path.GetFileName(songFileLocation).Replace($".{fileFormat.GetFormatExtension()}", "");

                //If there is already a song playing, cancel it
                await StopPlayingAudioOnServer(serverMusicList);
            }
            catch (Exception ex)
            {
                Logger.Log(ex.ToString(), LogVerbosity.Error);
                return;
            }

            //Create music playback for our music format
            IMusicPlaybackInterface playbackInterface = serverMusicList.MusicPlayback = CreateMusicPlayback(songFileLocation);

            //Log (if enabled) to the console that we are playing a new song
            if (Config.bot.AudioSettings.LogPlayStopSongToConsole)
            {
                Logger.Log($"The song '{songName}' on server {guild.Name}({guild.Id}) has started.",
                           LogVerbosity.Music);
            }

            serverMusicList.CancellationSource = new CancellationTokenSource();
            CancellationToken token = serverMusicList.CancellationSource.Token;

            serverMusicList.IsPlaying = true;

            //Create an outgoing pcm stream
            await using (AudioOutStream outStream = serverMusicList.AudioClient.CreatePCMStream(AudioApplication.Music))
            {
                bool      fail       = false;
                bool      exit       = false;
                const int bufferSize = 1024;
                byte[]    buffer     = new byte[bufferSize];

                await MessageUtils.ModifyMessage(message, $":musical_note: Now playing **{songName}**.");

                while (!fail && !exit)
                {
                    try
                    {
                        if (token.IsCancellationRequested)
                        {
                            exit = true;
                            break;
                        }

                        //Read from stream
                        int read = await playbackInterface.ReadAudioStream(buffer, bufferSize, token);

                        if (read == 0)
                        {
                            exit = true;
                            break;
                        }

                        //Flush
                        await playbackInterface.Flush();

                        //Write it to outgoing pcm stream
                        await outStream.WriteAsync(buffer, 0, read, token);

                        //If we are still playing
                        if (serverMusicList.IsPlaying)
                        {
                            continue;
                        }

                        //For pausing the song
                        do
                        {
                            //Do nothing, wait till is playing is true
                            await Task.Delay(100, token);
                        } while (serverMusicList.IsPlaying == false);
                    }
                    catch (OperationCanceledException)
                    {
                        //User canceled
                    }
                    catch (Exception ex)
                    {
                        await channel.SendMessageAsync("Sorry, but an error occured while playing!");

                        if (Config.bot.ReportErrorsToOwner)
                        {
                            await Global.BotOwner.SendMessageAsync(
                                $"ERROR: {ex.Message}\nError occured while playing music on guild `{guild.Id}`.");
                        }

                        fail = true;
                    }
                }

                if (Config.bot.AudioSettings.LogPlayStopSongToConsole)
                {
                    Logger.Log($"The song '{songName}' on server {guild.Name}({guild.Id}) has stopped.",
                               LogVerbosity.Music);
                }

                //There wasn't a request to cancel
                if (!token.IsCancellationRequested)
                {
                    await channel.SendMessageAsync($":musical_note: **{songName}** ended.");
                }

                //Clean up
                // ReSharper disable MethodSupportsCancellation
                await outStream.FlushAsync();

                outStream.Dispose();
                serverMusicList.IsPlaying = false;

                playbackInterface.EndAudioStream();
                serverMusicList.MusicPlayback = null;
                // ReSharper restore MethodSupportsCancellation

                serverMusicList.CancellationSource.Dispose();
                serverMusicList.CancellationSource = null;
            }
        }
Ejemplo n.º 29
0
        public static async Task RunWaivers(HtmlDocument feed, string leagueId, IMessageChannel channel)
        {
            var waiverWeb            = new HtmlWeb();
            var systemIcon           = "";
            var tempDateTime         = "";
            HtmlNodeCollection nodes = null;
            Embed embed = null;

            if (leagueId == "73")
            {
                systemIcon =
                    "https://cdn.discordapp.com/attachments/689119430021873737/711030693743820800/220px-PlayStation_logo.svg.jpg";
                nodes = feed.DocumentNode.SelectNodes("//*[@id='newsfeed_page']/ol/li[1]");
            }
            else if (leagueId == "53")
            {
                systemIcon =
                    "https://cdn.discordapp.com/attachments/689119430021873737/711030386775293962/120px-Xbox_one_logo.svg.jpg";
                nodes = feed.DocumentNode.SelectNodes("//*[@id='newsfeed_page']/ol/li[1]/div/h3");
            }

            foreach (var items in nodes)
            {
                tempDateTime = items.SelectSingleNode("//*[@id='newsfeed_page']/ol/li[1]/div/abbr").InnerText;
                var line    = items.SelectSingleNode("//*[@id='newsfeed_page']/ol/li[1]/div/h3").InnerText;
                var newLine = "";

                if (line.Contains("The "))
                {
                    newLine = line.Replace("The ", string.Empty);
                }
                if (line.Contains("the "))
                {
                    newLine = newLine.Replace("the ", string.Empty);
                }
                if (newLine == string.Empty)
                {
                    newLine = line;
                }
                IList <string> waiverLine = new List <string>();

                var lastNews = DateTime.Parse(tempDateTime);
                if (!NewsWriter.SaveWaiver(lastNews, newLine, leagueId))
                {
                    break;
                }
                EmbedBuilder builder = null;

                if (line.Contains("has cleared"))
                {
                    waiverLine = newLine.Split(new[] { "has", "cleared", "and put onto" }, StringSplitOptions.None);
                    if (waiverLine.Any())
                    {
                        builder = new EmbedBuilder()
                                  .WithColor(new Color(0xFF0019))
                                  .WithTimestamp(lastNews)
                                  .WithFooter(footer =>
                        {
                            footer
                            .WithText("leaguegaming.com/fifa")
                            .WithIconUrl("https://www.leaguegaming.com/images/league/icon/l53.png");
                        })
                                  .WithAuthor(author =>
                        {
                            author
                            .WithName("LGFA Waiver News")
                            .WithIconUrl(systemIcon);
                        })
                                  .WithDescription("**Player cleared waivers.**")
                                  .AddField("User", waiverLine[0], true)
                                  .AddField("Status", "Cleared", true)
                                  .AddField("Placement", "Training Camp", true);
                        embed = builder.Build();
                    }
                }
                else if (line.Contains("have claimed"))
                {
                    waiverLine = newLine.Split(new[] { "have claimed", "off of waivers" }, StringSplitOptions.None);
                    if (waiverLine.Any())
                    {
                        builder = new EmbedBuilder()
                                  .WithColor(new Color(0xFF0019))
                                  .WithTimestamp(lastNews)
                                  .WithFooter(footer =>
                        {
                            footer
                            .WithText("leaguegaming.com/fifa")
                            .WithIconUrl("https://www.leaguegaming.com/images/league/icon/l53.png");
                        })
                                  .WithAuthor(author =>
                        {
                            author
                            .WithName("LGFA Waiver News")
                            .WithIconUrl(systemIcon);
                        })
                                  .WithDescription("**Player Claimed off waivers.**")
                                  .AddField("New Team", waiverLine[0], true)
                                  .AddField("User", waiverLine[1], true)
                                  .AddField("Status", "Claimed", true);
                        //.AddField("Placement", placement, true);
                        embed = builder.Build();
                    }
                }
                else if (line.Contains("have placed"))
                {
                    waiverLine = newLine.Split(new[] { "have placed", "on waivers" }, StringSplitOptions.None);
                    if (waiverLine.Any())
                    {
                        builder = new EmbedBuilder()
                                  .WithColor(new Color(0xFF0019))
                                  .WithTimestamp(lastNews)
                                  .WithFooter(footer =>
                        {
                            footer
                            .WithText("leaguegaming.com/fifa")
                            .WithIconUrl("https://www.leaguegaming.com/images/league/icon/l53.png");
                        })
                                  .WithAuthor(author =>
                        {
                            author
                            .WithName("LGFA Waiver News")
                            .WithIconUrl(systemIcon);
                        })
                                  .WithDescription("**Player placed on waivers.**")
                                  .AddField("User", waiverLine[1], true)
                                  .AddField("Current Team", waiverLine[0], true)
                                  .AddField("Status", "On Waivers", true);
                        embed = builder.Build();
                    }
                }

                await channel.SendMessageAsync(null, embed : embed).ConfigureAwait(false);
            }
        }
Ejemplo n.º 30
0
        internal static async Task <bool> CheckUserTimeout(SocketUser usr, ulong guildID, IMessageChannel channel)
        {
            var Tracker = UserTimeouts.SingleOrDefault(ut => ut.TrackedUser == usr && ut.GuildID == guildID);

            if (Tracker != null)
            {
                TimeoutTimer t   = UserTimeoutTimers.SingleOrDefault(p => p.Tracker == Tracker);
                var          msg = await channel.SendMessageAsync($"Slow down {usr.Username}! Try again in {TimeSpan.FromSeconds((int)Constants._CMDTIMEOUT_ - (DateTime.Now - t.StartTime).TotalSeconds).Seconds}.{(TimeSpan.FromSeconds(5 - (DateTime.Now - t.StartTime).TotalSeconds).Milliseconds) / 100} seconds.");

                AddRandomTracker((RestUserMessage)msg);
                return(false);
            }
            return(true);
        }
Ejemplo n.º 31
0
 public HelpCommand(IUser author, IConfiguration config, IMessageChannel channel, IMessageWriter messageWriter, ICommandsInfo commandsInfo, IValidationHandler validationHandler, params string[] parameters)
     : base(author, config, channel, messageWriter, validationHandler, parameters)
 {
     _commandsInfo = commandsInfo;
 }
Ejemplo n.º 32
0
 public Task HandleMessagesBulkDelete(IReadOnlyCollection <Cacheable <IMessage, ulong> > messages,
                                      IMessageChannel channel) => _proxy.HandleMessageBulkDeleteAsync(messages, channel);
Ejemplo n.º 33
0
 public static async Task <IUserMessage> QueueStarted(IMessageChannel channel, InhouseQueue queue)
 {
     return(await channel.SendMessageAsync($"New Inhouse Queue created named {queue.Name}!"));
 }
 /// <summary>
 /// set the reply channel
 /// </summary>
 /// <param name="replyChannel">the reply channel</param>
 /// <returns>the current instance</returns>
 public MessageBuilder SetReplyChannel(IMessageChannel replyChannel)
 {
     return SetHeader(MessageHeaders.REPLY_CHANNEL, replyChannel);
 }
Ejemplo n.º 35
0
        /*
         * Match Output
         * @param matches - List of Match Pairings
         * @param channel - Channel Object for the Output Channel
         */
        public static async Task <IMessage> OutputUniqueMatches(List <Tuple <List <Player>, List <Player> > > matches, int groupNumber, IMessageChannel channel)
        {
            int          MaxMatchDisplayCount = 5;
            EmbedBuilder embedBuilder         = new EmbedBuilder();

            for (int i = 0; i < matches.Count && i < MaxMatchDisplayCount; i++)
            {
                // Generate Strings for Team Compositions
                var match = matches[i];
                var team1 = string.Join('\n', match.Item1.Select(m => m.Username + " (~" + m.MMR + ")"));
                var team2 = string.Join('\n', match.Item2.Select(m => m.Username + " (~" + m.MMR + ")"));

                // Generate Strings for Average Team MMRs
                int team1MMR = match.Item1.Sum(item => item.MMR) / match.Item1.Count;
                int team2MMR = match.Item2.Sum(item => item.MMR) / match.Item2.Count;

                // Add fields to EmbedBuilder
                embedBuilder.AddField($"Match {i + 1}", "\u200b");
                embedBuilder.AddField($"Orange ({team1MMR}):", team1, true);
                embedBuilder.AddField($"Blue ({team2MMR}):", team2, true);
                embedBuilder.AddField("\u200B", "\u200B");
            }

            return(await channel.SendMessageAsync($"**Group {groupNumber} ({matches.Count} Matches)**", false, embedBuilder.Build()));
        }
Ejemplo n.º 36
0
        public Task ShowCommandHelp(Command command, IUser user, IMessageChannel channel, IMessageChannel replyChannel = null)
        {
            var output = EmbedBuilder();

            if (!command.CanRun(user, channel, out var error))
            {
                output.WithDescription(error ?? "You do not have permission to access this command.");
            }
            else
            {
                ShowCommandHelpInternal(command, user, channel, output);
            }
            return((replyChannel ?? channel).SendMessageAsync(string.Empty, embed: output.Build()));
        }
Ejemplo n.º 37
0
        public async override Task <IUserMessage> SendAsync(IMessageChannel channel)
        {
            await UpdateMessageAsync();

            return(await base.SendAsync(channel));
        }
Ejemplo n.º 38
0
 public static Task <IUserMessage> SendTableAsync <T>(this IMessageChannel ch, IEnumerable <T> items, Func <T, string> howToPrint, int columns = 3) =>
 ch.SendTableAsync("", items, howToPrint, columns);
Ejemplo n.º 39
0
        /// <summary>
        /// danny kamisama
        /// </summary>
        public static async Task SendPaginatedConfirmAsync(this IMessageChannel channel, int currentPage, Func <int, EmbedBuilder> pageFunc, int?lastPage = null, bool addPaginatedFooter = true)
        {
            lastPage += 1;
            var embed = pageFunc(currentPage);

            if (addPaginatedFooter)
            {
                embed.AddPaginatedFooter(currentPage, lastPage);
            }

            var msg = await channel.EmbedAsync(embed) as IUserMessage;

            if (currentPage >= lastPage && lastPage == 1)
            {
                return;
            }

            await msg.AddReactionAsync(arrow_left).ConfigureAwait(false);

            await msg.AddReactionAsync(arrow_right).ConfigureAwait(false);

            await Task.Delay(2000).ConfigureAwait(false);

            Action <SocketReaction> changePage = async r =>
            {
                try
                {
                    if (r.Emoji.Name == arrow_left)
                    {
                        if (currentPage == 1)
                        {
                            return;
                        }
                        var toSend = pageFunc(--currentPage);
                        if (addPaginatedFooter)
                        {
                            toSend.AddPaginatedFooter(currentPage, lastPage);
                        }
                        await msg.ModifyAsync(x => x.Embed = toSend.Build()).ConfigureAwait(false);
                    }
                    else if (r.Emoji.Name == arrow_right)
                    {
                        if (lastPage == null || lastPage > currentPage)
                        {
                            var toSend = pageFunc(++currentPage);
                            if (addPaginatedFooter)
                            {
                                toSend.AddPaginatedFooter(currentPage, lastPage);
                            }
                            await msg.ModifyAsync(x => x.Embed = toSend.Build()).ConfigureAwait(false);
                        }
                    }
                }
                catch (Exception ex) { Console.WriteLine(ex); }
            };

            using (msg.OnReaction(changePage, changePage))
            {
                await Task.Delay(30000).ConfigureAwait(false);
            }

            await msg.RemoveAllReactionsAsync().ConfigureAwait(false);
        }
Ejemplo n.º 40
0
 public ITwoChoicesBitObliviousTransferChannel CreateChannel(IMessageChannel channel)
 {
     return(new TwoChoicesBitObliviousTransferChannelAdapter(_otProvider.CreateChannel(channel)));
 }
Ejemplo n.º 41
0
 public static Task <IUserMessage> SendConfirmAsync(this IMessageChannel ch, string text)
 => ch.SendMessageAsync("", embed: new EmbedBuilder().WithOkColor().WithDescription(text));
Ejemplo n.º 42
0
        /// <summary>
        /// Intercept the Message and, <em>if accepted</em> by the <see cref="IMessageSelector"/>,
        /// send it to the secondary target. If this wire tap's <see cref="IMessageSelector"/> is
        /// <code>null</code>, it will accept all messages.
        /// </summary>
        /// <param name="message">the message to intercept</param>
        /// <param name="channel">the channel to send to if accepted</param>
        /// <returns></returns>
        public override IMessage PreSend(IMessage message, IMessageChannel channel)
        {
            if(_running && (_selector == null || _selector.Accept(message))) {
                bool sent = _timeout == TimeSpan.Zero ? _channel.Send(message, _timeout) : _channel.Send(message);

                #region logging
                if(!sent && logger.IsWarnEnabled) {
                    logger.Warn("failed to send message to WireTap _channel '" + _channel + "'");
                }
                #endregion
            }
            return message;
        }
 public MessageChannelSelectorStub(IMessageChannel messageChannel) {
     _messageChannel = messageChannel;
 }
Ejemplo n.º 44
0
        public Task ShowGeneralHelp(IUser user, IMessageChannel channel, IMessageChannel replyChannel = null)
        {
            if (replyChannel == null)
            {
                replyChannel = channel;
            }
            var    output       = EmbedBuilder();
            var    tasks        = new List <Task>();
            Action sendAndClear = () =>
            {
                tasks.Add(replyChannel.SendMessageAsync(embed: output.Build()));
                output = EmbedBuilder();
            };
            bool isFirstCategory = true;

            foreach (var category in _categories)
            {
                bool   isFirstItem   = true;
                bool   isNamelessCat = category.Key == "";
                var    field         = new EmbedFieldBuilder();
                string value         = string.Empty;
                foreach (var group in category.Value.SubGroups)
                {
                    if (group.IsVisible && (group.HasSubGroups || group.HasNonAliases) && group.CanRun(user, channel, out var error))
                    {
                        if (isFirstItem)
                        {
                            isFirstItem = false;
                            //This is called for the first item in each category. If we never get here, we dont bother writing the header for a category type (since it's empty)
                            if (isFirstCategory)
                            {
                                isFirstCategory = false;
                                //Called for the first non-empty category
                                output.WithTitle("These are the commands you can use:");
                            }
                            if (!isNamelessCat)
                            {
                                field.Name = category.Key;
                            }
                        }
                        else
                        {
                            value += ", ";
                        }
                        value += $"`{group.Name}";
                        if (group.HasSubGroups)
                        {
                            value += "*";
                        }
                        value += "`";

                        if (value.ToString().Length >= (isNamelessCat ? Discord.EmbedBuilder.MaxDescriptionLength : EmbedFieldBuilder.MaxFieldValueLength) - 100) // Allow 100 characters to avoid going over character limit
                        {
                            if (isNamelessCat)
                            {
                                output.WithDescription(value);
                                sendAndClear();
                            }
                            else
                            {
                                output.AddField(field);
                                field = new EmbedFieldBuilder();
                            }
                            isFirstItem = true;
                        }
                    }
                }
                if (isNamelessCat)
                {
                    output.WithDescription(value);
                }
                else
                {
                    output.AddField(field);
                }
                if (output.Fields.Count == Discord.EmbedBuilder.MaxFieldCount)
                {
                    sendAndClear();
                }
            }

            if (string.IsNullOrEmpty(output.Description) && output.Fields.Count == 0 && tasks.Count() == 0)
            {
                output.WithDescription("There are no commands you have permission to run.");
            }
            else
            {
                var  field     = new EmbedFieldBuilder().WithName("Furthermore");
                var  chars     = Config.CommandChars;
                bool has_chars = chars.Any();
                if (has_chars)
                {
                    field.Value = $"You can use `{(chars.Length == 1 ? chars[0].ToString() : $"{string.Join(" ", chars.Take(chars.Length - 1))}` or `{chars.Last()}")}` to call a command.\n";
                }
                if (Config.MentionCommandChar != 0)
                {
                    field.Value += $"You can {(has_chars ? "also " : "")}@mention me before {(Config.MentionCommandChar == 1 ? "" : "or after ")}a command{(has_chars ? ", instead" : "")}.\n";
                }
                field.Value += $"`{(has_chars ? chars[0].ToString() : "")}help <command>` can tell you more about how to use a command.";
                output.AddField(field);
            }


            tasks.Add(replyChannel.SendMessageAsync(string.Empty, embed: output.Build()));
            return(Task.WhenAll(tasks));
        }
 /// <summary>
 /// Creates a publication for the specified channel.
 /// </summary>
 /// <param name="channel">The channel that will receive the publications.</param>
 /// <param name="publisher">The object that will publish events.</param>
 /// <param name="evt">The event that will be published to the channel.</param>
 /// <returns>The newly-created publicaton.</returns>
 public IMessagePublication Create( IMessageChannel channel, object publisher, EventInfo evt )
 {
     return new StandardMessagePublication( channel, publisher, evt );
 }
Ejemplo n.º 46
0
        public static IAsyncEnumerable <IReadOnlyCollection <RestMessage> > GetMessagesAsync(IMessageChannel channel, BaseDiscordClient client,
                                                                                             ulong?fromMessageId, Direction dir, int limit, RequestOptions options)
        {
            if (dir == Direction.Around)
            {
                throw new NotImplementedException(); //TODO: Impl
            }
            var guildId = (channel as IGuildChannel)?.GuildId;
            var guild   = guildId != null ? (client as IDiscordClient).GetGuildAsync(guildId.Value, CacheMode.CacheOnly).Result : null;

            return(new PagedAsyncEnumerable <RestMessage>(
                       DiscordConfig.MaxMessagesPerBatch,
                       async(info, ct) =>
            {
                var args = new GetChannelMessagesParams
                {
                    RelativeDirection = dir,
                    Limit = info.PageSize
                };
                if (info.Position != null)
                {
                    args.RelativeMessageId = info.Position.Value;
                }

                var models = await client.ApiClient.GetChannelMessagesAsync(channel.Id, args, options).ConfigureAwait(false);
                var builder = ImmutableArray.CreateBuilder <RestMessage>();
                foreach (var model in models)
                {
                    var author = GetAuthor(client, guild, model.Author.Value, model.WebhookId.ToNullable());
                    builder.Add(RestMessage.Create(client, channel, author, model));
                }
                return builder.ToImmutable();
            },
                       nextPage: (info, lastPage) =>
            {
                if (lastPage.Count != DiscordConfig.MaxMessagesPerBatch)
                {
                    return false;
                }
                if (dir == Direction.Before)
                {
                    info.Position = lastPage.Min(x => x.Id);
                }
                else
                {
                    info.Position = lastPage.Max(x => x.Id);
                }
                return true;
            },
                       start: fromMessageId,
                       count: limit
                       ));
        }
Ejemplo n.º 47
0
 public static Task <IUserMessage> SendConfirmAsync(this IMessageChannel ch, string title, string text, string url = null, string footer = null)
 => ch.SendMessageAsync("", embed: new EmbedBuilder().WithOkColor().WithDescription(text)
                        .WithTitle(title).WithUrl(url).WithFooter(efb => efb.WithText(footer)));
        /// <summary>
        /// Sends typing feedback.
        /// </summary>
        public async Task StartTyping(IMessageChannel channel)
        {
            await channel.TriggerTypingAsync();

            await Task.Delay(TimeSpan.FromSeconds(0.5));
        }
Ejemplo n.º 49
0
 /// <summary>
 /// Create a new wire tap with <em>no</em> <see cref="IMessageSelector"/>
 /// </summary>
 /// <param name="channel">the <see cref="IMessageChannel"/> to which intercepted messages will be sent</param>
 public WireTap(IMessageChannel channel)
     : this(channel, null)
 {
 }
        protected override IMessageHandler CreateProducerMessageHandler(IProducerDestination destination, IProducerOptions producerProperties, IMessageChannel errorChannel)
        {
            if (producerProperties.HeaderMode == HeaderMode.EmbeddedHeaders)
            {
                throw new InvalidOperationException("The RabbitMQ binder does not support embedded headers since RabbitMQ supports headers natively");
            }

            var extendedProperties = BindingsOptions.GetRabbitProducerOptions(producerProperties.BindingName);
            var prefix             = extendedProperties.Prefix;
            var exchangeName       = destination.Name;
            var destinationName    = string.IsNullOrEmpty(prefix) ? exchangeName : exchangeName[prefix.Length..];
Ejemplo n.º 51
0
        public static async Task RunTrades(HtmlDocument feed, string leagueId, IMessageChannel channel)
        {
            var   feedString   = "//*[@id='newsfeed_page']/ol/li[1]";
            var   tempDateTime = "";
            var   systemIcon   = "";
            Embed embed        = null;

            if (leagueId == "73")
            {
                systemIcon =
                    "https://cdn.discordapp.com/attachments/689119430021873737/711030693743820800/220px-PlayStation_logo.svg.jpg";
            }
            else if (leagueId == "53")
            {
                systemIcon =
                    "https://cdn.discordapp.com/attachments/689119430021873737/711030386775293962/120px-Xbox_one_logo.svg.jpg";
            }

            var nodes = feed.DocumentNode.SelectNodes(feedString);

            foreach (var item in nodes)
            {
                tempDateTime = item.SelectSingleNode("//*[@id='newsfeed_page']/ol/li[1]/div/abbr").InnerText;
                var line    = item.SelectSingleNode("//*[@id='newsfeed_page']/ol/li[1]/div/h3").InnerText;
                var newLine = "";
                if (line.Contains("The "))
                {
                    newLine = line.Replace("The ", string.Empty);
                }
                if (line.Contains("the "))
                {
                    newLine = newLine.Replace("the ", string.Empty);
                }

                var splits = newLine.Split(new[] { "have traded", " to ", "for" }, StringSplitOptions.None);


                var splitStr = newLine.Split(new[] { "to " }, StringSplitOptions.None);
                splitStr[1] = splitStr[1].Replace("  ", " ");
                var tradeIcon = item.SelectSingleNode("//*[@id='newsfeed_page']/ol/li[1]/a[2]/img")
                                .Attributes["src"].Value;
                var lastNews = DateTime.Parse(tempDateTime);

                if (!NewsWriter.SaveTrade(lastNews, splitStr[0], splitStr[1], leagueId))
                {
                    break;
                }
                try
                {
                    using var newsDb = new LiteDatabase(@"Filename=Database/LGFA.db;connection=shared");
                    var news   = newsDb.GetCollection <LeagueNews.News>("Trades");
                    var result = news.Find(x => x.Date.Equals(lastNews));
                    foreach (var headline in result)
                    {
                        var builder = new EmbedBuilder()
                                      .WithColor(new Color(0xFF0019))
                                      .WithTimestamp(lastNews)
                                      .WithFooter(footer =>
                        {
                            footer
                            .WithText("leaguegaming.com")
                            .WithIconUrl("https://www.leaguegaming.com/images/logo/logonew.png");
                        })
                                      .WithThumbnailUrl("https://www.leaguegaming.com/images/feed/trade.png")
                                      .WithAuthor(author =>
                        {
                            author
                            .WithName("LGFA Breaking News")
                            .WithIconUrl(systemIcon);
                        })
                                      .WithDescription("**New Trade**")
                                      .AddField($"**To {splits[0].Trim()}**", $"{splits[3].Trim()}", true)
                                      .AddField($"**To {splits[2].Trim()}**", $"{splits[1].Trim()}", true);

                        embed = builder.Build();
                    }

                    await channel.SendMessageAsync(null, embed : embed).ConfigureAwait(false);
                }
                catch (Exception e)
                {
                    Log.Logger.Error($"{e}");
                    throw;
                }
            }
        }
Ejemplo n.º 52
0
        public static async Task <IReadOnlyCollection <RestMessage> > GetPinnedMessagesAsync(IMessageChannel channel, BaseDiscordClient client,
                                                                                             RequestOptions options)
        {
            var guildId = (channel as IGuildChannel)?.GuildId;
            var guild   = guildId != null?await(client as IDiscordClient).GetGuildAsync(guildId.Value, CacheMode.CacheOnly).ConfigureAwait(false) : null;

            var models = await client.ApiClient.GetPinsAsync(channel.Id, options).ConfigureAwait(false);

            var builder = ImmutableArray.CreateBuilder <RestMessage>();

            foreach (var model in models)
            {
                var author = GetAuthor(client, guild, model.Author.Value, model.WebhookId.ToNullable());
                builder.Add(RestMessage.Create(client, channel, author, model));
            }
            return(builder.ToImmutable());
        }
 /// <summary>
 /// set the error channel
 /// </summary>
 /// <param name="errorChannel">the erroe channel</param>
 /// <returns>the current instance</returns>
 public MessageBuilder SetErrorChannel(IMessageChannel errorChannel)
 {
     return SetHeader(MessageHeaders.ERROR_CHANNEL, errorChannel);
 }
 /// <summary>
 /// Creates a subscription for the specified channel.
 /// </summary>
 /// <param name="channel">The channel that will be subscribed to.</param>
 /// <param name="subscriber">The object that will receive events from the channel.</param>
 /// <param name="injector">The injector that will be called to trigger the event handler.</param>
 /// <param name="deliveryThread">The thread on which the subscription will be delivered.</param>
 /// <returns>The newly-created subscription.</returns>
 public IMessageSubscription Create(IMessageChannel channel, object subscriber, MethodInjector injector,
                                    DeliveryThread deliveryThread)
 {
     return(new StandardMessageSubscription(channel, subscriber, injector, deliveryThread));
 }
Ejemplo n.º 55
0
        public static async Task<IUserMessage> ReplyAsync(SocketUser user, IMessageChannel channel, string text, bool mentionUser)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(text))
                {
                    if (channel as IPrivateChannel != null || !mentionUser)
                        return await channel.SendMessageAsync(text);
                    else
                        return await channel.SendMessageAsync($"{user.Mention}: {text}");
                }
            }
            catch (Exception e)
            {
                LogError("Couldn't send message.", e.Message);
            }

            return null;
        }
Ejemplo n.º 56
0
 public IDisposable TriggerTyping(IMessageChannel channel)
 {
     return(channel.EnterTypingState());
 }
 protected bool SendReplyMessage(IMessage replyMessage, IMessageChannel replyChannel)
 {
     if(logger.IsDebugEnabled) {
         logger.Debug("handler '" + this + "' sending reply Message: " + replyMessage);
     }
     return _channelTemplate.Send(replyMessage, replyChannel);
 }
Ejemplo n.º 58
0
        public async Task <bool> TryBlockLate(DiscordSocketClient client, IUserMessage msg, IGuild guild, IMessageChannel channel, IUser user, string moduleName, string commandName)
        {
            await Task.Yield();

            if (guild == null)
            {
                return(false);
            }
            else
            {
                var resetCommand = commandName == "resetperms";

                PermissionCache pc = GetCache(guild.Id);
                if (!resetCommand && !pc.Permissions.CheckPermissions(msg, commandName, moduleName, out int index))
                {
                    if (pc.Verbose)
                    {
                        try { await channel.SendErrorAsync(_strings.GetText("trigger", guild.Id, "Permissions".ToLowerInvariant(), index + 1, Format.Bold(pc.Permissions[index].GetCommand(_cmd.GetPrefix(guild), (SocketGuild)guild)))).ConfigureAwait(false); } catch { }
                    }
                    return(true);
                }


                if (moduleName == nameof(Permissions))
                {
                    var guildUser = user as IGuildUser;
                    if (guildUser == null)
                    {
                        return(true);
                    }

                    if (guildUser.GuildPermissions.Administrator)
                    {
                        return(false);
                    }

                    var permRole = pc.PermRole;
                    ulong.TryParse(permRole, out var rid);
                    string returnMsg;
                    IRole  role;
                    if (string.IsNullOrWhiteSpace(permRole) || (role = guild.GetRole(rid)) == null)
                    {
                        returnMsg = $"You need Admin permissions in order to use permission commands.";
                        if (pc.Verbose)
                        {
                            try { await channel.SendErrorAsync(returnMsg).ConfigureAwait(false); } catch { }
                        }

                        return(true);
                    }
                    else if (!guildUser.RoleIds.Contains(rid))
                    {
                        returnMsg = $"You need the {Format.Bold(role.Name)} role in order to use permission commands.";
                        if (pc.Verbose)
                        {
                            try { await channel.SendErrorAsync(returnMsg).ConfigureAwait(false); } catch { }
                        }

                        return(true);
                    }
                    return(false);
                }
            }

            return(false);
        }
 public override IMessage PreSend(IMessage message, IMessageChannel channel)
 {
     _sendCount.IncrementValueAndReturn();
     return message;
 }
Ejemplo n.º 60
0
 public Channel(IMessageChannel channel)
 {
     DiscordChannel = channel;
 }