private async Task BanSlowUsers() { var users = _usersStore.GetAll(); var usersToBan = users.Where( x => { var diff = DateTimeOffset.Now - x.JoinDateTime; return(diff > TimeSpan.FromSeconds(60)); }) .ToArray(); foreach (var newUser in usersToBan) { await _telegramBot.KickChatMemberAsync(newUser.ChatId, newUser.Id, DateTime.Now.AddDays(1)); await _telegramBot.DeleteMessageAsync(newUser.ChatId, newUser.InviteMessageId); await _telegramBot.DeleteMessageAsync(newUser.ChatId, newUser.JoinMessageId); _usersStore.Remove(newUser); _logger.LogInformation( "User {UserId} with name {UserName} was banned after one minute silence.", newUser.Id, newUser.PrettyUserName); } }
public async override void HandleCallBackQuery(CallbackQuery callbackQuery, ITelegramBotClient botClient) { var telegramid = callbackQuery.From.Id; var callbackdata = callbackQuery.Data.Split('~'); int msgId = int.Parse(callbackdata[1]); bool needsave = true; try { needsave = bool.Parse(callbackdata[2]); if (needsave) { if (MessageStorage.CheckMesDb(telegramid)) { try { await botClient.SendTextMessageAsync(telegramid, "Message has already been saved"); try { await botClient.DeleteMessageAsync(telegramid, callbackQuery.Message.MessageId); } catch { } } catch (Exception ex) { Console.WriteLine(ex.Message); } } else { MessageStorage.SaveMessageDB(msgId, textMes, telegramid); await botClient.SendTextMessageAsync(telegramid, "This message has been saved"); try { await botClient.DeleteMessageAsync(telegramid, callbackQuery.Message.MessageId); } catch { } } } else { //MessageStorage.DeletMessage(telegramid); await botClient.SendTextMessageAsync(telegramid, "Message not saved!"); await botClient.DeleteMessageAsync(telegramid, callbackQuery.Message.MessageId); } } catch { MessageStorage.DeletMessage(telegramid); await botClient.SendTextMessageAsync(telegramid, "Message was deleted!"); try { await botClient.DeleteMessageAsync(telegramid, callbackQuery.Message.MessageId); } catch { } } }
public async Task ProcessCallback(Update update) { var query = update.CallbackQuery; var chatId = query.Message.Chat.Id; var userId = query.From.Id; var unauthorizedUser = _userService.Get(chatId, userId); if (unauthorizedUser == null) { _logger.LogInformation($"Пользователь с id {userId} не найден"); return; } var unauthorizedUserAnswer = int.Parse(query.Data); if (unauthorizedUserAnswer != (int)unauthorizedUser.Answer) { await _telegramBot.KickChatMemberAsync( chatId, query.From.Id, DateTime.Now.AddDays(1)); _logger.LogInformation( $"Пользователь {userId} с ником {unauthorizedUser.PrettyUserName} был забанен после ввода неправильного ответа {unauthorizedUserAnswer}, " + $"в то время как правильный это - {unauthorizedUser.Answer}."); } else { var defaultPermissions = (await _telegramBot.GetChatAsync(chatId)).Permissions; var postBanPermissions = new ChatPermissions { CanAddWebPagePreviews = defaultPermissions?.CanAddWebPagePreviews ?? true, CanChangeInfo = defaultPermissions?.CanChangeInfo ?? true, CanInviteUsers = defaultPermissions?.CanInviteUsers ?? true, CanPinMessages = defaultPermissions?.CanPinMessages ?? true, CanSendMediaMessages = defaultPermissions?.CanSendMediaMessages ?? true, CanSendMessages = defaultPermissions?.CanSendMessages ?? true, CanSendOtherMessages = defaultPermissions?.CanSendOtherMessages ?? true, CanSendPolls = defaultPermissions?.CanSendPolls ?? true }; await _telegramBot.RestrictChatMemberAsync( chatId, query.From.Id, postBanPermissions); _logger.LogInformation($"Пользователь {unauthorizedUser.UserId} с именем {unauthorizedUser.PrettyUserName} был авторизован с ответом {unauthorizedUser.Answer}."); } await _telegramBot.DeleteMessageAsync(unauthorizedUser.ChatId, unauthorizedUser.InviteMessageId); await _telegramBot.DeleteMessageAsync(unauthorizedUser.ChatId, unauthorizedUser.JoinMessageId); _userService.Remove(unauthorizedUser); }
public async Task ProcessCallback(CallbackQuery query) { var chatId = query.Message.Chat.Id; var unauthorizedUser = _usersStore.Get(chatId, query.From.Id); if (unauthorizedUser == null) { _logger.LogInformation("User with id {UserId} not found", query.From.Id); return; } if (int.TryParse(query.Data, out int result)) { this._logger.LogInformation($"The number is not valid:{query.Data}"); return; } var unauthorizedUserAnswer = result; if (unauthorizedUserAnswer != unauthorizedUser.CorrectAnswer) { string log = await KickChatAsync(chatId, query.From.Id, unauthorizedUser); if (log != null) { this._logger.LogInformation($"KickChatAsync:{log}"); } } else { ChatMember preBanPermissions = unauthorizedUser.ChatMember; ChatPermissions defaultPermissions = (await _telegramBot.GetChatAsync(chatId)).Permissions; var postBanPermissions = CreateChatPermissions(preBanPermissions, defaultPermissions);// await _telegramBot.RestrictChatMemberAsync( chatId, query.From.Id, postBanPermissions); _logger.LogInformation( "User {UserId} with name {UserName} was authorized with answer {UserAnswer}. " + "With post ban permissions {PostBanPermissions}.", unauthorizedUser.Id, unauthorizedUser.PrettyUserName, unauthorizedUserAnswer, JsonSerializer.Serialize(postBanPermissions)); } await _telegramBot.DeleteMessageAsync(unauthorizedUser.ChatId, unauthorizedUser.InviteMessageId); await _telegramBot.DeleteMessageAsync(unauthorizedUser.ChatId, unauthorizedUser.JoinMessageId); _usersStore.Remove(unauthorizedUser); }
private async Task HandleIncomingFacultyAsync(Message request, CallbackQuery response, params object[] payload) { var chatId = response.Message.Chat.Id; var faculties = await _scheduleParser.ParseFacultiesAsync(); var facultyAbbreviation = response.Data; var faculty = faculties.FirstOrDefault(faculty => faculty.TitleAbbreviation.Equals(facultyAbbreviation)); if (faculty is not null) { var groups = await _scheduleParser.ParseGroupsAsync(faculty.Id); var inlineKeyboard = groups.ToInlineKeyboard ( group => group.Title, columnsCount: 3 ); await _client.SendChatActionAsync ( chatId, chatAction : ChatAction.Typing ); await _client.DeleteMessageAsync ( chatId, messageId : request.MessageId ); var nextRequest = await _client.SendTextMessageAsync ( chatId, text : "Теперь выберите группу:", replyMarkup : inlineKeyboard ); _callbackQueryListener.RegisterRequest ( nextRequest, HandleIncomingGroupAsync, faculty.Id ); } await _client.AnswerCallbackQueryAsync(response.Id); }
private static async System.Threading.Tasks.Task MessageDeletionOnCallback(CallbackQueryEventArgs e) { if ((DateTime.UtcNow - e.CallbackQuery.Message.Date).TotalHours < 48) { try { await botClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id); await botClient.DeleteMessageAsync(e.CallbackQuery.Message.Chat.Id, e.CallbackQuery.Message.MessageId); } catch (Telegram.Bot.Exceptions.ApiRequestException ex) { Console.WriteLine(ex.ErrorCode == 400 ? $"{string.Format("{0:[HH:mm:ss] dd.MM.yy}", DateTime.Now)} - Message with id {e.CallbackQuery.Message.MessageId} has already been deleted" : $"{string.Format("{0:[HH:mm:ss] dd.MM.yy}", DateTime.Now)} - Exception :( StackTrace: {ex.StackTrace}"); } } else { await botClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id, "удоли через контекстное меню"); Console.WriteLine($"{string.Format("{0:[HH:mm:ss] dd.MM.yy}", DateTime.Now)} - Old message deletion attempt {e.CallbackQuery.Message.Date} in chat with {users[e.CallbackQuery.From.Id]}"); SickLeaveEvent.Clear(sickLeaveEvents[e.CallbackQuery.From.Id]); SickLeaveEvent.Clear(dayoffEvents[e.CallbackQuery.From.Id]); SickLeaveEvent.Clear(vacationEvents[e.CallbackQuery.From.Id]); LeaveRequestEvent.Clear(leaveRequestEvents[e.CallbackQuery.From.Id]); } }
/// <summary> /// Immediately save data. /// </summary> /// <returns></returns> public async Task ForceSave() { using (await _saveLock.LockAsync()) { var chat = await _botClient.GetChatAsync(_saveResChatId); var prevPinnedMessage = chat.PinnedMessage; SaveStorageStateToFile(); Message savedMsg = null; using (var readStream = File.OpenRead(_storageFilePath)) { savedMsg = await _botClient.SendDocumentAsync( _saveResChatId, new InputOnlineFile(readStream, FileResName), caption : FileResName ); } await _botClient.PinChatMessageAsync(_saveResChatId, savedMsg.MessageId); if (_deletePreviousMessages) { await _botClient.DeleteMessageAsync(_saveResChatId, prevPinnedMessage.MessageId); } } }
public async void Handle(Message message) { Debug.Assert(message != null); if (message.From.Id == _botClient.BotId) { // Don't process messages sent by us. return; } if (message.Text != null) { _logger.Information($"{Utilities.UserToString(message.From)}: {message.Text}"); } if (_spammerDetector.IsSpam(message)) { // Don't ban admins. ChatMember[] admins = await _botClient.GetChatAdministratorsAsync(message.Chat.Id).ConfigureAwait(false); if (admins.Select(a => a.User.Id).Contains(message.From.Id)) { _logger.Information($"Ignoring spam from admin {message.From.Id}"); return; } await _botClient.DeleteMessageAsync(message.Chat.Id, message.MessageId).ConfigureAwait(false); await _botClient.KickChatMemberAsync(message.Chat.Id, message.From.Id).ConfigureAwait(false); await _botClient.SendTextMessageAsync(message.Chat.Id, $"Banned spammer {Utilities.UserToString(message.From)}.").ConfigureAwait(false); } }
private async Task RemovePreviousMessages(int chatId, BaseTransactionModel currentTransaction) { foreach (var id in currentTransaction.MessageIds) { await _botClient.DeleteMessageAsync(chatId, id); } currentTransaction.MessageIds.Clear(); }
public void DeleteMessage(long chatId, int messageId) { ITelegramBotClient telegramBotClient = ModulesManager.GetTelegramBotClient(); ISessionManager sessionManager = ModulesManager.GetSessionManager(); sessionManager.GetChatSession(chatId).MessageDeleted(messageId); telegramBotClient.DeleteMessageAsync(chatId, messageId); }
private async Task BanSlowUsers() { var banTime = DateTime.Now + _settings.BanTime; foreach (var newUser in _userService .GetAll() .Where(x => DateTimeOffset.Now - x.JoinDateTime > _settings.ProcessEventTimeout)) { await _telegramBot.KickChatMemberAsync(newUser.ChatId, (int)newUser.UserId, banTime); await _telegramBot.DeleteMessageAsync(newUser.ChatId, newUser.InviteMessageId); await _telegramBot.DeleteMessageAsync(newUser.ChatId, newUser.JoinMessageId); _userService.Remove(newUser); _logger.LogInformation($"Пользователь {newUser.UserId} с именем {newUser.PrettyUserName} был забанен после {_settings.ProcessEventTimeout.ToString()} ожидания."); } }
public async Task <QuestCard> SelectQuestCard(long id) { var tcs = new TaskCompletionSource <QuestCard>(); Message message = null; EventHandler <CallbackQueryEventArgs> handler = (s, e) => { if (message.MessageId == e.MessageId) { tcs.TrySetResult((QuestCard)Enum.Parse(typeof(QuestCard), e.Data)); } }; try { callbackQueryHandler.CallbackQuery += handler; message = await client.SendTextMessageAsync( chatId : new Telegram.Bot.Types.ChatId(id), text : "Please select quest card", replyMarkup : new InlineKeyboardMarkup( new InlineKeyboardButton[] { new InlineKeyboardButton() { Text = "Success", CallbackData = QuestCard.MissionSuccess.ToString() }, new InlineKeyboardButton() { Text = "Failed", CallbackData = QuestCard.MissionFailed.ToString() } })); var result = await tcs.Task; await client.DeleteMessageAsync(new ChatId(message.Chat.Id), message.MessageId); return(result); } finally { callbackQueryHandler.CallbackQuery -= handler; } }
private async Task HandleIncomingWeekAsync(Message request, CallbackQuery response, params object[] payload) { var chatId = response.Message.Chat.Id; var weekDates = _weekDatesProvider.GetCurrentWeekDates ( DateTime.Parse(response.Data) ); var inlineKeyboard = weekDates.ToInlineKeyboard ( dateTime => $"{dateTime:dd.MM (ddd)}", columnsCount: 3 ); await _client.SendChatActionAsync ( chatId, chatAction : ChatAction.Typing ); await _client.DeleteMessageAsync ( chatId, messageId : request.MessageId ); var nextRequest = await _client.SendTextMessageAsync ( chatId, text : "Выберите дату:", replyMarkup : inlineKeyboard ); _callbackQueryListener.RegisterRequest ( nextRequest, HandleIncomingDateAsync ); await _client.AnswerCallbackQueryAsync(response.Id); }
private async Task <bool> SendSuccess(Message message, User user) { var deleteTask = _telegramBotClient.DeleteMessageAsync(message.Chat.Id, message.MessageId); var sendTask = _telegramBotClient.SendTextMessageAsync(message.Chat.Id, $"Successfully logged in using: ```{user.Email}```", ParseMode.MarkdownV2); await Task.WhenAll(deleteTask, sendTask); return(true); }
public async Task ExecuteCallbackQueryAsync(long chatId, int messageId, string callbackQueryId, string payload) { _storageService.AddOrUpdate(StorageKeys.BotCurrentState, BotStateType.FirewallCreateWaitingEnterName); await _telegramBotClient.DeleteMessageAsync( chatId : chatId, messageId : messageId); await _telegramBotClient.SendTextMessageAsync( chatId : chatId, text : FirewallMessage.GetEnterNameMessage()); }
public static bool Delete(long chatid, int messageid) { try { return(Api.DeleteMessageAsync(chatid, messageid).Result); } catch { //... return(false); } }
/// <summary> /// Отправить фото в чат /// </summary> /// <param name="chatId"></param> /// <param name="caption"></param> /// <param name="file"></param> public Message[] EditFoto(Message[] messages, List <byte[]> file) { if (messages == null || messages.Length == 0) { return(new Message[2]); } for (int i = 0; i < messages.Length; i++) { botClient.DeleteMessageAsync(messages[i].Chat, messages[i].MessageId); } return(SedFoto(messages[0].Chat, "редактировать фото", file)); }
private static async void BotClient_OnCallbackQuery(object sender, CallbackQueryEventArgs e) { Console.WriteLine("\nMessage id: " + e.CallbackQuery.Message.MessageId + "code: " + e.CallbackQuery.Data); string[] code = e.CallbackQuery.Data.Split(" "); switch (code[0]) { case "reset": await SendOptionsAsync(e.CallbackQuery.Message.Chat.Id, Messages.OPTIONS); break; case "stats": await SendStats(e.CallbackQuery.Message, e.CallbackQuery.From.Id); break; case "eggs": await ProcessEggCode(e.CallbackQuery.Message.Chat.Id, code, (e.CallbackQuery.Message.Text == "Which one was shiny?")); break; case "raid": await ProcessRaidCode(e.CallbackQuery.Message.Chat.Id, code); break; default: break; } try { await botClient.DeleteMessageAsync(e.CallbackQuery.Message.Chat.Id, e.CallbackQuery.Message.MessageId); } catch (Telegram.Bot.Exceptions.ApiRequestException ex) { Console.WriteLine("tried to delete a message twice\n" + ex.ToString()); } }
public async Task <bool> DeleteMessage(long chatId, long messageId) { try { await _api.DeleteMessageAsync(chatId, (int)messageId).ConfigureAwait(false); return(true); } catch { return(false); } }
static async void Bot_OnMessage(object sender, MessageEventArgs messageEvent) { var message = messageEvent.Message; if (message == null) { return; } try { var messageLines = message.Text.Split(new[] { '\r', '\n' }); if (messageLines[0].Trim() == "#phatcard") { // Add cards to list. cardInfo.Clear(); for (int i = 1; i < messageLines.Length; i++) { string provider = messageLines[i].Split('-', 2)[0].Trim().ToUpper(); string pin = messageLines[i].Split('-', 2)[1].Trim(); cardInfo.Add(new CardInfo(provider, pin)); } // Create buttons buttons.Clear(); for (int i = 0; i < cardInfo.Count; i++) { List <InlineKeyboardButton> oneButton = new List <InlineKeyboardButton> { InlineKeyboardButton.WithCallbackData(cardInfo[i].Provider, i.ToString()) }; buttons.Add(oneButton); } var inlineKeyboard = new InlineKeyboardMarkup(buttons); // Send buttons await vozPhatCardBot.SendTextMessageAsync( message.Chat, "Phát cạc bà con ơi. Bấm vào nút là được!", replyMarkup : inlineKeyboard); // Delete command message await vozPhatCardBot.DeleteMessageAsync( message.Chat, message.MessageId); } } catch (IndexOutOfRangeException) { } catch (NullReferenceException) { } }
private async void OnCallbackQuery(object sender, CallbackQueryEventArgs args) { try { var query = args.CallbackQuery; if (query.Data != "Пёс с ним") { var id = Int32.Parse(query.Data); await UnRestrict(id); await _client.SendTextMessageAsync(_configuration.ChannelId, $"Разбанил {id}"); } if (query.Message != null) { await _client.DeleteMessageAsync(query.Message.Chat.Id, query.Message.MessageId); } } catch (Exception exception) { Console.WriteLine(exception); } }
static async void Bot_OnMessage(object sender, MessageEventArgs e) { var messageText = e.Message.Text; if (messageText != null) { Console.WriteLine($"Received a text message in chat {e.Message.Chat.Id}: {messageText}"); var originalMessage = messageText; var regexUrl = new Regex(@"[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&\/=]*)"); if (regexUrl.Match(originalMessage).Success) { Console.WriteLine($"Url regex found. Deleting message in chat {e.Message.Chat.Id}: {messageText}"); try { await _botClient.DeleteMessageAsync( chatId : e.Message.Chat, messageId : e.Message.MessageId ); await _botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : "Шилтеме өчүрүлдү" ); } catch (Exception ex) { Console.WriteLine($"{ex}"); } } } if (e.Message.NewChatMembers != null && e.Message.NewChatMembers.Length > 0) { foreach (var newChatMember in e.Message.NewChatMembers) { var message = $"Салам Урматтуу '{newChatMember.Username}'. Кош келипсиз биздин груупага!"; Console.WriteLine(message); await _botClient.SendTextMessageAsync( chatId : e.Message.Chat, text : message ); } } }
public async Task ExecuteCallbackQueryAsync(long chatId, int messageId, string callbackQueryId, string payload) { var paginator = _firewallPaginatorService.Select(payload); _storageService.AddOrUpdate(StorageKeys.FirewallId, payload); _storageService.Remove(StorageKeys.Firewalls); await _telegramBotClient.DeleteMessageAsync(chatId, messageId); await _telegramBotClient.SendTextMessageAsync( chatId : chatId, text : paginator.MessageText, parseMode : ParseMode.Markdown, replyMarkup : paginator.Keyboard); }
private async Task TryDeleteMissingTagsWarning(Message message) { var hasWarningMessage = _memoryCache.TryGetValue( GetErrorKey(message), out ChatMessageId warningMessageIds); if (!hasWarningMessage) { return; } await _telegramBot.DeleteMessageAsync( warningMessageIds.ChatId, warningMessageIds.MessageId); }
public async Task ExecuteCallbackQueryAsync(long chatId, int messageId, string callbackQueryId, string payload) { var paginator = _imagePaginatorService.Select(payload); _storageService.AddOrUpdate(StorageKeys.ImageId, long.Parse(payload)); _storageService.Remove(StorageKeys.Images); await _telegramBotClient.DeleteMessageAsync(chatId, messageId); await _telegramBotClient.SendTextMessageAsync( chatId : chatId, text : paginator.MessageText, parseMode : ParseMode.Markdown); _imagePaginatorService?.OnSelectCallback(); }
public async override void Handle(MessageWrapper message, ITelegramBotClient client) { if (message.Type == MessageType.Sticker && message.Sticker != null) { Console.WriteLine($"[{message.Chat.Id} ({message.Chat.Title})] {message.From.Username}: [sticker] {message.Sticker.SetName} emoji {message.Sticker.Emoji} file id {message.Sticker.FileId}"); if (((message.Sticker.SetName?.Contains("Sharij", StringComparison.OrdinalIgnoreCase) ?? false) || (message.Sticker.SetName?.Contains("Shariy", StringComparison.OrdinalIgnoreCase) ?? false))) { await client.DeleteMessageAsync(message.Chat.Id, message.MessageId); } } else { NextHandler?.Handle(message, client); } }
public async Task ExecuteAsync(object sender, CallbackQueryEventArgs e) { //Console.WriteLine(e.CallbackQuery.Message.Text); //Console.WriteLine(e.CallbackQuery.Id); //Console.WriteLine(e.CallbackQuery.Data);//这才是关键的东西,就是上面在按钮上写的那个sendmessage var ChatId = e.CallbackQuery.Message.Chat.Id; var IsGroup = e.CallbackQuery.Message.Chat.Id < 0; await botClient.AnswerCallbackQueryAsync(e.CallbackQuery.Id, "搜索中。。。"); try { var searchOption = JsonConvert.DeserializeObject <SearchOption>(Encoding.UTF8.GetString(await Cache.GetAsync(e.CallbackQuery.Data))); await Cache.RemoveAsync(e.CallbackQuery.Data); searchOption.ToDelete.Add(e.CallbackQuery.Message.MessageId); searchOption.ReplyToMessageId = e.CallbackQuery.Message.MessageId; searchOption.Chat = e.CallbackQuery.Message.Chat; if (searchOption.ToDeleteNow) { foreach (var i in searchOption.ToDelete) { await Send.AddTask(async() => { try { await botClient.DeleteMessageAsync(ChatId, (int)i); } catch (AggregateException) { logger.LogError("删除了不存在的消息"); } }, IsGroup); } return; } var searchOptionNext = await sonicSearchService.Search(searchOption); if (searchOptionNext.Messages.Count == 0) { searchOption = await searchService.Search(searchOption); } await sendService.ExecuteAsync(searchOption, searchOptionNext.Messages); } catch (KeyNotFoundException) { } catch (ArgumentException) { } }
private void OnCallbackQuery(object sender, CallbackQueryEventArgs e) { _logger.LogInformation("A callback query received: {@CallbackQuery}", e.CallbackQuery); var chatId = e.CallbackQuery.Message.Chat.Id; if (chatId != _options.Connection.ChatId) { _logger.LogWarning("Unexpected chat id in callback query: {@CallbackQuery}", e.CallbackQuery); return; } // fire message removal _client.DeleteMessageAsync(chatId, e.CallbackQuery.Message.MessageId, _cancellationToken); // fire callback _client.AnswerCallbackQueryAsync(e.CallbackQuery.Id, "🐱", cancellationToken: _cancellationToken); }
private async Task TryDeleteWarningMessage(Message message) { var vacancyErrors = _vacancyAnalyzer.GetVacancyErrors(message).ToList(); if (vacancyErrors.Count != 0) { return; } var hasWarningMessage = _memoryCache.TryGetValue( GetErrorKey(message), out ChatMessageId warningMessageIds); if (hasWarningMessage) { await _telegramBot.DeleteMessageAsync( warningMessageIds.ChatId, warningMessageIds.MessageId); } }
private async Task BanSlowUsers() { var users = _usersStore.GetAll(); var usersToBan = users.Where( x => { var diff = DateTimeOffset.Now - x.JoinDateTime; return(diff > TimeSpan.FromSeconds(60)); }) .ToArray(); foreach (var newUser in usersToBan) { await _telegramBot.KickChatMemberAsync(newUser.ChatId, newUser.Id, DateTime.Now.AddDays(1)); await _telegramBot.DeleteMessageAsync(newUser.ChatId, newUser.InviteMessageId); _usersStore.Remove(newUser); } }