public void UpdateChatListing(TelegramChat telegramChat) { Chat dbChat = _chatBotRepository.GetChatByTelegramChatId(telegramChat.Id); dbChat.MembersCount = _telegramRepository.GetChatMemberCount(telegramChat.Id) .Value; dbChat.Name = telegramChat.Title; dbChat.LastMessageReceived = DateTime.Now; _chatBotRepository.SaveChanges(); }
private static void SetControllerData(TController controller, Update update, MessageCommand command, TContext context, TelegramChat chat, ITelegramBotData botData) { controller.Update = update; controller.MessageCommand = command; controller.TelegramContext = context; controller.TelegramChat = chat; controller.BotData = botData; }
public async Task <bool> CreateChatSettings(ModelContainer db, TelegramChat chat, AlertType type) { db.TelegramChatSettings.Add(new TelegramChatSetting() { TelegramChatId = chat.Id, Type = type }); await db.SaveChangesAsync().ConfigureAwait(false); return(true); }
public void AddUpdateChatListing(TelegramChat telegramChat) { if (_chatBotRepository.CheckIfChatExistsByTelegramChatId(telegramChat.Id)) { UpdateChatListing(telegramChat); } else { AddChatListing(telegramChat); } }
public async Task UpdateChat(TelegramChat chat) { var entity = await _context.TelegramChats.FirstOrDefaultAsync(x => x.Id == chat.Id); if (entity == null) { throw new Exception("Чат не найден"); } entity.LastCommandType = chat.LastCommandType; _context.Update(entity); await _context.SaveChangesAsync(); }
public async Task <bool> SetCarType(ModelContainer db, TelegramChat chat, AlertType alertType, CarType carType) { var telegramChatSetting = await db.TelegramChatSettings .FirstOrDefaultAsync(x => x.TelegramChatId == chat.Id && x.Type == alertType) .ConfigureAwait(false); if (telegramChatSetting == null) { return(false); } telegramChatSetting.CarType = carType; db.SaveChanges(); return(true); }
private void AddChatListing(TelegramChat telegramChat) { DateTime now = DateTime.Now; int memberCount = _telegramRepository.GetChatMemberCount(telegramChat.Id).Value; var chatToAdd = new Chat { ChatId = telegramChat.Id, Name = telegramChat.Title, MembersCount = memberCount, LastMessageReceived = now, }; _chatBotRepository.AddChat(chatToAdd); _chatBotRepository.SaveChanges(); }
public void ShouldRunAddingChatToDatabase() { chatRepositoryMock.Setup(r => r.AddChat(It.IsAny <Chat>())).Returns(true); chatRepositoryMock.Setup(r => r.CheckIfChatExistsByTelegramChatId(It.IsAny <int>())).Returns(false); telegramRepositoryMock.Setup(r => r.GetChatMemberCount(It.IsAny <int>())) .Returns(3); var testChat = new TelegramChat { Id = 329, Title = "TestChat", }; messageParserServices.AddUpdateChatListing(testChat); }
public async Task <object> SendMessage(string bodId, string chatId, string text) { var request = new HttpRequestMessage(HttpMethod.Post, $"{_baseurl}bot{StringCipher.decodingWinDataProtection(bodId)}/sendMessage"); var body = new TelegramChat() { ChatId = StringCipher.decodingWinDataProtection(chatId), Text = text }; request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); if (response.IsSuccessStatusCode) { using var responseStream = await response.Content.ReadAsStreamAsync(); return(await JsonSerializer.DeserializeAsync <object>(responseStream)); } return(null); }
private bool GetCommandTextMessage(TelegramChat telegramChat, BirthdayNotificationScheduleBotCommandTypes?commandType, Update update, out string text) { text = null; switch (commandType.Value) { case BirthdayNotificationScheduleBotCommandTypes.SetNotificationDelayInDays: text = $"За сколько дней нужно сообщать о дне рождения?{Environment.NewLine}Требуется указать цифру{Environment.NewLine}"; if (telegramChat.BirthdayNotificationSchedules != null && telegramChat.BirthdayNotificationSchedules.Any()) { text += $"Текущее значение: {telegramChat.BirthdayNotificationSchedules.First().DaysCountBeforeNotificaiton}"; } return(true); case BirthdayNotificationScheduleBotCommandTypes.ImportBirthdays: text = $@"Укажите список дней рождения в следующем формате:{Environment.NewLine}имя фамилия dd.MM{Environment.NewLine}имя фамилия dd.MM{Environment.NewLine}имя фамилия dd.MM{Environment.NewLine}и т.д."; return(true); default: text = "Неизвестный тип команды"; return(false); } }
/// <inheritdoc /> public override bool IsValid(Update update, TelegramChat user, MessageCommand command, ITelegramBotData botData) { return(update.Message != null && _type.Contains(update.Message.Chat.Type)); }
public override bool IsValid(Update update, TelegramChat user, MessageCommand command, ITelegramBotData botData) { return(command == null || !command.IsCommand()); }
public override bool IsValid(Update update, TelegramChat chat, MessageCommand command, ITelegramBotData botData) { return(_type.Any(x => x == update.Type)); }
public async Task CreateGroup(TelegramContact serviceContact, TelegramContact clientContact, string title) { try { string prefix = "Covario - "; if (!title.StartsWith(prefix)) { title = prefix + title; } TelegramChat tc = _chats.Values.FirstOrDefault(c => c.Title == title); if (tc == null) { var basicGroup = await _client.ExecuteAsync(new TdApi.CreateNewBasicGroupChat() { Title = title, UserIds = new[] { _serviceUserId, serviceContact.UserId, clientContact.UserId } }); tc = new TelegramChat() { ChatId = basicGroup.Id, BasicGroupId = (basicGroup.Type as TdApi.ChatType.ChatTypeBasicGroup)?.BasicGroupId ?? 0, Title = title, Members = new[] { serviceContact, clientContact } }; _chats.TryAdd(tc.ChatId, tc); } await _client.ExecuteAsync(new TdApi.SetChatPermissions() { ChatId = tc.ChatId, Permissions = new TdApi.ChatPermissions { CanSendMessages = true, CanSendMediaMessages = false, CanSendPolls = false, CanSendOtherMessages = false, CanAddWebPagePreviews = true, CanChangeInfo = false, CanInviteUsers = false, CanPinMessages = false } }); await _client.ExecuteAsync(new TdApi.SetChatDescription() { ChatId = tc.ChatId, Description = "Covar.io Client Support Chat" }); await _client.ExecuteAsync(new TdApi.SetChatDescription() { ChatId = tc.ChatId, Description = "Covar.io Client Support Chat" }); var parts = new[] { @"All communication in this conversation is logged by our systems for auditing and compliance mandates, as per our Terms of Service: ", @"https://messenger.covar.io/terms", @". Communicating here acknowledges your acceptance of these terms." }; var tosMessage = await _client.ExecuteAsync(new TdApi.SendMessage() { ChatId = tc.ChatId, Options = new TdApi.SendMessageOptions { FromBackground = false, DisableNotification = true }, InputMessageContent = new TdApi.InputMessageContent.InputMessageText() { Text = new TdApi.FormattedText() { Text = string.Join("", parts), Entities = new TdApi.TextEntity[] { new TdApi.TextEntity() { Type = new TdApi.TextEntityType.TextEntityTypeUrl(), Offset = parts[0].Length, Length = parts[1].Length }, } }, } }); _pendingPins.Add(tosMessage.Id); } catch (Exception ex) { throw new TelegramCreateGroupException(ex.Message, ex); } }
public static async Task Execute(Message message, TelegramBotClient client) { var chatId = message.Chat.Id; bool userExists = false; Regex regex = new Regex(@"^\/start\s(.*)"); Match match = regex.Match(message.Text); if (match.Success) { string eventKey = match.Groups[1].Value; using (TelegramChatContext db = new TelegramChatContext()) { try { var events = db.Events; var _event = await events.FirstOrDefaultAsync(x => x.InviteKey == eventKey); TelegramChat user = new TelegramChat { ChatId = chatId, FirstName = message.Chat.FirstName, LastName = message.Chat.LastName, UserName = message.Chat.Username, }; foreach (var eventUser in _event.Participants) { if (eventUser.ChatId == user.ChatId) { userExists = true; break; } } if (!userExists) { _event.Participants.Add(user); await db.SaveChangesAsync(); await client.SendTextMessageAsync(chatId, $"Congratulations! You are registered to event!"); //await client.SendTextMessageAsync(chatId, $"Now you can add wishlist using next syntax: /addWish Type your wish here"); //await client.SendTextMessageAsync(chatId, $"To clear wish list use command /clearWishList"); //await client.SendTextMessageAsync(chatId, $"To show wish list use command /showWishList"); await client.SendTextMessageAsync(chatId, $"When the event organizer closes the registration, " + $"I will send you a message with a random participant to whom you will give a gift."); } else { await client.SendTextMessageAsync(chatId, "You don't need to register to this event again."); } } catch (Exception e) { Debug.WriteLine($"{nameof(UserStart)}:{e.Message}"); } } } else { await client.SendTextMessageAsync(chatId, "Ooops, something wrong with your link or such event is not exists."); } }
/// <inheritdoc /> public override bool IsValid(Update update, TelegramChat user, MessageCommand command, ITelegramBotData botData) { return(_endpoint.Contains(botData?.Endpoint)); }
public override async Task ExecuteAsync(Message message, TelegramBotClient client) { var chatId = message.Chat.Id; bool userExists = false; TelegramChat user = new TelegramChat { ChatId = chatId, FirstName = message.Chat.FirstName, LastName = message.Chat.LastName, UserName = message.Chat.Username }; using (TelegramChatContext db = new TelegramChatContext()) { await client.SendTextMessageAsync(chatId, "Created DB context"); try { /*db.Database.Connection.Open(); * await client.SendTextMessageAsync(chatId, "Opened DB connection");*/ var users = db.Users; await client.SendTextMessageAsync(chatId, "Get users"); foreach (var dbUser in users) { await client.SendTextMessageAsync(chatId, $"Check for user:{dbUser}"); if (user.ChatId == dbUser.ChatId) { await client.SendTextMessageAsync(chatId, "Your data already saved in db."); userExists = true; break; } } if (!userExists) { await client.SendTextMessageAsync(chatId, "Try to add user to DB"); db.Users.Add(user); await client.SendTextMessageAsync(chatId, "User has been added, trying to save changes"); await db.SaveChangesAsync(); await client.SendTextMessageAsync(chatId, $"ChatId={user.ChatId} and userName={user.FirstName} added to db."); } else { await client.SendTextMessageAsync(chatId, "User already exists in DB"); } } catch (Exception e) { Debug.WriteLine(e.Message); } } await client.SendTextMessageAsync(chatId, "Disposed"); }
public override bool IsValid(Update update, TelegramChat chat, MessageCommand command, ITelegramBotData botData) { return(command.Parameters.Count == _qnt); }
private async Task DispatchAsync(IServiceScope scope, Update update) { TController controller = scope.ServiceProvider.GetRequiredService <TController>(); TContext context = scope.ServiceProvider.GetRequiredService <TContext>(); _logger.LogInformation($"Received update - ID: {update.Id}"); TelegramChat chat = null; if (update.Type == UpdateType.Message) { var newChat = update.Message.Chat; chat = await TelegramChat.GetAsync(context, newChat.Id); if (chat != null) { if (newChat.Username != null && chat.Username == newChat.Username) { chat.Username = newChat.Username; } if (newChat.Title != null && chat.Title == newChat.Title) { chat.Title = newChat.Title; } if (newChat.Description != null && chat.Description == newChat.Description) { chat.Description = newChat.Description; } if (newChat.InviteLink != null && chat.InviteLink == newChat.InviteLink) { chat.InviteLink = newChat.InviteLink; } if (newChat.LastName != null && chat.LastName == newChat.LastName) { chat.LastName = newChat.LastName; } if (newChat.StickerSetName != null && chat.StickerSetName == newChat.StickerSetName) { chat.StickerSetName = newChat.StickerSetName; } if (newChat.FirstName != null && chat.FirstName == newChat.FirstName) { chat.FirstName = newChat.FirstName; } if (newChat.CanSetStickerSet != null && chat.CanSetStickerSet == newChat.CanSetStickerSet) { chat.CanSetStickerSet = newChat.CanSetStickerSet; } if (chat.AllMembersAreAdministrators == newChat.AllMembersAreAdministrators) { chat.AllMembersAreAdministrators = newChat.AllMembersAreAdministrators; } } else { chat = new TelegramChat(update.Message.Chat); await context.AddAsync(chat); } } MessageCommand command; if (update.Type == UpdateType.Message) { command = new MessageCommand(update.Message); if (command.Target != null && _botData.Username != null && command.Target != _botData.Username) { _logger.LogDebug($"Command's target is @{command.Target} - Ignoring command"); return; } } else { command = new MessageCommand(); } SetControllerData(controller, update, command, context, chat, _botData); context.SaveChanges(); _logger.LogTrace($"Command: {JsonConvert.SerializeObject(command, Formatting.Indented)}"); _logger.LogTrace($"Chat: {JsonConvert.SerializeObject(chat, Formatting.Indented)}"); var firstMethod = _methods.FirstOrDefault(m => ((MemberInfo)m).GetCustomAttributes() .Where(att => att is DispatcherFilterAttribute) .All(attr => ((DispatcherFilterAttribute)attr).IsValid(update, chat, command, _botData))); if (firstMethod != null) { if (firstMethod.GetCustomAttribute <AsyncStateMachineAttribute>() != null) { _logger.LogInformation($"Calling async method: {firstMethod.Name}"); await(Task) firstMethod.Invoke(controller, null); } else { _logger.LogInformation($"Calling sync method: {firstMethod.Name}"); firstMethod.Invoke(controller, null); } } else if (_noMethodsMethod != null) { if (_noMethodsMethod.GetCustomAttribute <AsyncStateMachineAttribute>() != null) { _logger.LogInformation("No valid method found to manage current request. Calling the async NoMethod: " + _noMethodsMethod.Name); await(Task) _noMethodsMethod.Invoke(controller, null); } else { _logger.LogInformation("No valid method found to manage current request. Calling the sync NoMethod: " + _noMethodsMethod.Name); _noMethodsMethod.Invoke(controller, null); } } else { _logger.LogInformation("No valid method found to manage current request."); } _logger.LogTrace("End of dispatching"); }
private void NewChat(TelegramChat chat) { SyncLog(chat.ChatId).RunSynchronously(); }
/// <summary> /// Called when searching for eligible handler method, return true if the method is eligible /// </summary> /// <param name="update">Update of he current request</param> /// <param name="chat">Current chat</param> /// <param name="command">MessageCommand generated from current Update</param> /// <param name="botData">Data of the bot in use</param> /// <returns>If true, the mehod is eligible for the currrent update. If false, the method is discarded</returns> public abstract bool IsValid(Update update, TelegramChat chat, MessageCommand command, ITelegramBotData botData);
public bool CheckIfChatExists(TelegramChat chat) { return(CheckIfChatExistsByTelegramChatId(chat.Id)); }
private async Task <TelegramChat> GetChat(long chatId, TdApi.Chat chat = null) { if (_chats.TryGetValue(chatId, out var tg)) { return(tg); } AutoResetEvent wait; if (_loadingChats.TryGetValue(chatId, out wait)) { wait.WaitOne(); return(_chats[chatId]); } wait = new AutoResetEvent(false); if (!_loadingChats.TryAdd(chatId, wait)) { wait.WaitOne(); return(_chats[chatId]); } int tryIndex = 0; while (tryIndex < 5) { tryIndex++; const string tdLibThrottlePrefix = "Too Many Requests: retry after"; try { if (chat == null) { chat = await _client.ExecuteAsync(new TdApi.GetChat { ChatId = chatId }); } switch (chat.Type) { case TdApi.ChatType.ChatTypeBasicGroup existingBasicGroup: { if (chat.LastReadInboxMessageId != 0) { _logger.LogInformation("Known last read for chat {chat} {messageId}", chat.Id, chat.LastReadInboxMessageId); } tg = new TelegramChat() { ChatId = chatId, BasicGroupId = existingBasicGroup.BasicGroupId, Title = chat.Title }; var basicGroupFullInfo = await _client.ExecuteAsync(new TdApi.GetBasicGroupFullInfo() { BasicGroupId = existingBasicGroup.BasicGroupId }); var users = basicGroupFullInfo.Members.Where(m => m.UserId != _serviceUserId).Select(m => m.UserId); var members = new List <TelegramContact>(); foreach (var user in users) { var contact = await GetTelegramContact(user); members.Add(contact); } tg.Members = members.ToArray(); break; } case TdApi.ChatType.ChatTypePrivate privateChat: { tg = new TelegramChat() { ChatId = chatId, Title = chat.Title }; var members = new List <TelegramContact>(); var contact = await GetTelegramContact(privateChat.UserId); members.Add(contact); tg.Members = members.ToArray(); break; } case TdApi.ChatType.ChatTypeSupergroup superGroup: { tg = new TelegramChat() { ChatId = chatId, Title = chat.Title }; var group = await _client.ExecuteAsync(new TdApi.GetSupergroup() { SupergroupId = superGroup.SupergroupId }); try { var groupMember = await _client.ExecuteAsync(new TdApi.GetSupergroupMembers() { SupergroupId = superGroup.SupergroupId, Limit = 1000, Offset = 0 }); var users = groupMember.Members.Where(m => m.UserId != _serviceUserId).Select(m => m.UserId); var members = new List <TelegramContact>(); foreach (var user in users) { var contact = await GetTelegramContact(user); members.Add(contact); } tg.Members = members.ToArray(); } catch (Exception ex) { _logger.LogInformation("Error loading supergroup members {group}, {message}", tg.Title, ex.Message); } break; } default: { tg = new TelegramChat() { ChatId = chatId, BasicGroupId = 0, Title = chat.Title, }; break; } } _chats.TryAdd(tg.ChatId, tg); _loadingChats.Remove(chatId, out wait); break; } catch (Exception ex) when(ex.Message.StartsWith(tdLibThrottlePrefix)) { var howLong = int.Parse(ex.Message.Substring(tdLibThrottlePrefix.Length)); _logger.LogWarning("TDLib throttling in progress waiting {howLong} seconds", howLong); Thread.Sleep((howLong + 5) * 1000); } } wait.Set(); _chatFeed.OnNext(tg); return(tg); }
/// <inheritdoc /> public override bool IsValid(Update update, TelegramChat user, MessageCommand command, ITelegramBotData botData) { return(user != null && _state.Contains(user.State)); }
/// <inheritdoc /> public override bool IsValid(Update update, TelegramChat user, MessageCommand command, ITelegramBotData botData) { return(_command.Contains(command?.Command)); }