public void PityTheFool(Message message, IMessageClient client, string phrase) { var pity = GetRandomItem(new List<string> { "I Pity The Fool", "Pity The Fool", "Thou Shalt pity the fool", "Pity thee", "Be pitiful for those", "cast pity towards those" }); if (string.IsNullOrEmpty(phrase)) { phrase = GetRandomItem(new List<string> { "who breaks the build", "who doesn't test before check-in", "who is last to the dessert tray", "who doesn't login to campfire", "who isn't nBot" }); } MemeGen(message, client, "1646", "5353", pity, phrase); }
public CommentRequestGitlabProcessor(ICommentRequestMessageFormatter formatter, IMessageClient messageClient, ILogger <CommentRequestGitlabProcessor> logger) : base(messageClient, logger) { this.formatter = formatter; }
public async Task SendSalesReportEmailAsync_OrdersIsEmpty_ShouldNotSendSalesReport() { // Arrange Mock <IOrderService> mockOrderService = new Mock <IOrderService>(); mockOrderService .Setup(os => os.Get(It.IsAny <OrderSearchCriteria>())) .Returns(new Collection <Order>()); Mock <IUserService> mockUserService = new Mock <IUserService>(); Mock <ISalesReportBuilder> mockSalesReportBuilder = new Mock <ISalesReportBuilder>(); IOrderService orderService = mockOrderService.Object; IUserService userService = mockUserService.Object; ISalesReportBuilder salesReportBuilder = mockSalesReportBuilder.Object; Mock <IMessageClient> mockMessageClient = new Mock <IMessageClient>(); mockMessageClient .Setup(mc => mc.SendAsync(It.IsAny <TestApp.Mocking.User>(), It.IsAny <TestApp.Mocking.User>(), It.IsAny <SalesReport>())).Verifiable(); IMessageClient messageClient = mockMessageClient.Object; ReportService reportService = new ReportService(orderService, userService, salesReportBuilder, messageClient); // Act await reportService.SendSalesReportEmailAsync(DateTime.Now); // Assert mockMessageClient.Verify(mc => mc.SendAsync(It.IsAny <Mocking.User>(), It.IsAny <Mocking.User>(), It.IsAny <SalesReport>()), Times.Never); }
public override void Push(IMessage message, IMessageClient messageClient) { if (IsClosed) { BaseRtmpHandler.Push(this, message, messageClient); } }
public override void Push(IMessage message, IMessageClient messageClient) { if (base.State != RtmpState.Disconnected) { BaseRtmpHandler.Push(this, message, messageClient); } }
public void DoAchievement(Message message, IMessageClient client, string caption) { string encodedCaption = UrlEncode(caption); string url = string.Format("http://achievement-unlocked.heroku.com/xbox/{0}.png", encodedCaption); client.ReplyTo(message, url); }
internal static void Push(RtmpConnection connection, IMessage message, IMessageClient messageClient) { if (connection != null) { object response = message; if (message is BinaryMessage) { BinaryMessage binaryMessage = message as BinaryMessage; binaryMessage.Update(messageClient); byte[] binaryContent = binaryMessage.body as byte[]; //byte[] destClientBinaryId = messageClient.GetBinaryId(); //Array.Copy(destClientBinaryId, 0, binaryContent, binaryMessage.PatternPosition, destClientBinaryId.Length); RawBinary result = new RawBinary(binaryContent); response = result; } else { //This should be a clone of the original message message.SetHeader(MessageBase.DestinationClientIdHeader, messageClient.ClientId); message.clientId = messageClient.ClientId; } RtmpChannel channel = connection.GetChannel(3); FlexInvoke reply = new FlexInvoke(); Call call = new Call("receive", new object[] { response }); reply.ServiceCall = call; //reply.Cmd = "receive"; //reply.Response = response; reply.InvokeId = connection.InvokeId; channel.Write(reply); } }
public WebsocketTopicClient(Uri uri, DelegateConnected connected, CompletionQueue completion_queue) { message_client = new WebsocketMessageClient( uri, WebsocketTopicServer.protocol, connected, MessageWaiting, completion_queue); topic_client = new TopicClient(message_client); this.completion_queue = completion_queue; }
public MessageController( IMessageClient messageClient, ICacheManager <string> cacheManager) { _messageClient = messageClient; _cacheManager = cacheManager; }
public override async Task HandleMessage(IMessageClient client, TMessage message) { foreach (IMessageHandler <TMessage> handler in Handlers) { await handler.HandleMessage(client, message); } }
public void SwansonMe(Message message, IMessageClient client) { var httpclient = GetJsonServiceClient("http://ronsays.tumblr.com"); var html = httpclient.Get<string>("/random"); var linkMatch = Regex.Match(html, "<div class=\"stat-media-wrapper\"><a href=\"http://ronsays.tumblr.com/image/(\\d+)\"><img\\ssrc=\"(.*)\"\\salt"); client.ReplyTo(message, linkMatch.Groups[2].Value); }
public void XkcdMe(Message message, IMessageClient client, string number) { IRestClient jsonClient = GetJsonServiceClient("http://xkcd.com"); var result = new RootObject(); string jsonResponse; try { jsonResponse = (string.IsNullOrEmpty(number) || number == "xkcd me") ? jsonClient.Get<string>("/info.0.json") : jsonClient.Get<string>(string.Format("/{0}/info.0.json", number)); } catch (Exception) { jsonResponse = jsonClient.Get<string>("/1/info.0.json"); } result.Value = JsonObject.Parse(jsonResponse); string imgUrl = result.Value.Child("img").Replace("\\", ""); string altText = result.Value.Child("alt"); //Reply with two messages back to back client.ReplyTo(message, imgUrl); client.ReplyTo(message, altText); }
private object[] BuildParameters(MethodInfo method, Message message, IMessageClient client, Dictionary<string, string> inputParameters) { ParameterInfo[] methodParameters = method.GetParameters(); var result = new object[methodParameters.Count()]; for (int parameterIndex = 0; parameterIndex < result.Length; parameterIndex++) { ParameterInfo parameter = methodParameters[parameterIndex]; if (parameter.ParameterType.IsAssignableFrom(typeof(Message))) { result[parameterIndex] = message; } else if (parameter.ParameterType == typeof(IMessageClient)) { result[parameterIndex] = client; } else if (parameter.ParameterType == typeof(IBrain)) { result[parameterIndex] = _brain; } else if (inputParameters.ContainsKey(parameter.Name)) { result[parameterIndex] = Convert.ChangeType(inputParameters[parameter.Name], parameter.ParameterType); } } return result; }
public void SearchStackOverflow(Message message, IMessageClient client, string query) { try { var authCode = Robot.GetSetting<string>("StackappsApiKey"); if (string.IsNullOrEmpty(authCode)) throw new ArgumentException("Please supply the StackappsApiKey"); var result = GetGZipedJsonServiceClient(string.Format("http://api.stackoverflow.com/1.1/search?intitle={0}&key={1}", Uri.EscapeDataString(query), Uri.EscapeDataString(authCode))) .Get<SearchResult>("/"); if (result.Questions.Any()) { client.ReplyTo(message, string.Format("Top 5 Search results for: {0}", query)); foreach (Question question in result.Questions.OrderByDescending(q => q.answer_count).Take(5)) { client.ReplyTo(message, string.Format("{0} responses to: {1} {2}", question.answer_count, question.title, "http://stackoverflow.com" + question.question_answers_url)); } } else { client.ReplyTo(message, string.Format("No results found for {0}", query)); } } catch (Exception ex) { EventLog.WriteEntry("NBot-Sosearch", ex.ToString()); client.ReplyTo(message, "Error in searching Stack Overflow."); } }
public void RollDice(Message message, IMessageClient client, string sides) { var dice = new Random(DateTime.Now.Millisecond); //default to typical 6 side die int numSides = 6; if (string.IsNullOrEmpty(sides) || int.TryParse(sides, out numSides)) { if (numSides <= 0) { //negative number var result = "I'm sorry, i will not roll a " + numSides.ToString() + " sided dice without adult supervision. That would tear a hole in the universe..."; client.ReplyTo(message, result); Thread.Sleep(5000); client.ReplyTo(message, "No... you don't qualify as an adult"); } else { //good number var result = "You rolled a " + dice.Next(1, numSides + 1) + " on a " + numSides.ToString() + " sided dice"; client.ReplyTo(message, result); } } else { //non number, or too large a number var result = "I can't roll a " + sides + " I am but a meager .net bot"; client.ReplyTo(message, result); } }
internal static void Push(RtmpConnection connection, IMessage message, IMessageClient messageClient) { if (connection != null) { object obj2 = message; if (message is BinaryMessage) { BinaryMessage message2 = message as BinaryMessage; message2.Update(messageClient); byte[] body = message2.body as byte[]; RawBinary binary = new RawBinary(body); obj2 = binary; } else { message.SetHeader("DSDstClientId", messageClient.ClientId); message.clientId = messageClient.ClientId; } RtmpChannel channel = connection.GetChannel(3); FlexInvoke invoke = new FlexInvoke { Cmd = "receive", InvokeId = connection.InvokeId, Response = obj2 }; channel.Write(invoke); } }
/// <summary> /// Pushes a message to a remote client. /// </summary> /// <param name="message">Message to push.</param> /// <param name="messageClient">The MessageClient subscription that this message targets.</param> public override void Push(IMessage message, IMessageClient messageClient) { if (_connection is RtmpConnection) { (_connection as RtmpConnection).Push(message, messageClient); } }
public void RoomAnnounce(Message message, IMessageClient client, string announcement) { IEntity user = client.GetUser(message.UserId); string response = string.Format("{0} says \" {1} \"", user.Name, announcement); client.Broadcast(response); }
public IncomingMessageMessageClient(IMessageClient messageClient, IOptionsMonitor <IncomingMessageHandlerConfig> settings) { Settings = settings.CurrentValue; _messageClient = messageClient; _messageClient.MessageReceived += OnMessageReceived; }
internal _TimeoutContext(IMessageClient messageClient) { _session = messageClient.Session; _client = messageClient.Client; if (log.IsDebugEnabled) log.Debug(__Res.GetString(__Res.Context_Initialized, "[not available]", _client != null ? _client.Id : "[not available]", _session != null ? _session.Id : "[not available]")); }
public void GetAscii(Message message, IMessageClient client, string query) { IRestClient httpClient = GetJsonServiceClient("http://asciime.heroku.com/"); var result = httpClient.Get <string>("/generate_ascii?s={0}".FormatWith(query)); client.ReplyTo(message, result); }
private static object[] BuildParameters(MethodInfo method, Message message, IMessageClient client, Dictionary <string, string> inputParameters) { var methodParameters = method.GetParameters(); var result = new object[methodParameters.Count()]; for (var parameterIndex = 0; parameterIndex < result.Length; parameterIndex++) { var parameter = methodParameters[parameterIndex]; if (parameter.ParameterType.IsAssignableFrom(typeof(Message))) { result[parameterIndex] = message; } else if (parameter.ParameterType == typeof(IMessageClient)) { result[parameterIndex] = client; } else if (parameter.ParameterType == typeof(IBrain)) { result[parameterIndex] = Brain; } else { string value; if (inputParameters.TryGetValue(parameter.Name, out value)) { result[parameterIndex] = Convert.ChangeType(value, parameter.ParameterType); } } } return(result); }
public override void Push(IMessage message, IMessageClient messageClient) { if (this.IsActive) { BaseRtmpHandler.Push(this, message, messageClient); } }
public void PityTheFool(Message message, IMessageClient client, string phrase) { string pity = GetRandomItem(new List <string> { "I Pity The Fool", "Pity The Fool", "Thou Shalt pity the fool", "Pity thee", "Be pitiful for those", "cast pity towards those" }); if (string.IsNullOrEmpty(phrase)) { phrase = GetRandomItem(new List <string> { "who breaks the build", "who doesn't test before check-in", "who is last to the dessert tray", "who doesn't login to campfire", "who isn't nBot" }); } MemeGen(message, client, "1646", "5353", pity, phrase); }
public void Recieve(Message message, IMessageClient client) { IRestClient httpClient = GetJsonServiceClient("http://facepalm.org"); var response = httpClient.Get<HttpWebResponse>("/img.php"); var imageUrl = response.ResponseUri.AbsoluteUri; client.ReplyTo(message, imageUrl); }
public void XkcdMe(Message message, IMessageClient client, string number) { IRestClient jsonClient = GetJsonServiceClient("http://xkcd.com"); var result = new RootObject(); string jsonResponse; try { jsonResponse = (string.IsNullOrEmpty(number) || number == "xkcd me") ? jsonClient.Get <string>("/info.0.json") : jsonClient.Get <string>(string.Format("/{0}/info.0.json", number)); } catch (Exception) { jsonResponse = jsonClient.Get <string>("/1/info.0.json"); } result.Value = JsonObject.Parse(jsonResponse); string imgUrl = result.Value.Child("img").Replace("\\", ""); string altText = result.Value.Child("alt"); //Reply with two messages back to back client.ReplyTo(message, imgUrl); client.ReplyTo(message, altText); }
public void RegisterMessageClient(IMessageClient messageClient) { if (!this.MessageClients.Contains(messageClient)) { this.MessageClients.Add(messageClient); } }
/// <summary> /// This method supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> /// <param name="messageClient"></param> public void UnregisterMessageClient(IMessageClient messageClient) { //This operation was possibly initiated by this client //if (messageClient.IsDisconnecting) // return; if (this.MessageClients != null && this.MessageClients.Contains(messageClient)) { this.MessageClients.Remove(messageClient); if (_endpointPushHandlers != null) { IEndpointPushHandler handler = _endpointPushHandlers[messageClient.EndpointId] as IEndpointPushHandler; if (handler != null) { handler.UnregisterMessageClient(messageClient); } } /* * if (this.MessageClients.Count == 0) * { * Disconnect(); * } */ } }
public void RollDice(Message message, IMessageClient client, string sides) { var dice = new Random(DateTime.Now.Millisecond); //default to typical 6 side die int numSides = 6; if (string.IsNullOrEmpty(sides) || int.TryParse(sides, out numSides)) { if (numSides <= 0) { //negative number var result = "I'm sorry, I will not roll a " + numSides.ToString() + " sided dice without adult supervision. That would tear a hole in the universe..."; client.ReplyTo(message, result); Thread.Sleep(5000); client.ReplyTo(message, "No... you don't qualify as an adult"); } else { //good number var result = "You rolled a " + dice.Next(1, numSides + 1) + " on a " + numSides.ToString() + " sided dice"; client.ReplyTo(message, result); } } else { //non number, or too large a number var result = "I can't roll a " + sides + " I am but a meager .net bot"; client.ReplyTo(message, result); } }
public PlayerApplicationService(string name) { client_ = new MessageClient(); name_ = name; client_.MessageReceivedEvent += OnMessageReceived; }
public static void UseInterServiceCommunication(this IServiceCollection services, InterServiceCommunicationSettings settings) { IMessageClient messageClient = null; MessageClientSettings producerSettings = null; switch (settings.Type) { case Enumerations.InterServiceCommunicationType.RabbitMQ: messageClient = new RabbitMQMessageClient(); break; case Enumerations.InterServiceCommunicationType.Kafka: default: messageClient = new KafkaMessageClient(); producerSettings = new KafkaMessageSettings() { BrokerList = settings.Address, Topics = settings.Receivers, ServiceName = settings.ServiceName }; break; } messageClient.InitializeMessageClient(producerSettings); services.AddSingleton(messageClient); }
static void Main(string[] args) { IMessageClient client = IoC.Resolve <IMessageClient>(); client.ExecuteJob(); Console.ReadKey(); }
public void Hear(Message message, IMessageClient client, IBrain brain) { string time = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(); string result = time + " in the room " + message.RoomId; var userName = client.GetUser(message.UserId).Name; brain.SetValue(LastSpokeKey(userName), result); }
private void SetMessageClient(IMessageClient client) { MessageClient = client; client.Received += (sender, e) => OnReceiveInternal(e.Message); client.Connected += (sender, e) => OnConnected(); client.ConnectFailed += (sender, e) => OnConnectFailed(e.Exception); client.Disconnected += (sender, e) => OnDisconnected(); }
public HubMessageClient(IHubContext <NotifyHub, ITypedHubClient> hubContext, IMessageClient messageClient, IOptionsMonitor <SHubConfig> settings) { _hubContext = hubContext; Settings = settings.CurrentValue; _messageClient = messageClient; _messageClient.MessageReceived += OnMessageReceived; }
public void SwansonMe(Message message, IMessageClient client) { var httpclient = GetJsonServiceClient("http://ronsays.tumblr.com"); var html = httpclient.Get <string>("/random"); var linkMatch = Regex.Match(html, "<div class=\"stat-media-wrapper\"><a href=\"http://ronsays.tumblr.com/image/(\\d+)\"><img\\ssrc=\"(.*)\"\\salt"); client.ReplyTo(message, linkMatch.Groups[2].Value); }
public TcpTopicClientSAE(IPEndPoint ipEndPoint, DelegateConnected connected, CompletionQueue completion_queue) { message_client = new TcpMessageClientSAE( ipEndPoint, connected, MessageWaiting, completion_queue); topic_client = new TopicClient(message_client); this.completion_queue = completion_queue; }
/// <summary> /// Disassociates a MessageClient (subscription) from a Session. /// </summary> /// <param name="messageClient">The MessageClient to disassociate from the session.</param> internal void UnregisterMessageClient(IMessageClient messageClient) { if (_messageClients != null) { _messageClients.Remove(messageClient); messageClient.RemoveMessageClientDestroyedListener(this); } }
/// <summary> /// Opens a connection to the server and start receiving messages. /// </summary> /// <param name="oauth">Your password should be an OAuth token authorized through our API with the chat:read scope (to read messages) and the chat:edit scope (to send messages)</param> /// <param name="nick">Your nickname must be your Twitch username (login name) in lowercase</param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task ConnectAsync(string oauth, string nickId, CancellationToken cancellationToken) { _twitchMessageClient = new WebSocketPubSubClient(); _twitchMessageClient.MessageReceived += OnRawMessageReceived; _twitchMessageClient.ConnectionClosed += OnConnectionClosed; return(_twitchMessageClient.ConnectAsync(oauth, nickId.ToLower(), cancellationToken)); }
/// <summary> /// Send json payload /// </summary> /// <param name="client"></param> /// <param name="payload"></param> /// <param name="contentType"></param> /// <param name="partitionKey"></param> public static Task SendAsync(this IMessageClient client, JToken payload, string contentType, string partitionKey) { return(client.SendAsync(payload, new Dictionary <string, string> { [CommonProperties.kContentType] = contentType }, partitionKey)); }
public ShowsService(IShowsRepository showsRepository, IRestClient client, IMessageClient messageClient) { _showsRepository = showsRepository; _client = client; _messageClient = messageClient; }
public void DoExcuseMe(Message mesage, IMessageClient client) { IEntity user = client.GetUser(mesage.UserId); IRestClient httpClient = GetJsonServiceClient("http://developerexcuses.com/"); var result = httpClient.Get<string>("/"); Match matches = Regex.Match(result, "<a href=\"/\" .*>(.*)</a>"); string excuse = matches.Groups[1].Value; client.ReplyTo(mesage, string.Format("{0}, your excuse is \"{1}\".", user.Name, excuse)); }
internal void Update(IMessageClient messageClient) { byte[] binaryContent = this.body as byte[]; byte[] destClientBinaryId = messageClient.GetBinaryId(); int patternPosition = Scan(binaryContent, _lastPattern, 0); while (patternPosition != -1) { Array.Copy(destClientBinaryId, 0, binaryContent, patternPosition, destClientBinaryId.Length); patternPosition = Scan(binaryContent, _lastPattern, 0); } _lastPattern = destClientBinaryId; }
/// <summary> /// Initializes a new instance of the <see cref="PersonAlertClientRepository"/> class. /// </summary> /// <param name="applicationSetting">The application setting.</param> /// <exception cref="System.ArgumentNullException">applicationSetting;Parameter cannot be null </exception> public PersonAlertClientRepository(IApplicationSetting applicationSetting) { if (applicationSetting != null) { this.alertClient = DIContainer.Instance.Resolve<IAlertClient>(new ResolverOverride[] { new ParameterOverride(BaseAddressParameterName, applicationSetting.PersonNotificationServiceBaseAddress) }); this.alertTypeClient = DIContainer.Instance.Resolve<IAlertTypeClient>(new ResolverOverride[] { new ParameterOverride(BaseAddressParameterName, applicationSetting.PersonNotificationServiceBaseAddress) }); this.messageClient = DIContainer.Instance.Resolve<IMessageClient>(new ResolverOverride[] { new ParameterOverride(BaseAddressParameterName, applicationSetting.PersonNotificationServiceBaseAddress) }); this.personMessageClient = DIContainer.Instance.Resolve<IPersonMessageClient>(new ResolverOverride[] { new ParameterOverride(BaseAddressParameterName, applicationSetting.PersonNotificationServiceBaseAddress) }); this.personAlertClient = DIContainer.Instance.Resolve<IPersonAlertsClient>(new ResolverOverride[] { new ParameterOverride(BaseAddressParameterName, applicationSetting.PersonNotificationServiceBaseAddress) }); } }
public async void HandleTemperatureRequest(IMessageClient client, TemperatureRequest request) { await Context; var temp = await service.GetTemperature(request.City); client.Send(new TemperatureResponse { City = request.City, Temperature = temp, }); }
/// <summary> /// Registers a message client (implemented by the /// child controls). /// </summary> /// <param name="client">The client which gets messages /// by the master.</param> public void RegisterClient(IMessageClient client) { //store reference this.clients.Add(client); //add client to dropdown if (!this.IsPostBack) { ListItem item = new ListItem(client.ClientName, this.clients.IndexOf(client).ToString()); this.ClientList.Items.Add(item); } }
public void FindMemeGenerator(Message message, IMessageClient client, string url) { IRestClient httpClient = GetJsonServiceClient( string.Format( "http://version1.api.memegenerator.net/Generator_Select_ByUrlNameOrGeneratorID?generatorID=&urlName={0}", url)); var response = httpClient.Get<string>(""); client.ReplyTo(message, response); }
/// <summary> /// Initializes a new instance of the <see cref="MainPage"/> class. /// </summary> public MainPage() { this.InitializeComponent(); this.messageClient = new MessageClient( 4530, new JsonMessageSerializer(new List<Type>() { typeof(WeatherMessage), typeof(SubscribeMessage) })); this.messageClient.MessageRecieved += this.messageClient_MessageRecieved; this.messageClient.ConnectCompleted += (s, args) => { this.Dispatcher.BeginInvoke(() => { this.SubscribeButton.IsEnabled = true; }); }; this.messageClient.ConnectAsync(); }
public void PingMe(Message message, IMessageClient client, string location) { var startInfo = new ProcessStartInfo(); startInfo.FileName = "ping.exe"; startInfo.Arguments = location; startInfo.RedirectStandardOutput = true; startInfo.UseShellExecute = false; var process = Process.Start(startInfo); process.WaitForExit(5000); var result = process.StandardOutput.ReadToEnd(); client.ReplyTo(message, result); }
public void PageUser(Message message, IMessageClient client, string name) { string regex = string.Format("(.*)({0})(.*)", name); List<IEntity> rooms = client.GetAllRooms().ToList(); string sentFrom = client.GetUser(message.UserId).Name; IEntity requestedRoom = rooms.Single(r => r.Id == message.RoomId); const string pageMessage = "Paging {0} ... Paging {0} ... Your presence is requested by {1} in the \"{2}\" room."; const string failureMessage = "Sorry, nobody by the name {0} could be found."; const string userIsInYourRoom = "Lulz!! {0} is in your room."; var roomsUserIsIn = new List<IEntity>(); bool hasMatch = false; foreach (IEntity room in rooms) { IEnumerable<IEntity> usersInRoom = client.GetUsersInRoom(room.Id); foreach (IEntity user in usersInRoom) { if (Regex.IsMatch(user.Name, regex, RegexOptions.IgnoreCase)) { roomsUserIsIn.Add(room); string response = string.Format(pageMessage, user.Name, sentFrom, requestedRoom.Name); if (room.Id == requestedRoom.Id) response = string.Format(userIsInYourRoom, user.Name); client.Send(response, room.Id); hasMatch = true; } } } if (!hasMatch) { string response = string.Format(failureMessage, name); client.Send(response, requestedRoom.Id); } else { var responseMessage = new StringBuilder(); responseMessage.AppendLine(string.Format("{0}, \"{1}\" was found in the following rooms:", sentFrom, name)); foreach (IEntity room in roomsUserIsIn) { responseMessage.AppendLine(string.Format("- {0}", room.Name)); } client.Send(responseMessage.ToString(), requestedRoom.Id); } }
public void DoIsItDownForYou(Message message, IMessageClient client, string site) { try { IRestClient jsonClient = GetJsonServiceClient(DownForMeSite); var result = jsonClient.Get<string>(site); Match match = Regex.Match(result, SiteIsUpReges); client.ReplyTo(message, match.Success ? string.Format("It's just you. {0} is up for me.", site) : string.Format("Oh no {0} is down for me too!!!!! *PANIC*", site)); } catch (Exception e) { client.Send("Oh no I am Down!!! *UberPanic*", message.RoomId); } }
private void MemeGen(Message message, IMessageClient client, string generatorId, string imageId, string text0, string text1) { IRestClient httpClient = GetJsonServiceClient( string.Format( "http://version1.api.memegenerator.net/Instance_Create?username=test&password=test&languageCode=en&generatorID={0}&imageID={3}&text0={1}&text1={2}", generatorId, text0, text1, imageId)); var response = httpClient.Get<MemeGeneratorResponse>(""); client.ReplyTo(message, response.Result.InstanceImageUrl); }
private void Translate(Message message, IMessageClient client, string textToTranslate) { try { var result = GetJsonServiceClient(string.Format("http://isithackday.com/arrpi.php?text={0}&format=json", UrlEncode(textToTranslate))) .Get<string>("pirate"); client.ReplyTo(message, result); } catch (Exception ex) { EventLog.WriteEntry("NBot-PirateTranslator", ex.ToString()); client.ReplyTo(message, "PirateTranslator crashed!"); } }
public void PluginHelp(Message message, IMessageClient client, string plugin) { string ouputMessage = string.Format("Commands for {0}:", plugin); IEnumerable<List<Command>> helpInformationCommands = _helpInformation.Where(hi => hi.Plugin.ToLower() == plugin.ToLower()).Select(hi => hi.Commands); foreach (var commands in _helpInformation.Where(hi => hi.Plugin.ToLower() == plugin.ToLower()).Select(hi => hi.Commands)) { foreach (Command command in commands) { ouputMessage += "\n" + string.Format("Command Syntax: {0}\nDescription: {1}\nExample: {2}\n", command.Syntax, command.Description, command.Example); } } client.ReplyTo(message, helpInformationCommands.Any() ? ouputMessage : string.Format("Plugin '{0}' not found.", plugin)); }
public void ChuckNorrisJoke(Message message, IMessageClient client, string name) { IRestClient jsonClient = GetJsonServiceClient("http://api.icndb.com/jokes/"); RootObject result; if (!string.IsNullOrEmpty(name)) { result = jsonClient.Get<string>("random?firstName=" + name + "&lastName=").FromJson<RootObject>(); } else { result = jsonClient.Get<string>("random").FromJson<RootObject>(); } client.ReplyTo(message, result.Value.Joke); }
private void MemeGen(Message message, IMessageClient client, string urlString, string text1, string text2) { try { var result = GetJsonServiceClient(string.Format("http://memecaptain.com/g?u={0}&t1={1}&t2={2}", UrlEncode(urlString), UrlEncode(text1), UrlEncode(text2))) .Get<string>(""); string startOfUrl = result.Substring(result.IndexOf("http")); string imgUrl = startOfUrl.Substring(0, startOfUrl.IndexOf("\"")); client.ReplyTo(message, imgUrl); } catch (Exception ex) { EventLog.WriteEntry("NBot-MemeCaptain", ex.ToString()); client.ReplyTo(message, "MemGenerator crashed!"); } }
public void HandlePowerShellCommand(Message message, IMessageClient client, string command, string parameters) { if (_commands.ContainsKey(command)) { var filePath = _commands[command]; var scriptParameters = string.IsNullOrEmpty(parameters) ? string.Empty : parameters; var startInfo = new ProcessStartInfo(); startInfo.FileName = "powershell.exe"; startInfo.Arguments = string.Format("-File {0} {1}", filePath, scriptParameters); startInfo.RedirectStandardOutput = true; startInfo.UseShellExecute = false; var process = Process.Start(startInfo); process.WaitForExit(5000); var result = process.StandardOutput.ReadToEnd(); client.ReplyTo(message, result); } }
public void HandleStatusChange(Message message, IMessageClient client, IBrain brain, string query) { string time = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(); //string result = "wut"; var userName = client.GetUser(message.UserId).Name; if (query.ToLower().StartsWith("in")) { //result = "i recognize " + message.UserId + " checked in at " + time; brain.SetValue(LastCheckinKey(userName), time); brain.RemoveKey(LastCheckoutKey(userName)); } else if (query.ToLower().StartsWith("out")) { //result = "i recognize " + message.UserId + " checked out at " + time; brain.SetValue(LastCheckoutKey(userName), time); brain.RemoveKey(LastCheckinKey(userName)); } //client.ReplyTo(message, result); }
public void HandleGetStatus(Message message, IMessageClient client, IBrain brain, string userName) { string result = userName; bool needsAnd = false; bool neverSeenThem = true; if (brain.ContainsKey(LastCheckinKey(userName))) { result += " last checked in at " + brain.GetValue(LastCheckinKey(userName)); neverSeenThem = false; needsAnd = true; } if (brain.ContainsKey(LastCheckoutKey(userName))) { if (needsAnd) { result += ","; } result += " last checked out at " + brain.GetValue(LastCheckoutKey(userName)); neverSeenThem = false; needsAnd = true; } if (brain.ContainsKey(LastSpokeKey(userName))) { if (needsAnd) { result += " and"; } result += " last spoke at " + brain.GetValue(LastSpokeKey(userName)); neverSeenThem = false; } if (neverSeenThem) { result = "I ain't never seen " + userName + " come round these parts"; } client.ReplyTo(message, result); }