private async Task <bool> IsValidSender(Message message) { if (message.Chat.Type == ChatType.Private) { var isAllowed = false; if (!usersCache.TryGetValue(message.From.Id, out isAllowed)) { try { var member = await _botClient.GetChatMemberAsync(_config.TestChatId, message.From.Id); isAllowed = member != null && member.Status != ChatMemberStatus.Left; usersCache.TryAdd(message.From.Id, isAllowed); } catch { _logger.Warning($"Can't verify if user is member of the group. {_config.TestChatId}, {message.From.Id}"); } } return(isAllowed); } return(message.Chat.Id == _config.AHChatId || message.Chat.Id == _config.TestChatId); }
public async Task ProcessNewChatMember(Message message) { var freshness = DateTime.UtcNow - message.Date.ToUniversalTime(); if (freshness > _settings.ProcessEventTimeout) { _logger.LogInformation( "Message about {NewChatMembers} received {Freshness} ago and ignored", message.NewChatMembers.Length, freshness); return; } foreach (var unauthorizedUser in message.NewChatMembers) { var answer = GetRandomNumber(); var chatUser = await _telegramBot.GetChatMemberAsync(message.Chat.Id, unauthorizedUser.Id); if (chatUser == null) { return; } await _telegramBot.RestrictChatMemberAsync( message.Chat.Id, unauthorizedUser.Id, new ChatPermissions { CanAddWebPagePreviews = false, CanChangeInfo = false, CanInviteUsers = false, CanPinMessages = false, CanSendMediaMessages = false, CanSendMessages = false, CanSendOtherMessages = false, CanSendPolls = false }, DateTime.Now.AddDays(1)); var prettyUserName = GetPrettyName(unauthorizedUser); var sentMessage = await _telegramBot .SendTextMessageAsync( message.Chat.Id, $"Привет, {prettyUserName}, нажми кнопку {GetText(answer)}, чтобы тебя не забанили!", replyToMessageId : message.MessageId, replyMarkup : new InlineKeyboardMarkup(GetKeyboardButtons())); _usersStore.Add(unauthorizedUser, message, sentMessage.MessageId, prettyUserName, answer, chatUser); _logger.LogInformation( "The new user {UserId} with name {UserName} was detected and trialed. " + "He has one minute to answer.", unauthorizedUser.Id, prettyUserName); } }
public async Task <OkResult> GetUpdates([FromBody] Update updates) { if (updates.Type == UpdateType.Unknown) { return(Ok()); } else if (updates.Type == UpdateType.Message) { if (updates.Message.Chat.Type == ChatType.Private) { if (updates.Type == UpdateType.Message) { } } else if (updates.Message.Chat.Type == ChatType.Supergroup || updates.Message.Chat.Type == ChatType.Group) { if (updates.Message.Text == "فعال شدن") { var creator = await _client.GetChatMemberAsync(updates.Message.Chat.Id, updates.Message.From.Id); if (creator.Status == ChatMemberStatus.Creator) { if (_context.Groups.Any(c => c.Id == updates.Message.Chat.Id.ToString())) { await _client.SendTextMessageAsync(updates.Message.Chat.Id, ErrorAnswerModel.GroupAddedbefor); } else { try { _context.Groups.Add(new Group { Id = updates.Message.Chat.Id.ToString(), BotSetting = new botSetting { LockGap = false, LockSticker = false, LockVideo = false, LockVoice = false, SettingId = Guid.NewGuid().ToString() }, GroupAdded = true, GroupName = updates.Message.Chat.FirstName + updates.Message.Chat.LastName, MemberCount = await _client.GetChatMembersCountAsync(updates.Message.Chat.Id), }); _context.Admins.Add(new Admin { Id = updates.Message.From.Id.ToString(), Name = updates.Message.From.FirstName + updates.Message.From.LastName, UserName = updates.Message.From.Username ?? default }); _context.AdminGroups.Add(new AdminGroup { AdminId = updates.Message.From.Id.ToString(), GroupId = updates.Message.Chat.Id.ToString() }); _context.SaveChanges(); await _client.SendTextMessageAsync(updates.Message.Chat.Id, TextAnswerModel.GapAdded(updates.Message.Chat.Id, updates.Message.From.Id)); }
public async Task <IActionResult> Info(long chatId, int?userId, CancellationToken cancellationToken = default) { IDictionary <string, object> result = new ExpandoObject(); result["chat"] = await myBot.GetChatAsync(chatId, cancellationToken); if (userId is {} uid) { result["member"] = await myBot.GetChatMemberAsync(chatId, uid, cancellationToken); } return(Json(result)); }
public async Task ExecuteAsync(ITelegramBotClient botClient, Message message) { var tableClient = new CloudTableClient( new Uri(Environment.GetEnvironmentVariable("STORAGE_URL")), new StorageCredentials(Environment.GetEnvironmentVariable("STORAGE_ACCOUNT_NAME"), Environment.GetEnvironmentVariable("STORAGE_ACCOUNT_KEY"))); var laroRankingTable = tableClient.GetTableReference("LaroRanking"); await laroRankingTable.CreateIfNotExistsAsync(); var query = new TableQuery <LaroRankingEntity>(). Where( TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, message.Chat.Id.ToString()) ); var rankingEntries = await laroRankingTable.ExecuteQuerySegmentedAsync(query, null); var groupedRankingEntries = rankingEntries.GroupBy(e => e.UserId).OrderByDescending(g => g.Count()).Take(10); if (groupedRankingEntries.Count() > 0) { var stringBuilder = new StringBuilder(); var emojiIndex = 0; stringBuilder.AppendLine("🏆 LARO RANKING 🏆"); stringBuilder.AppendLine(); foreach (var rankingUser in groupedRankingEntries) { try { var userInfo = await botClient.GetChatMemberAsync(message.Chat.Id, rankingUser.Key); var userName = userInfo.User.Username; if (string.IsNullOrWhiteSpace(userName)) { userName = $"{userInfo.User.FirstName} {userInfo.User.LastName}"; } stringBuilder.AppendLine($"{_rankingEmojis[emojiIndex]} {userName} ➡️ {rankingUser.Count()}"); } catch (Exception ex) { stringBuilder.AppendLine($"{_rankingEmojis[emojiIndex]} <Unknown user ({rankingUser.Key})> ➡️ {rankingUser.Count()}"); } emojiIndex++; } await botClient.SendTextMessageAsync(message.Chat.Id, stringBuilder.ToString()); } }
public async Task ExecuteAsync(ITelegramBotClient botClient, Message message) { var messageParts = message.Text.Split(' '); if (messageParts.Length < 2) { await botClient.SendTextMessageAsync(message.Chat.Id, "Please specify a group name", replyToMessageId : message.MessageId); return; } var notificationGroupName = messageParts[1].ToLowerInvariant(); var tableClient = new CloudTableClient( new Uri(Environment.GetEnvironmentVariable("STORAGE_URL")), new StorageCredentials(Environment.GetEnvironmentVariable("STORAGE_ACCOUNT_NAME"), Environment.GetEnvironmentVariable("STORAGE_ACCOUNT_KEY"))); var subscriptionsTable = tableClient.GetTableReference("NotificationGroups"); await subscriptionsTable.CreateIfNotExistsAsync(); var query = new TableQuery <GroupSubscriptionEntity>(). Where( TableQuery.CombineFilters ( TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, message.Chat.Id.ToString()), TableOperators.And, TableQuery.GenerateFilterCondition("GroupName", QueryComparisons.Equal, notificationGroupName) ) ); var existingSubscriptions = await subscriptionsTable.ExecuteQuerySegmentedAsync(query, null); if (existingSubscriptions.Count() == 0) { await botClient.SendTextMessageAsync(message.Chat.Id, $"The group \"{notificationGroupName}\" does not exist", replyToMessageId : message.MessageId); return; } var messageText = new StringBuilder(); foreach (var result in existingSubscriptions) { var user = await botClient.GetChatMemberAsync(message.Chat.Id, int.Parse(result.UserId)); messageText.Append($"@{user.User.Username} "); } messageText.Append($"{notificationGroupName}"); await botClient.SendTextMessageAsync(message.Chat.Id, messageText.ToString()); }
public async Task <ChatMember> GetChatMemberAsync( ChatId chatId, long userId, bool evictAfter = false ) { var cacheKey = "chat-member_" + chatId + $"_{userId}"; var data = await _cacheService.GetOrSetAsync( cacheKey, evictAfter : evictAfter, action : async() => { var chat = await _botClient.GetChatMemberAsync(chatId, userId); return(chat); } ); return(data); }
public async Task <ChatMemberStatus> GetChatMemberStatus([CanBeNull] ChatId chat, long?userId, CancellationToken cancellation = default) { if (!(chat?.Identifier is long chatId) || chatId == 0) { return(UnknownStatus); } if (!(userId is long id)) { return(UnknownStatus); } // regular user, itself if (chatId == id) { return(ChatMemberStatus.Creator); } // regular user, not itself if ((chatId > 0) || (userId < 0)) { return(ChatMemberStatus.Restricted); } var key = (chatId, id : (int)id); return(await myMemoryCache.GetOrCreateAsync(key, async entry => { entry.SlidingExpiration = TimeSpan.FromMinutes(5); try { return (await myBot.GetChatMemberAsync(key.chatId, key.id, cancellation)).Status; } catch (ApiRequestException) { return UnknownStatus; } })); }
private static async void BotOnMessageReceived(object sender, MessageEventArgs e) { if (e.Message == null) { return; } string MessageText = e.Message.Text; // Текстовое сообщение long ChatId = e.Message.Chat.Id; // Id чата int UserId = e.Message.From.Id; // Id участника чата var ReplyMessage = e.Message.ReplyToMessage; // Сообщение которому ответили int MessageId = e.Message.MessageId; // Id сообщения string FirstName = e.Message.From.FirstName; // Ник участника чата var photo = new ChoosePhoto(); try { if (MessageText == "/start" && ChatId == UserId) { await botClient.SendTextMessageAsync(chatId : e.Message.Chat, "Приветствую тебя. Хочешь поговорить со мной? :)").ConfigureAwait(false); } if (MessageText == "Заказ" && ChatId == UserId) // Взаимодействие с API sms-activate.ru { var InlineOrder = new InlineKeyboardMarkup(new[] { new[] { InlineKeyboardButton.WithCallbackData("Баланс"), InlineKeyboardButton.WithCallbackData("Заказать номер") }, new[] { InlineKeyboardButton.WithCallbackData("Кол-во доступных номеров") }, new[] { InlineKeyboardButton.WithCallbackData("Статус заказа"), InlineKeyboardButton.WithCallbackData("Цены") }, new[] { InlineKeyboardButton.WithCallbackData("Изменить статус") }, }); // Inline клавиатура для выполнения заказа номера await botClient.SendTextMessageAsync(ChatId, "Выбери одну из следующих операций:", replyMarkup : InlineOrder); } if (int.TryParse(MessageText, out int IdOrder) && MessageText.Length >= 9 && ChatId == UserId) { string Path_to_id = @"id.txt"; // файл c номером заказа using (StreamWriter Id = new StreamWriter(Path_to_id, false, Encoding.UTF8)) { Id.WriteLine(IdOrder); } await botClient.SendTextMessageAsync(ChatId, $"Заказ с Id {IdOrder} запомнил"); } if (ChatId == 1234567890 && MessageText.Substring(0, 9) == "Добавить:") // TODO: поставить свой id { // Добавляем новые слова в бд для таблицы "секретных слов" var DeleteFirstWord = MessageText.Remove(0, 9); String[] DropString = DeleteFirstWord.Split(new char[] { ' ', ',', '|' }, StringSplitOptions.RemoveEmptyEntries); // Удалить все ненужные элементы во входной строке using (var AddsecretWords = new DataBaseBot()) { foreach (var ScrollWords in DropString) { var secret = new MessagesAndRating.SecretWordTable() { words = ScrollWords }; AddsecretWords.SecretWordTables.Add(secret); AddsecretWords.SaveChanges(); await botClient.SendTextMessageAsync(ChatId, ScrollWords); } } } } catch { } try { var admin = botClient.GetChatMemberAsync(ChatId, userId: e.Message.ReplyToMessage.From.Id).Result; // инфорамация про участника, которому был реплай if (MessageText == "Права" && ReplyMessage != null && admin.Status == ChatMemberStatus.Administrator) // Проверять права администраторов { await botClient.SendTextMessageAsync(ChatId, $"*{admin.Status}* [{e.Message.ReplyToMessage.From.FirstName}](tg://user?id={e.Message.ReplyToMessage.From.Id}) может:" + $"\nУдалять сообщения: *{admin.CanDeleteMessages}*" + $"\nЗакреплять сообщения: *{admin.CanPinMessages}*" + $"\nДобавлять администрацию: *{admin.CanPromoteMembers}*" + $"\nОграничивать/банить пользователей: *{admin.CanRestrictMembers}*" + $"\nИзменять описание группы: *{admin.CanChangeInfo}*" + $"\nПриглашать людей: *{admin.CanInviteUsers}*", parseMode : ParseMode.Markdown); } else if (MessageText == "Фото") { await botClient.SendPhotoAsync(ChatId, photo.SavePhoto(), replyToMessageId : MessageId); // Отправка случайного фото } } catch { } try { if (MessageText == "Стат" || MessageText == "/mystat@terpilla_bot" || MessageText == "/mystat" && ChatId != UserId) { using (var context = new DataBaseBot()) { var group = new MessagesAndRating.RatingTable() { FirstName = e.Message.From.FirstName, UserId = e.Message.From.Id }; var count = new MessagesAndRating.CountMessageTable() { FirstName = e.Message.From.FirstName, UserId = e.Message.From.Id }; try { var counter = context.CountMessageTables.Single(x => x.UserId == count.UserId); var s = context.RatingTables.Single(x => x.UserId == group.UserId); await botClient.SendTextMessageAsync(chatId : e.Message.Chat, text : $"[{FirstName}](tg://user?id={UserId})\nID чата: *{ChatId}*\nВсего сообщений в чате : " + $" *{e.Message.MessageId}*\nТвой рейтинг: *{s.rate}* 🆙\nТвои сообщения по всем чатам: *{counter.Counter}* ✉️\n" + $"Твое звание: *{counter.rank}*\nДата: *{e.Message.Date}* (UTC + 3 часа)" , parseMode : ParseMode.Markdown).ConfigureAwait(false); } catch (InvalidOperationException) { await botClient.SendTextMessageAsync(chatId : e.Message.Chat, $"[{FirstName}](tg://user?id={UserId}), для показа статистики у тебя должен быть рейтинг", parseMode : ParseMode.Markdown); } } } if (MessageText == "/help@terpilla_bot" || MessageText == "/help") // Инструкция к боту { var choose = new InlineKeyboardMarkup(new[] { new[] { InlineKeyboardButton.WithCallbackData("Для админов") }, new[] { InlineKeyboardButton.WithCallbackData("Для участников") } }); await botClient.SendTextMessageAsync(ChatId, "Инструкция:", replyMarkup : choose); } } catch { } try { if (e.Message.Type == MessageType.Text) //проверка триггеров для общения в ЛС { var responsed = apiAi_for_pm.TextRequest(MessageText); // Сообщение которое будет отправленно в DialogFlow string answer_pm = responsed.Result.Fulfillment.Speech; // Получаем ответ от DialogFlow await botClient.SendTextMessageAsync(chatId : e.Message.From.Id, answer_pm, replyToMessageId : MessageId); } if (e.Message.Type == MessageType.Text) //проверка триггеров для общения в чате { var responsed_1 = apiAi_for_chat.TextRequest(MessageText); string answer_chat = responsed_1.Result.Fulfillment.Speech; await botClient.SendTextMessageAsync(chatId : ChatId, answer_chat, replyToMessageId : MessageId); } } catch { } string name = $"{FirstName} ({e.Message.From.Username})"; Console.WriteLine($"{name} написал : {MessageText}"); }