public static void HandleMessage(GroupUpdate a, VkApi api) { if (a.Type == GroupUpdateType.MessageNew) { var currentString = a.Message.Body; //Console.WriteLine(currentString + "\r\n"); Program.Logger.WriteMessage(currentString, "svc"); var strOut = WeatherAP.GetWeather(currentString); var idUser = a.Message.UserId; var randomNum = new Random(); api.Messages.Send(new MessagesSendParams() { RandomId = randomNum.Next(0, int.MaxValue), UserId = idUser, Message = strOut }); api.Messages.Send(new MessagesSendParams() { RandomId = randomNum.Next(0, int.MaxValue) >> 1, // короче эта хрень нужна чтобы randomId с верхним не повторялся UserId = idUser, Message = "Введите название города" }); } }
public async Task TestUpdateGroup() { var groupNew = new GroupNew().SetDefaults(); groupNew.Name = "api.test.group." + new Guid().ToString(); groupNew.Description = "This is a test group for the API tests."; var createGroupRequest = new CreateGroupRequest(groupNew); var createGroupResponse = await SkyManager.ApiClient.ExecuteRequestAsync(createGroupRequest); var groupId = createGroupResponse.Content.Id; var groupUpdate = new GroupUpdate().SetDefaults(); groupUpdate.Description = "Updated decsription"; groupUpdate.Name = "Update group name"; Assert.NotNull(groupUpdate.ToJson()); Assert.NotNull(groupUpdate.ToString()); var updateGroupRequest = new UpdateGroupRequest(groupUpdate, groupId); var updateGroupResponse = await SkyManager.ApiClient.ExecuteRequestAsync(updateGroupRequest); var deleteGroupRequest = new DeleteGroupRequest(groupId); await SkyManager.ApiClient.ExecuteRequestAsync(deleteGroupRequest); }
private void OnNewGroupUpdate_(GroupUpdate groupUpdate) { var item = this.table[groupUpdate.GroupId]; if (groupUpdate.FieldName == "Pad") { int padNumber = item.PadNumber; string format = item.Format; int newPad = (int)groupUpdate.Value; string labelFormat = (string)groupUpdate.Value; foreach (var kv in item.Table) { this.chart.Pads[padNumber].Remove(kv.Value.Item2); this.EnsurePadExists(newPad, labelFormat); this.chart.Pads[newPad].Add(kv.Value.Item2); } item.PadNumber = newPad; item.Format = labelFormat; } if (groupUpdate.FieldName == "Color") { Color color = (Color)groupUpdate.Value; foreach (var kv in item.Table) { if (kv.Value.Item1 is TimeSeriesViewer) { (kv.Value.Item1 as TimeSeriesViewer).Color = color; } } this.chart.UpdatePads(); } }
/// <inheritdoc /> public void HandleRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken) { var user = _userManager.GetUserById(session.UserId); if (user.SyncPlayAccess == SyncPlayAccess.None) { _logger.LogWarning("HandleRequest: {0} does not have access to SyncPlay.", session.Id); var error = new GroupUpdate <string>() { Type = GroupUpdateType.JoinGroupDenied }; _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None); return; } lock (_groupsLock) { _sessionToGroupMap.TryGetValue(session.Id, out var group); if (group == null) { _logger.LogWarning("HandleRequest: {0} does not belong to any group.", session.Id); var error = new GroupUpdate <string>() { Type = GroupUpdateType.NotInGroup }; _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None); return; } group.HandleRequest(session, request, cancellationToken); } }
public async Task <IActionResult> Edit(int id, [Bind("GroupUpdateId,Updatemsg,Status,GroupGoalId,UpdateDate")] GroupUpdate groupUpdate) { if (id != groupUpdate.GroupUpdateId) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(groupUpdate); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!GroupUpdateExists(groupUpdate.GroupUpdateId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(groupUpdate)); }
/// <inheritdoc /> public void JoinGroup(SessionInfo session, Guid groupId, JoinGroupRequest request, CancellationToken cancellationToken) { var user = _userManager.GetUserById(session.UserId); if (user.SyncPlayAccess == SyncPlayAccess.None) { _logger.LogWarning("JoinGroup: {0} does not have access to SyncPlay.", session.Id); var error = new GroupUpdate <string>() { Type = GroupUpdateType.JoinGroupDenied }; _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None); return; } lock (_groupsLock) { ISyncPlayController group; _groups.TryGetValue(groupId, out group); if (group == null) { _logger.LogWarning("JoinGroup: {0} tried to join group {0} that does not exist.", session.Id, groupId); var error = new GroupUpdate <string>() { Type = GroupUpdateType.GroupDoesNotExist }; _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None); return; } if (!HasAccessToItem(user, group.GetPlayingItemId())) { _logger.LogWarning("JoinGroup: {0} does not have access to {1}.", session.Id, group.GetPlayingItemId()); var error = new GroupUpdate <string>() { GroupId = group.GetGroupId().ToString(), Type = GroupUpdateType.LibraryAccessDenied }; _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None); return; } if (IsSessionInGroup(session)) { if (GetSessionGroup(session).Equals(groupId)) { return; } LeaveGroup(session, cancellationToken); } group.SessionJoin(session, request, cancellationToken); } }
private async Task DispatchUpdates(GroupUpdate updateObj) { if (MessageIsCommand(updateObj)) { switch (updateObj.Message.Text) { case "Начать": _logger.LogInformation($"Получено комманда: НАЧАТЬ"); await _sendMessageService.SendMessageWithoutKeyboard(updateObj, "Добро пожаловать."); break; default: _logger.LogInformation($"Непонятная комманда"); await _sendMessageService.SendMessageWithoutKeyboard(updateObj, "Я не понимаю, что от меня хотят((("); break; } } else if (decimal.TryParse(updateObj.Message.Text, out var result)) { _logger.LogInformation($"Получено значение: {result}"); await _sendMessageService.SendMessageWithoutKeyboard(updateObj, $"Получено значение: {result}"); } else { _logger.LogInformation($"Вообще непойми что пришло"); await _sendMessageService.SendMessageWithoutKeyboard(updateObj, "Я не понимаю, что от меня хотят((("); } }
/// <inheritdoc /> public void NewGroup(SessionInfo session, CancellationToken cancellationToken) { var user = _userManager.GetUserById(session.UserId); if (user.SyncPlayAccess != SyncPlayAccess.CreateAndJoinGroups) { _logger.LogWarning("NewGroup: {0} does not have permission to create groups.", session.Id); var error = new GroupUpdate <string> { Type = GroupUpdateType.CreateGroupDenied }; _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None); return; } lock (_groupsLock) { if (IsSessionInGroup(session)) { LeaveGroup(session, cancellationToken); } var group = new SyncPlayController(_sessionManager, this); _groups[group.GetGroupId()] = group; group.CreateGroup(session, cancellationToken); } }
public static void SendMessage(GroupUpdate message, string text) { Task.Run(() => { if (message.MessageNew.Message.Attachments.Count != 0) { var attachments = new List <MediaAttachment> { message.MessageNew.Message.Attachments[0].Instance }; text = message.MessageNew.Message.Attachments[0].Instance.AccessKey + " | " + message.MessageNew.Message.Attachments[0].Instance.Id + " | " + message.MessageNew.Message.Attachments[0].Instance.OwnerId; GroupApi.Messages.Send(new MessagesSendParams { RandomId = new Random().Next(999999), UserId = message.MessageNew.Message.FromId, Message = text, Attachments = attachments }); } else { GroupApi.Messages.Send(new MessagesSendParams { RandomId = new Random().Next(999999), UserId = message.MessageNew.Message.FromId, Message = text, }); } }); }
public void OnEvent(GroupUpdate update) { if (update.Message != null) { OnNewMessage(update.Message); } }
/// <inheritdoc /> public void LeaveGroup(SessionInfo session, CancellationToken cancellationToken) { // TODO: determine what happens to users that are in a group and get their permissions revoked lock (_groupsLock) { _sessionToGroupMap.TryGetValue(session.Id, out var group); if (group == null) { _logger.LogWarning("LeaveGroup: {0} does not belong to any group.", session.Id); var error = new GroupUpdate <string>() { Type = GroupUpdateType.NotInGroup }; _sessionManager.SendSyncPlayGroupUpdate(session.Id, error, CancellationToken.None); return; } group.SessionLeave(session, cancellationToken); if (group.IsGroupEmpty()) { _logger.LogInformation("LeaveGroup: removing empty group {0}.", group.GetGroupId()); _groups.Remove(group.GetGroupId(), out _); } } }
public async Task <IActionResult> PutGroupUpdate(int id, GroupUpdate groupUpdate) { if (id != groupUpdate.GroupUpdateId) { return(BadRequest()); } _context.Entry(groupUpdate).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!GroupUpdateExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <ActionResult <GroupUpdate> > PostGroupUpdate(GroupUpdate groupUpdate) { _context.GroupUpdates.Add(groupUpdate); await _context.SaveChangesAsync(); return(CreatedAtAction("GetGroupUpdate", new { id = groupUpdate.GroupUpdateId }, groupUpdate)); }
public async Task Handle(GroupUpdate upd) { if (upd.Secret != _options.SecretKey) { _logger.Warning("Пришло событие с неправильным секретным ключом ({0})", upd.Secret); return; } _logger.Debug("Обработка события с типом {0}", upd.Type); if (upd.Type == GroupUpdateType.MessageNew) { if (upd.MessageNew.Message.Action?.Type == MessageAction.ChatInviteUser) { await _sender.Send(upd.MessageNew.Message.PeerId.Value, "Здравствуйте!\n" + "Подробности по настройке бота для бесед здесь: vk.com/@japanese.goblin-conversations"); return; } var msg = _mapper.Map <Message>(upd.MessageNew.Message); ExtractUserIdFromConversation(msg); await MessageNew(msg); } else if (upd.Type == GroupUpdateType.MessageEvent) { await MessageEvent(upd.MessageEvent); } else if (upd.Type == GroupUpdateType.GroupLeave) { await GroupLeave(upd.GroupLeave); } else if (upd.Type == GroupUpdateType.GroupJoin) { await GroupJoin(upd.GroupJoin); } else { _logger.Fatal("Обработчик для события {0} не найден", upd.Type); throw new ArgumentOutOfRangeException(nameof(upd.Type), "Отсутствует обработчик события"); } _logger.Information("Обработка события {0} завершена", upd.Type); void ExtractUserIdFromConversation(Message msg) { if (msg.ChatId == msg.UserId) { return; } var regEx = Regex.Match(msg.Text, @"\[club\d+\|.*\] (.*)"); if (regEx.Groups.Count > 1) { msg.Text = regEx.Groups[1].Value.Trim(); } } }
public override bool Execute(GroupUpdate update, IVkApi bot) { if (update.Type == GroupUpdateType.MessageNew && update.MessageNew != null && update.MessageNew.Message != null && update.MessageNew.Message.Attachments.Any()) { var attachment = update.MessageNew.Message.Attachments.First(); if (attachment.Type == typeof(Document)) { var document = attachment.Instance as Document; using (var client = new WebClient()) { string salt = Guid.NewGuid().ToString().Substring(0, 8); string path = Path.Combine(Folders.Docs(), $"{update.MessageNew.Message.FromId} {salt} Check.{document.Ext}"); client.DownloadFile(document.Uri, path); update.ReplyMessageNew(bot, AppData.Strings.DocumentSaved); context.PathUserId.Add(path, (long)update.MessageNew.Message.FromId); antiplagiatService.EnqueueDocument(path); } return(true); } } return(false); }
public static void ReplyMessageNew(this GroupUpdate update, IVkApi vkApi, string message) { vkApi.Messages.Send(new MessagesSendParams { RandomId = random.Next(), UserId = update.MessageNew.Message.FromId, Message = message }); }
public static void RePostImage(GroupUpdate message) {/* * _api.Wall.Post(new WallPostParams * { * OwnerId = Tokens.GroupId, * FromGroup = true, * Message = "" * });*/ }
public void PutGroupIdTest() { // TODO: add unit test for the method 'PutGroupId' string groupId = null; // TODO: replace null with proper value GroupUpdate body = null; // TODO: replace null with proper value var response = instance.PutGroupId(groupId, body); Assert.IsInstanceOf <Group> (response, "response is Group"); }
public async Task <IActionResult> Create([Bind("GroupUpdateId,Updatemsg,Status,GroupGoalId,UpdateDate")] GroupUpdate groupUpdate) { if (ModelState.IsValid) { _context.Add(groupUpdate); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(groupUpdate)); }
public static void SendHelp(GroupUpdate message) { Task.Run(() => { GroupApi.Messages.Send(new MessagesSendParams { RandomId = new Random().Next(999999), UserId = message.MessageNew.Message.FromId, Message = Localization.HelpText }); }); }
public override Task Handle(GroupUpdate evt, Action next = null) { var evtBody = typeof(GroupUpdate).GetProperty(eventFieldName).GetValue(evt); if (IsMatch(evt)) { return(handlerFn((T)(dynamic)Convert.ChangeType(evtBody, evtBody.GetType()), next)); } next?.Invoke(); return(Task.CompletedTask); }
public void CreateUpdate(GroupUpdate update, string userId) { groupUpdateRepository.Add(update); SaveUpdate(); var groupUpdateUser = new GroupUpdateUser { UserId = userId, GroupUpdateId = update.GroupUpdateId }; groupUpdateUserRepository.Add(groupUpdateUser); SaveUpdate(); }
public async Task SendMessageWithCategoryKeyboard(GroupUpdate updateObj, string text) { var msg = new MessagesSendParams { UserId = updateObj.Message.UserId, Message = text, PeerId = updateObj.Message.PeerId, RandomId = new DateTime().Millisecond, Keyboard = _keyboards.GetCategoryKeyboard() }; await _vkApi.Messages.SendAsync(msg); }
/// <summary> /// Sends a GroupUpdate message to the interested sessions. /// </summary> /// <param name="from">The current session.</param> /// <param name="type">The filtering type.</param> /// <param name="message">The message to send.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <value>The task.</value> private Task SendGroupUpdate <T>(SessionInfo from, BroadcastType type, GroupUpdate <T> message, CancellationToken cancellationToken) { IEnumerable <Task> GetTasks() { foreach (var session in FilterSessions(from, type)) { yield return(_sessionManager.SendSyncPlayGroupUpdate(session.Id, message, cancellationToken)); } } return(Task.WhenAll(GetTasks())); }
/// <summary> /// The packet process /// </summary> /// <param name="packet"></param> public override void Process(Packet packet) { var d = DataMap.Deserialize(packet.Payload); UserId uid = d["contact-id"]; GroupId gid = d["group-id"]; int type = int.Parse(d["type"]); var user = uid.GetUser(Bot); if (user == null) { user = new User(uid); Bot.Information.UserCache.Add(uid, user); } if (type == 0) { if (d.ContainsKey("contacts")) { d = DataMap.Deserialize(d["contacts"]); } if (d.ContainsKey(uid.ToString())) { d = DataMap.Deserialize(d[uid.ToString()]); } if (d.ContainsKey("nickname")) { user.Nickname = d["nickname"].GetDisplayString(); } if (d.ContainsKey("status")) { user.Status = d["status"].GetDisplayString(); } if (d.ContainsKey("rep")) { user.Reputation = int.Parse(d["rep"]); } if (d.ContainsKey("rep_lvl")) { user.RepLevel = double.Parse(d["rep_lvl"]); } } var g = new GroupUpdate { Group = gid, User = uid, IsJoin = type == 0 }; Bot.On.Trigger("gu", g); }
public static void RePost(GroupUpdate message) { Task.Run(() => { _api.Wall.Post(new WallPostParams { OwnerId = -188415343, FromGroup = true, Message = message.MessageNew.Message.Text.Remove(0, 5) + " (C) [id" + message.MessageNew.Message.FromId + "|Цитата]" }); }); }
/// <inheritdoc /> public void LeaveGroup(SessionInfo session, LeaveGroupRequest request, CancellationToken cancellationToken) { if (session == null) { throw new InvalidOperationException("Session is null!"); } if (request == null) { throw new InvalidOperationException("Request is null!"); } // Locking required to access list of groups. lock (_groupsLock) { if (_sessionToGroupMap.TryGetValue(session.Id, out var group)) { // Group lock required to let other requests end first. lock (group) { if (_sessionToGroupMap.TryRemove(session.Id, out var tempGroup)) { if (!tempGroup.GroupId.Equals(group.GroupId)) { throw new InvalidOperationException("Session was in wrong group!"); } } else { throw new InvalidOperationException("Could not remove session from group!"); } UpdateSessionsCounter(session.UserId, -1); group.SessionLeave(session, request, cancellationToken); if (group.IsGroupEmpty()) { _logger.LogInformation("Group {GroupId} is empty, removing it.", group.GroupId); _groups.Remove(group.GroupId, out _); } } } else { _logger.LogWarning("Session {SessionId} does not belong to any group.", session.Id); var error = new GroupUpdate <string>(Guid.Empty, GroupUpdateType.NotInGroup, string.Empty); _sessionManager.SendSyncPlayGroupUpdate(session, error, CancellationToken.None); return; } } }
public override Task HandleAsync(VkRequest req, CancellationToken ct) { var response = GroupUpdate.FromJson(req.Response); if (response.Type == GroupUpdateType.Confirmation) { return(SendStringAsync(_vkOptions.ConfirmationCode, cancellation: ct)); } BackgroundJob.Enqueue(() => _handler.Handle(response)); return(SendStringAsync("ok", cancellation: ct)); }
public async Task Handle(GroupUpdate longpollEvent, IVkApi api = null) { await events.ExecuteAsync(longpollEvent); if (longpollEvent.MessageNew == null) { return; } var message = new MessageContext(longpollEvent); message.Api = api; await commands.ExecuteAsync(message); }
public async Task Cannot_update_non_existing_group() { var request = new GroupUpdate.Request { Id = 1, Name = "S3 - Timo", }; var useCase = new GroupUpdate(new ProgressContext(Fixture.ContextOptions)); var result = await useCase.HandleAsync(request); result.IsFailure.Should().BeTrue(); result.Error.Should().Contain("exist"); }
private void OnNewGroupUpdate_(GroupUpdate groupUpdate) { var item = this.table[groupUpdate.GroupId]; if (groupUpdate.FieldName == "Pad") { int padNumber = item.PadNumber; string format = item.Format; int newPad = (int)groupUpdate.Value; string labelFormat = (string)groupUpdate.Value; foreach (var kv in item.Table) { this.chart.Pads[padNumber].Remove(kv.Value.Item2); this.EnsurePadExists(newPad, labelFormat); this.chart.Pads[newPad].Add(kv.Value.Item2); } item.PadNumber = newPad; item.Format = labelFormat; } if (groupUpdate.FieldName == "Color") { Color color = (Color)groupUpdate.Value; foreach (var kv in item.Table) { if (kv.Value.Item1 is TimeSeriesViewer) (kv.Value.Item1 as TimeSeriesViewer).Color = color; } this.chart.UpdatePads(); } }
public void OnNewGroupUpdate(GroupUpdate groupUpdate) { #if GTK Gtk.Application.Invoke((sender, e) => OnNewGroupUpdate_(groupUpdate)); #else if (InvokeRequired) Invoke((Action)delegate { OnNewGroupUpdate(groupUpdate); }); else OnNewGroupUpdate_(groupUpdate); #endif }
private void updateGroup(GroupUpdate response) { PlayerListView.Items.Clear(); //lets just pretend this never happend mkay? Invite.Visibility = Visibility.Hidden; InvitedPlayers.Visibility = Visibility.Hidden; QueueButton.Visibility = Visibility.Hidden; ReadyButton.Visibility = Visibility.Visible; teambuilderSlotId = response.slotId; teambuilderGroupId = response.groupId; //TODO: find how matched team lobby chatroom name is generated //if(connectedToChat) // LeaveChat(); //ConnectToChat(); foreach (PlayerSlot slot in response.slots) populateSlot(slot); }
public void OnNewGroupUpdate(GroupUpdate groupUpdate) { // no-op }