/// <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 IAsyncEnumerable <MessageResponse> Handler(Message message) { yield return("准备中……"); UserInfo senderInfo; try { senderInfo = await _backendService.GetUserByTelegramIdAsync(message.From.Id); } catch (MatatakiUserNotFoundException) { throw new HandlerException("抱歉,目标没有绑定 Matataki 帐号或者仍未同步用户名"); } var groupButtons = new List <InlineButton[]>(); foreach (var groupId in await _groupService.GetParticipatedGroupsAsync(message.From.Id)) { try { var chat = await _botClient.GetChatAsync(groupId); groupButtons.Add(new[] { InlineButton.WithCallbackData(chat.Title, $"createHongbao {message.From.Id} {chat.Id}") }); } catch (ChatNotFoundException) { _logger.Warning("Chat not found: {Chat}", groupId); } } yield return(Markdown("请选择你要发红包的群").WithInlineButtons(groupButtons)); }
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); }
public async Task SendEpicGamesBroadcaster(long chatId) { var games = await GetFreeGamesParsed(); var freeGames = games.FirstOrDefault(); if (freeGames == null) { return; } var productUrl = freeGames.ProductUrl; var productTitle = freeGames.ProductTitle; var chat = await _botClient.GetChatAsync(chatId); if (chat.LinkedChatId != null) { chatId = chat.LinkedChatId.Value; } var isHistoryExist = await _rssService.IsHistoryExist(chatId, productUrl); if (isHistoryExist) { Log.Information( "Seem EpicGames with Title: '{Title}' already sent to ChatId: {ChannelId}", productTitle, chatId ); } else { await _botClient.SendPhotoAsync( chatId : chatId, photo : freeGames.Images.ToString(), caption : freeGames.Detail, parseMode : ParseMode.Html ); await _rssService.SaveRssHistoryAsync( new RssHistory() { ChatId = chatId, Title = productTitle, Url = productUrl, PublishDate = DateTime.UtcNow, Author = "EpicGames Free", CreatedAt = DateTime.UtcNow, RssSource = "https://store.epicgames.com" } ); } }
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 <Chat> GetChatAsync(ChatId chatId) { var cacheKey = "chat_" + chatId; var data = await _cacheService.GetOrSetAsync( cacheKey, async() => { var chat = await _botClient.GetChatAsync(chatId); return(chat); } ); return(data); }
public static Message GetPinned(long chatid) { try { var t = Api.GetChatAsync(chatid); t.Wait(); return(t.Result.PinnedMessage); } catch (Exception e) { //... e.Log(true); return(null); } }
public async IAsyncEnumerable <MessageResponse> GroupHandler(Message message, long groupId) { yield return("查询中……"); if (!await _groupService.IsGroupExistsAsync(groupId)) { yield return("没有这样的群"); yield break; } var chat = await _botClient.GetChatAsync(groupId); var inviteLink = chat.InviteLink ?? await _botClient.ExportChatInviteLinkAsync(groupId); yield return(Text("您可以进入该群") .WithInlineButtons(InlineButton.WithUrl(chat.Title, inviteLink))); }
public async Task <User?> GetUser(long userId) { var user = await _api.GetChatAsync(userId).ConfigureAwait(false); return(TgConverter.ToUser(user)); }
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; } var unauthorizedUserAnswer = int.Parse(query.Data); if (unauthorizedUserAnswer != unauthorizedUser.CorrectAnswer) { await _telegramBot.KickChatMemberAsync( chatId, query.From.Id, DateTime.Now.AddDays(1)); _logger.LogInformation( "User {UserId} with name {UserName} was banned after incorrect answer {UserAnswer}, " + "while correct one is {CorrectAnswer}.", unauthorizedUser.Id, unauthorizedUser.PrettyUserName, unauthorizedUserAnswer, unauthorizedUser.CorrectAnswer); } else { var preBanPermissions = unauthorizedUser.ChatMember; var defaultPermissions = (await _telegramBot.GetChatAsync(chatId)).Permissions; var postBanPermissions = new ChatPermissions { CanAddWebPagePreviews = preBanPermissions.CanAddWebPagePreviews ?? defaultPermissions?.CanAddWebPagePreviews ?? true, CanChangeInfo = preBanPermissions.CanChangeInfo ?? defaultPermissions?.CanChangeInfo ?? true, CanInviteUsers = preBanPermissions.CanInviteUsers ?? defaultPermissions?.CanInviteUsers ?? true, CanPinMessages = preBanPermissions.CanPinMessages ?? defaultPermissions?.CanPinMessages ?? true, CanSendMediaMessages = preBanPermissions.CanSendMediaMessages ?? defaultPermissions?.CanSendMediaMessages ?? true, CanSendMessages = preBanPermissions.CanSendMessages ?? defaultPermissions?.CanSendMessages ?? true, CanSendOtherMessages = preBanPermissions.CanSendOtherMessages ?? defaultPermissions?.CanSendOtherMessages ?? true, CanSendPolls = preBanPermissions.CanSendPolls ?? defaultPermissions?.CanSendPolls ?? true }; 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 void Command_Received(object sender, MessageEventArgs e) { Task.Run(() => { var requestUser = _userService.AddUserIfNotExist(new dal.entities.User { Username = e.Message.From.Username, TelegramId = e.Message.From.Id, Firstname = e.Message.From.FirstName, Lastname = e.Message.From.LastName, }); if (e.Message.Type == MessageType.Text) { if (e.Message.Text.Trim().StartsWith(TelegramBotCommands.INSERT_CHANNEL) && e.Message.Text != TelegramBotCommands.INSERT_CHANNEL) { try { ChatId chatId = new ChatId(e.Message.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Last()); Chat chat = _telegramBotClient.GetChatAsync(chatId).Result; var addedGroup = _telegramGroupService.AddGroupIfNotExist(new dal.entities.TelegramGroup { ChatId = chat.Id, UserId = requestUser.Id, Firstname = chat.FirstName, Description = chat.Description, Lastname = chat.LastName, Title = chat.Title, Username = chat.Username, }); if (addedGroup != null) { _telegramBotClient.SendTextMessageAsync(e.Message.Chat.Id, TelegramBotCommands.CHANNEL_ADDED_INFORMATION, ParseMode.Html); } } catch (Exception ex) { _logService.InsertLog(ex, enums.LogLevel.TELEGRAM); _telegramBotClient.SendTextMessageAsync(e.Message.Chat.Id, TelegramBotCommands.INSERT_CHANNEL_INFORMATION_ERROR, ParseMode.Html); } } else if (e.Message.Text.Trim().StartsWith(TelegramBotCommands.INSERT_RSS) && e.Message.Text != TelegramBotCommands.INSERT_RSS) { string rss = e.Message.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Last(); if (ValidationHelper.IsRss(rss, _logService)) { var userRss = _userRssService.AddRssIfNotExist(new dal.entities.UserRss { Url = rss, UserId = requestUser.Id, }); if (userRss != null) { _telegramBotClient.SendTextMessageAsync(e.Message.Chat.Id, TelegramBotCommands.RSS_ADDED_INFORMATION, ParseMode.Html); } } else { _telegramBotClient.SendTextMessageAsync(e.Message.Chat.Id, TelegramBotCommands.RSS_IS_NOT_VALID); } } else if (e.Message.Text == TelegramBotCommands.MENU) { _telegramBotClient.SendStartMenu(e.Message.Chat.Id); } else if (e.Message.Text == TelegramBotCommands.HELP || e.Message.Text == TelegramBotCommands.START) { _telegramBotClient.SendTextMessageAsync(e.Message.Chat.Id, TelegramBotCommands.HELP_INFORMATION, ParseMode.Html); } else if (e.Message.Text == TelegramBotCommands.ABOUT_ME) { _telegramBotClient.SendTextMessageAsync(e.Message.Chat.Id, TelegramBotCommands.ABOUT_ME_INFORMATION, ParseMode.Html); } else if (e.Message.Text == TelegramBotCommands.INSERT_RSS) { _telegramBotClient.SendTextMessageAsync(e.Message.Chat.Id, TelegramBotCommands.INSERT_RSS_INFORMATION, ParseMode.Html); } else if (e.Message.Text == TelegramBotCommands.INSERT_CHANNEL) { _telegramBotClient.SendTextMessageAsync(e.Message.Chat.Id, TelegramBotCommands.INSERT_CHANNEL_INFORMATION, ParseMode.Html); } else if (e.Message.Text.StartsWith('@')) { try { ChatId chatId = new ChatId(e.Message.Text.Trim()); Chat chat = _telegramBotClient.GetChatAsync(chatId).Result; var addedGroup = _telegramGroupService.AddGroupIfNotExist(new dal.entities.TelegramGroup { ChatId = chat.Id, UserId = requestUser.Id, Firstname = chat.FirstName, Description = chat.Description, Lastname = chat.LastName, Title = chat.Title, Username = chat.Username, }); if (addedGroup != null) { _telegramBotClient.SendTextMessageAsync(e.Message.Chat.Id, TelegramBotCommands.CHANNEL_ADDED_INFORMATION, ParseMode.Html); } } catch (Exception ex) { _logService.InsertLog(ex, enums.LogLevel.TELEGRAM); _telegramBotClient.SendTextMessageAsync(e.Message.Chat.Id, TelegramBotCommands.INSERT_CHANNEL_INFORMATION_ERROR, ParseMode.Html); } } else if (ValidationHelper.IsRss(e.Message.Text, _logService)) { var userRss = _userRssService.AddRssIfNotExist(new dal.entities.UserRss { Url = e.Message.Text.Trim(), UserId = requestUser.Id, }); if (userRss != null) { _telegramBotClient.SendTextMessageAsync(e.Message.Chat.Id, TelegramBotCommands.RSS_ADDED_INFORMATION, ParseMode.Html); } } else { _telegramBotClient.SendTextMessageAsync(e.Message.Chat.Id, TelegramBotCommands.COMMAND_NOT_FOUND, ParseMode.Html); } } else if (e.Message.Type == MessageType.GroupCreated || e.Message.Type == MessageType.ChatMembersAdded) { var addedGroup = _telegramGroupService.AddGroupIfNotExist(new dal.entities.TelegramGroup { ChatId = e.Message.Chat.Id, UserId = requestUser.Id, Firstname = e.Message.Chat.FirstName, Lastname = e.Message.Chat.LastName, Description = e.Message.Chat.Description, Title = e.Message.Chat.Title, Username = e.Message.Chat.Username, }); } }); }