/// <summary> /// Resctrict user. /// </summary> /// <param name="chatId">Chat id.</param> /// <param name="userid">User id.</param> /// <param name="until">Rescrict until.</param> /// <param name="canWriteMessages">Can write messages or not.</param> public Task RestrictUserAsync(long chatId, int userid, DateTime until, bool canWriteMessages = false) { try { var permissions = new ChatPermissions { CanAddWebPagePreviews = canWriteMessages, CanChangeInfo = canWriteMessages, CanInviteUsers = canWriteMessages, CanPinMessages = canWriteMessages, CanSendMediaMessages = canWriteMessages, CanSendMessages = canWriteMessages, CanSendOtherMessages = canWriteMessages, CanSendPolls = canWriteMessages }; return(RestrictChatMemberAsync( chatId: chatId, userId: userid, untilDate: until, permissions: permissions)); } catch (Exception exp) { Logger.Log(LogType.Error, $"Exception: {exp.Message}\nTrace: {exp.StackTrace}"); return(default);
private async void SendExecute() { var chat = _chat; if (chat == null) { return; } var permissions = new ChatPermissions { CanChangeInfo = _canChangeInfo, CanPinMessages = _canPinMessages, CanInviteUsers = _canInviteUsers, CanAddWebPagePreviews = _canAddWebPagePreviews, CanSendPolls = _canSendPolls, CanSendOtherMessages = _canSendOtherMessages, CanSendMediaMessages = _canSendMediaMessages, CanSendMessages = _canSendMessages }; var response = await ProtoService.SendAsync(new SetChatPermissions(chat.Id, permissions)); if (response is Error error) { } else { NavigationService.GoBack(); NavigationService.Frame.ForwardStack.Clear(); } }
public async Task RestrictMemberAsync(int userId, bool unMute = false, DateTime until = default) { var chatId = Message.Chat.Id; var untilDate = until; if (until == default) { untilDate = DateTime.UtcNow.AddDays(366); } Log.Information($"Restricting member on {chatId} until {untilDate}"); Log.Information($"UserId: {userId}, IsMute: {unMute}"); var permission = new ChatPermissions { CanSendMessages = unMute, CanSendMediaMessages = unMute, CanSendOtherMessages = unMute, CanAddWebPagePreviews = unMute, CanChangeInfo = unMute, CanInviteUsers = unMute, CanPinMessages = unMute, CanSendPolls = unMute }; Log.Information($"ChatPermissions: {permission.ToJson(true)}"); if (unMute) { untilDate = DateTime.UtcNow; } await Client.RestrictChatMemberAsync(chatId, userId, permission, untilDate) .ConfigureAwait(false); }
/// <summary> /// Initializes a new request with chatId, userId and new user permissions /// </summary> /// <param name="chatId">Unique identifier for the target chat or username of the target supergroup</param> /// <param name="userId">Unique identifier of the target user</param> /// <param name="permissions">New user permissions</param> public RestrictChatMemberRequest(ChatId chatId, long userId, ChatPermissions permissions) : base("restrictChatMember") { ChatId = chatId; UserId = userId; Permissions = permissions; }
public async void OnExecution(object sender, CommandEventArgs command) { if (command.Message.Chat.Type != ChatType.Private) { return; } try { var bot = sender as Pieprz; var permissions = new ChatPermissions { CanAddWebPagePreviews = true, CanChangeInfo = true, CanInviteUsers = true, CanPinMessages = true, CanSendMediaMessages = true, CanSendMessages = true, CanSendOtherMessages = true, CanSendPolls = true }; await bot.RestrictChatMemberAsync( chatId : OfftopiaId, userId : command.Message.From.Id, untilDate : DbConverter.DateTimeUtc2.AddSeconds(40), permissions : permissions); } catch (Exception exp) { Logger.Log(LogType.Error, $"Exception: {exp.Message}\nTrace: {exp.StackTrace}"); } }
/// <summary> /// Changes the chat members permissions. Supported only for basic groups and supergroups. Requires can_restrict_members administrator right /// </summary> public static Task <Ok> SetChatPermissionsAsync( this Client client, long chatId = default, ChatPermissions permissions = default) { return(client.ExecuteAsync(new SetChatPermissions { ChatId = chatId, Permissions = permissions })); }
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 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 virtual async Task ChangeChatPermissions(ChatPermissions permissions) { try { await this.Client.TelegramClient.SetChatPermissionsAsync(this.DeviceId, permissions); } catch { } }
public virtual async Task ChangeChatPermissions(ChatPermissions permissions) { try { await API(a => a.SetChatPermissionsAsync(this.DeviceId, permissions)); } catch { } }
public virtual async Task RestrictUser(int userId, ChatPermissions permissions, DateTime until = default(DateTime)) { try { await API(a => a.RestrictChatMemberAsync(this.DeviceId, userId, permissions, until)); } catch { } }
public override async Task Execute(Message message) { var promotedMembers = await _chatService.GetPromotedMembersAsync(message.Chat.Id); bool isAdmin = await message.From.IsAdmin(message.Chat.Id); bool isPromotedChatMember = promotedMembers?.Any(member => member.UserId == message.From.Id) == true; if (!(isAdmin || isPromotedChatMember)) { await DevSilenceKeeper.BotClient.SendTextMessageAsync( message.Chat.Id, "Розмутить могут только модераторы и участники чата с привилегиями!", replyToMessageId : message.MessageId); return; } isAdmin = await message.ReplyToMessage.From.IsAdmin(message.Chat.Id); if (isAdmin) { await DevSilenceKeeper.BotClient.SendTextMessageAsync( message.Chat.Id, "Ничосе!. Админа розмутить пытаются...", replyToMessageId : message.MessageId); return; } var unmutePermissions = new ChatPermissions { CanSendMessages = true, CanSendMediaMessages = true, CanSendOtherMessages = true, CanSendPolls = true, CanAddWebPagePreviews = true, CanInviteUsers = true }; await DevSilenceKeeper.BotClient.RestrictChatMemberAsync( message.Chat.Id, message.ReplyToMessage.From.Id, unmutePermissions, DateTime.Now); await DevSilenceKeeper.BotClient.SendTextMessageAsync( message.Chat.Id, $"{message.ReplyToMessage.From} розмучен", replyToMessageId : message.MessageId); }
/// <summary> /// Updates user permissions /// </summary> public static async Task <bool> UpdatePermissions(long chatId, long userId, ChatPermissions permissions) { try { await api.RestrictChatMemberAsync(chatId, userId, permissions); return(true); } catch (Exception e) { Log.Error(e.ToString()); return(false); } }
public static async void UserControl(object sender, MessageEventArgs e) { var message = e.Message; long Chat_Id = e.Message.Chat.Id; if (message.Text is null) { return; } try { ChatMember admin = new ChatMember(); ChatPermissions chatPermissions = new ChatPermissions(); admin = Program.botClient.GetChatMemberAsync(Chat_Id, userId: message.From.Id).Result; // Информация об одном из участников чата if (message.ReplyToMessage != null && String.Equals(message.Text, "Бан", StringComparison.CurrentCultureIgnoreCase) && admin.CanRestrictMembers == true && e.Message.ReplyToMessage.From.Id != 1234567890 || message.ReplyToMessage != null && String.Equals(message.Text, "Бан", StringComparison.CurrentCultureIgnoreCase) && admin.Status == ChatMemberStatus.Creator) { // бан пользователю, которому был реплай (и поставить id бота чтобы администрация не забанила бота) await Program.botClient.SendTextMessageAsync(Chat_Id, $"[{message.From.FirstName}](tg://user?id={message.From.Id}) забанил участника [{message.ReplyToMessage.From.FirstName}](tg://user?id={e.Message.ReplyToMessage.From.Id}) *({e.Message.ReplyToMessage.From.Id})*", parseMode : ParseMode.Markdown); await Program.botClient.KickChatMemberAsync(Chat_Id, userId : e.Message.ReplyToMessage.From.Id); } if (message.ReplyToMessage != null && String.Equals(message.Text, "Кик", StringComparison.CurrentCultureIgnoreCase) && admin.CanRestrictMembers == true && message.ReplyToMessage.From.Id != 1238720093 || message.ReplyToMessage != null && String.Equals(message.Text, "Кик", StringComparison.CurrentCultureIgnoreCase) && admin.Status == ChatMemberStatus.Creator) { await Program.botClient.SendTextMessageAsync(message.Chat.Id, $"[{message.From.FirstName}](tg://user?id={message.From.Id}) кикнул участника [{message.ReplyToMessage.From.FirstName}](tg://user?id={message.ReplyToMessage.From.Id})", parseMode : ParseMode.Markdown); await Program.botClient.KickChatMemberAsync(message.Chat.Id, userId : message.ReplyToMessage.From.Id); // бан пользователЮ, которому был реплай await Program.botClient.UnbanChatMemberAsync(message.Chat.Id, userId : message.ReplyToMessage.From.Id); // разбан того же пользователя } } catch (ApiRequestException) { await Program.botClient.SendTextMessageAsync(message.Chat.Id, $"Почему ты такой злой?!"); } catch (Exception) { } try { ChatMember admin = new ChatMember(); admin = Program.botClient.GetChatMemberAsync(Chat_Id, userId: message.From.Id).Result; // Информация об одном из участников чата ChatPermissions chatPermissions = new ChatPermissions(); if (message.ReplyToMessage != null && message.Text.StartsWith(".мут", StringComparison.CurrentCultureIgnoreCase) && admin.CanRestrictMembers == true || message.ReplyToMessage != null && message.Text.StartsWith(".мут", StringComparison.CurrentCultureIgnoreCase) && admin.Status == ChatMemberStatus.Creator) {// мут пользователю, которому был реплай String[] mute = message.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); uint mutes = Convert.ToUInt32(mute[^ 1]);
private static void _Unban(TelegramBotClient client, Chat chat, User user) { var permissions = new ChatPermissions() { CanAddWebPagePreviews = true, CanChangeInfo = true, CanInviteUsers = true, CanPinMessages = true, CanSendMediaMessages = true, CanSendMessages = true, CanSendOtherMessages = true, CanSendPolls = true }; client.RestrictChatMemberAsync(chat.Id, user.Id, permissions); }
internal static async Task Mute(int time, TelegramBotAbstract telegramBotClient, long chatId, int userId) { var permissions = new ChatPermissions { CanSendMessages = false, CanInviteUsers = true, CanSendOtherMessages = false, CanSendPolls = false, CanAddWebPagePreviews = false, CanChangeInfo = false, CanPinMessages = false, CanSendMediaMessages = false }; var untilDate = DateTime.Now.AddSeconds(time); await telegramBotClient.RestrictChatMemberAsync(chatId, userId, permissions, untilDate); }
private ChatPermissions CreateChatPermissions(ChatMember?preBanPermissions, ChatPermissions?defaultPermissions) { var postBanPermissions = new ChatPermissions { CanAddWebPagePreviews = Check(preBanPermissions.CanAddWebPagePreviews, defaultPermissions?.CanAddWebPagePreviews), CanChangeInfo = Check(preBanPermissions.CanChangeInfo, defaultPermissions?.CanChangeInfo), CanInviteUsers = Check(preBanPermissions.CanInviteUsers, defaultPermissions?.CanInviteUsers), CanPinMessages = Check(preBanPermissions.CanPinMessages, defaultPermissions?.CanPinMessages), CanSendMediaMessages = Check(preBanPermissions.CanSendMediaMessages, defaultPermissions?.CanSendMediaMessages), CanSendMessages = Check(preBanPermissions.CanSendMessages, defaultPermissions?.CanSendMessages), CanSendOtherMessages = Check(preBanPermissions.CanSendOtherMessages, defaultPermissions?.CanSendOtherMessages), CanSendPolls = Check(preBanPermissions.CanSendPolls, defaultPermissions?.CanSendPolls) }; return(postBanPermissions); }
private static async Task Mute2Async(DateTime?untilDate, TelegramBotAbstract telegramBotClient, long chatId, int userId, ChatType?chatType) { var permissions = new ChatPermissions { CanSendMessages = false, CanInviteUsers = true, CanSendOtherMessages = false, CanSendPolls = false, CanAddWebPagePreviews = false, CanChangeInfo = false, CanPinMessages = false, CanSendMediaMessages = false }; if (untilDate == null) { await telegramBotClient.RestrictChatMemberAsync(chatId, userId, permissions, default, chatType);
public SupergroupAdminBotTestsFixture(TestsFixture testsFixture) { TestsFixture = testsFixture; PinnedMessages = new List <Message>(3); AddLifetime( initialize: async() => { Chat chat = await TestsFixture.BotClient.GetChatAsync(TestsFixture.SupergroupChat); // Save existing chat photo as byte[] to restore it later because Bot API 4.4+ invalidates old // file_ids after changing chat photo if (!string.IsNullOrEmpty(chat.Photo?.BigFileId)) { await using MemoryStream stream = new(); await TestsFixture.BotClient.GetInfoAndDownloadFileAsync(chat.Photo.BigFileId, stream); _oldChatPhoto = stream.ToArray(); } // Save default permissions so they can be restored ExistingDefaultPermissions = chat.Permissions; }, dispose: async() => { // If chat had a photo before, reset the photo back. if (_oldChatPhoto is not null) { await using MemoryStream photoStream = new(_oldChatPhoto); await TestsFixture.BotClient.SetChatPhotoAsync( chatId: Chat.Id, photo: photoStream ); } // Reset original default permissions await TestsFixture.BotClient.SetChatPermissionsAsync( TestsFixture.SupergroupChat, ExistingDefaultPermissions ); } ); }
public override async Task Execute(CallbackQuery query) { var queryData = new CallbackQueryData(query.Data); if (query.From.Id != queryData.UserId) { var expectedChatMember = await DevSilenceKeeper.BotClient.GetChatMemberAsync(query.Message.Chat.Id, queryData.UserId); await DevSilenceKeeper.BotClient.AnswerCallbackQueryAsync( query.Id, $"Эту кнопку должен нажать определенный участник чата — {expectedChatMember.User}.", true); return; } var unmutePermissions = new ChatPermissions { CanSendMessages = true, CanSendMediaMessages = true, CanSendOtherMessages = true, CanSendPolls = true, CanAddWebPagePreviews = true, CanInviteUsers = true }; await DevSilenceKeeper.BotClient.RestrictChatMemberAsync( query.Message.Chat.Id, query.From.Id, unmutePermissions, DateTime.Now); DevSilenceKeeper.BotClient.SendTextMessageAsync( query.Message.Chat.Id, $"[{query.From}](tg://user?id={query.From.Id}) теперь ты полноценный участник чата!", ParseMode.Markdown) .Wait(); await DevSilenceKeeper.BotClient.DeleteMessageAsync( query.Message.Chat.Id, query.Message.MessageId); }
public async Task InitializeAsync() { Chat chat = await TestsFixture.BotClient .GetChatAsync(TestsFixture.SupergroupChat); // Save existing chat photo as byte[] to restore it later because Bot API 4.4+ invalidates old // file_ids after changing chat photo if (!string.IsNullOrEmpty(chat.Photo?.BigFileId)) { using (MemoryStream stream = new MemoryStream()) { await TestsFixture.BotClient .GetInfoAndDownloadFileAsync(chat.Photo.BigFileId, stream); _oldChatPhoto = stream.ToArray(); } } // Save default permissions so they can be restored ExistingDefaultPermissions = chat.Permissions; }
public async Task Should_Set_New_Default_Permissions() { ChatPermissions newDefaultPermissions = new ChatPermissions() { CanInviteUsers = false, CanSendMediaMessages = true, CanChangeInfo = false, CanSendMessages = true, CanPinMessages = false, CanSendPolls = false, CanSendOtherMessages = false, CanAddWebPagePreviews = false }; await BotClient.SetChatPermissionsAsync(_classFixture.Chat.Id, newDefaultPermissions); Chat supergroup = await BotClient.GetChatAsync(_classFixture.Chat.Id); ChatPermissions setChatPermissions = supergroup.Permissions; Asserts.JsonEquals(newDefaultPermissions, setChatPermissions); }
private static void _BanInChat(TelegramBotClient client, Chat chat, User user, int replyMessageId = 0, DateTime untilDate = default) { var permissions = new ChatPermissions() { CanSendMediaMessages = false, CanSendMessages = false, CanSendOtherMessages = false }; client.RestrictChatMemberAsync(chat.Id, user.Id, permissions, untilDate); if (replyMessageId > 0) { client.SendTextMessageAsync(chat.Id, $"{user.GetMension()} будет забанен!", replyToMessageId: replyMessageId, parseMode: ParseMode.Markdown); } var member = BotDbContext.Get().GetMember(chat.Id, user.Id); member.Warns = 0; BotDbContext.Get().Entry(member).State = System.Data.Entity.EntityState.Modified; BotDbContext.Get().SaveChanges(); }
private static string formatUserPermissions(ChatPermissions rights, ChatPermissions defaultBannedRights) { if (rights == null) { return(""); } StringBuilder builder = new StringBuilder(); //if (rights.view_messages && defaultBannedRights.view_messages != rights.view_messages) //{ // builder.append(Strings.Resources.UserRestrictionsNoRead); //} if (rights.CanSendMessages && defaultBannedRights.CanSendMessages != rights.CanSendMessages) { if (builder.Length > 0) { builder.Append(", "); } builder.Append(Strings.Resources.UserRestrictionsNoSend); } if (rights.CanSendMediaMessages && defaultBannedRights.CanSendMediaMessages != rights.CanSendMediaMessages) { if (builder.Length > 0) { builder.Append(", "); } builder.Append(Strings.Resources.UserRestrictionsNoSendMedia); } if (rights.CanSendOtherMessages && defaultBannedRights.CanSendOtherMessages != rights.CanSendOtherMessages) { if (builder.Length > 0) { builder.Append(", "); } builder.Append(Strings.Resources.UserRestrictionsNoSendStickers); } if (rights.CanSendPolls && defaultBannedRights.CanSendPolls != rights.CanSendPolls) { if (builder.Length > 0) { builder.Append(", "); } builder.Append(Strings.Resources.UserRestrictionsNoSendPolls); } if (rights.CanAddWebPagePreviews && defaultBannedRights.CanAddWebPagePreviews != rights.CanAddWebPagePreviews) { if (builder.Length > 0) { builder.Append(", "); } builder.Append(Strings.Resources.UserRestrictionsNoEmbedLinks); } if (rights.CanInviteUsers && defaultBannedRights.CanInviteUsers != rights.CanInviteUsers) { if (builder.Length > 0) { builder.Append(", "); } builder.Append(Strings.Resources.UserRestrictionsNoInviteUsers); } if (rights.CanPinMessages && defaultBannedRights.CanPinMessages != rights.CanPinMessages) { if (builder.Length > 0) { builder.Append(", "); } builder.Append(Strings.Resources.UserRestrictionsNoPinMessages); } if (rights.CanChangeInfo && defaultBannedRights.CanChangeInfo != rights.CanChangeInfo) { if (builder.Length > 0) { builder.Append(", "); } builder.Append(Strings.Resources.UserRestrictionsNoChangeInfo); } if (builder.Length > 0) { //builder.Replace(0, 1, builder.ToString().Substring(0, 1).ToUpper()); //builder.Append('.'); } return(builder.ToString()); }
public override async Task OnMessage(MessageResult e) { var from = e.Message.From.Id; if (e.Message.From.IsBot) { return; } //Are urls inside his message ? if (!HasLinks(e.MessageText)) { return; } var u = await Device.GetChatUser(from); //Don't kick Admins or Creators if (u.Status == Telegram.Bot.Types.Enums.ChatMemberStatus.Administrator | u.Status == Telegram.Bot.Types.Enums.ChatMemberStatus.Creator) { await this.Device.Send("You won't get kicked,...not this time."); return; } await e.Device.DeleteMessage(e.MessageId); var cp = new ChatPermissions(); cp.CanAddWebPagePreviews = false; cp.CanChangeInfo = false; cp.CanInviteUsers = false; cp.CanPinMessages = false; cp.CanSendMediaMessages = false; cp.CanSendMessages = false; cp.CanSendOtherMessages = false; cp.CanSendPolls = false; //Collect user "mistakes" with sending url, after 3 he gets kicked out. if (Counter.ContainsKey(from)) { Counter[from]++; } else { Counter[from] = 1; } if (Counter[from] >= 3) { await e.Device.KickUser(from); await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName + " has been removed from the group"); } else { await e.Device.RestrictUser(from, cp, DateTime.UtcNow.AddSeconds(30)); await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName + " has been blocked for 30 seconds"); } }
public Task SetChatPermissionsAsync( ChatId chatId, ChatPermissions permissions, CancellationToken cancellationToken = new CancellationToken()) => throw new NotImplementedException();
/// <summary>Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success.</summary> /// <param name="bot">BotClient</param> /// <param name="chatId">Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)</param> /// <param name="userId">Unique identifier of the target user</param> /// <param name="permissions">A JSON-serialized object for new user permissions</param> /// <param name="untilDate">Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever</param> /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> public static async Task <bool> RestrictChatMemberAsync(this BotClient bot, string chatId, long userId, ChatPermissions permissions, [Optional] uint?untilDate, [Optional] CancellationToken cancellationToken) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } var args = new RestrictChatMemberArgs { ChatId = chatId, UserId = userId, Permissions = permissions, UntilDate = untilDate }; return(await bot.RPCA <bool>(MethodNames.RestrictChatMember, args, cancellationToken : cancellationToken).ConfigureAwait(false)); }
/// <summary>Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success.</summary> /// <param name="bot">BotClient</param> /// <param name="chatId">Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)</param> /// <param name="userId">Unique identifier of the target user</param> /// <param name="permissions">A JSON-serialized object for new user permissions</param> /// <param name="untilDate">Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever</param> /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> public static bool RestrictChatMember(this BotClient bot, string chatId, long userId, ChatPermissions permissions, [Optional] uint?untilDate) { if (bot == null) { throw new NullReferenceException(nameof(bot)); } var args = new RestrictChatMemberArgs { ChatId = chatId, UserId = userId, Permissions = permissions, UntilDate = untilDate }; return(bot.RPC <bool>(MethodNames.RestrictChatMember, args)); }
private MessageContent GetMessageContent(ChatEvent item) { if (item.Action is ChatEventDescriptionChanged descriptionChanged) { var text = new FormattedText(descriptionChanged.NewDescription, new TextEntity[0]); var webPage = string.IsNullOrEmpty(descriptionChanged.OldDescription) ? null : new WebPage { SiteName = Strings.Resources.EventLogPreviousGroupDescription, Description = new FormattedText { Text = descriptionChanged.OldDescription } }; return(new MessageText(text, webPage)); } else if (item.Action is ChatEventUsernameChanged usernameChanged) { var link = string.IsNullOrEmpty(usernameChanged.NewUsername) ? string.Empty : MeUrlPrefixConverter.Convert(_protoService, usernameChanged.NewUsername); var text = new FormattedText(link, new[] { new TextEntity(0, link.Length, new TextEntityTypeUrl()) }); var webPage = string.IsNullOrEmpty(usernameChanged.OldUsername) ? null : new WebPage { SiteName = Strings.Resources.EventLogPreviousLink, Description = new FormattedText { Text = MeUrlPrefixConverter.Convert(_protoService, usernameChanged.OldUsername) } }; return(new MessageText(text, webPage)); } else if (item.Action is ChatEventPermissionsChanged permissionChanged) { var text = string.Empty; var entities = new List <TextEntity>(); ChatPermissions o = permissionChanged.OldPermissions; ChatPermissions n = permissionChanged.NewPermissions; if (o == null) { o = new ChatPermissions(); } if (n == null) { n = new ChatPermissions(); } var rights = new StringBuilder(Strings.Resources.EventLogDefaultPermissions); var added = false; void AppendChange(bool value, string label) { if (!added) { rights.Append('\n'); added = true; } rights.Append('\n').Append(value ? '+' : '-').Append(' '); rights.Append(label); } //if (o.IsViewMessages != n.IsViewMessages) //{ // AppendChange(n.IsViewMessages, Strings.Resources.EventLogRestrictedReadMessages); //} if (o.CanSendMessages != n.CanSendMessages) { AppendChange(n.CanSendMessages, Strings.Resources.EventLogRestrictedSendMessages); } if (o.CanSendOtherMessages != n.CanSendOtherMessages) { AppendChange(n.CanSendOtherMessages, Strings.Resources.EventLogRestrictedSendStickers); } if (o.CanSendMediaMessages != n.CanSendMediaMessages) { AppendChange(n.CanSendMediaMessages, Strings.Resources.EventLogRestrictedSendMedia); } if (o.CanSendPolls != n.CanSendPolls) { AppendChange(n.CanSendPolls, Strings.Resources.EventLogRestrictedSendPolls); } if (o.CanAddWebPagePreviews != n.CanAddWebPagePreviews) { AppendChange(n.CanAddWebPagePreviews, Strings.Resources.EventLogRestrictedSendEmbed); } if (o.CanChangeInfo != n.CanChangeInfo) { AppendChange(n.CanChangeInfo, Strings.Resources.EventLogRestrictedChangeInfo); } if (o.CanInviteUsers != n.CanInviteUsers) { AppendChange(n.CanInviteUsers, Strings.Resources.EventLogRestrictedSendEmbed); } if (o.CanPinMessages != n.CanPinMessages) { AppendChange(n.CanPinMessages, Strings.Resources.EventLogRestrictedPinMessages); } text = rights.ToString(); return(new MessageText(new FormattedText(text, entities), null)); } else if (item.Action is ChatEventMemberRestricted memberRestricted) { var text = string.Empty; var entities = new List <TextEntity>(); var whoUser = _protoService.GetUser(memberRestricted.UserId); ChatMemberStatusRestricted o = null; ChatMemberStatusRestricted n = null; if (memberRestricted.OldStatus is ChatMemberStatusRestricted oldRestricted) { o = oldRestricted; } else if (memberRestricted.OldStatus is ChatMemberStatusBanned oldBanned) { o = new ChatMemberStatusRestricted(false, oldBanned.BannedUntilDate, new ChatPermissions(false, false, false, false, false, false, false, false)); } else if (memberRestricted.OldStatus is ChatMemberStatusMember) { o = new ChatMemberStatusRestricted(true, 0, new ChatPermissions(true, true, true, true, true, true, true, true)); } if (memberRestricted.NewStatus is ChatMemberStatusRestricted newRestricted) { n = newRestricted; } else if (memberRestricted.NewStatus is ChatMemberStatusBanned newBanned) { n = new ChatMemberStatusRestricted(false, newBanned.BannedUntilDate, new ChatPermissions(false, false, false, false, false, false, false, false)); } else if (memberRestricted.NewStatus is ChatMemberStatusMember) { n = new ChatMemberStatusRestricted(true, 0, new ChatPermissions(true, true, true, true, true, true, true, true)); } if (!_channel && (n == null || n != null && o != null /*&& n.RestrictedUntilDate != o.RestrictedUntilDate*/)) { StringBuilder rights; String bannedDuration; if (n != null && !n.IsForever()) { bannedDuration = ""; int duration = n.RestrictedUntilDate - item.Date; int days = duration / 60 / 60 / 24; duration -= days * 60 * 60 * 24; int hours = duration / 60 / 60; duration -= hours * 60 * 60; int minutes = duration / 60; int count = 0; for (int a = 0; a < 3; a++) { String addStr = null; if (a == 0) { if (days != 0) { addStr = Locale.Declension("Days", days); count++; } } else if (a == 1) { if (hours != 0) { addStr = Locale.Declension("Hours", hours); count++; } } else { if (minutes != 0) { addStr = Locale.Declension("Minutes", minutes); count++; } } if (addStr != null) { if (bannedDuration.Length > 0) { bannedDuration += ", "; } bannedDuration += addStr; } if (count == 2) { break; } } } else { bannedDuration = Strings.Resources.UserRestrictionsUntilForever; } var str = Strings.Resources.EventLogRestrictedUntil; rights = new StringBuilder(String.Format(str, GetUserName(whoUser, entities, str.IndexOf("{0}")), bannedDuration)); var added = false; if (o == null) { o = new ChatMemberStatusRestricted(true, 0, new ChatPermissions(true, true, true, true, true, true, true, true)); } if (n == null) { n = new ChatMemberStatusRestricted(true, 0, new ChatPermissions(true, true, true, true, true, true, true, true)); } void AppendChange(bool value, string label) { if (!added) { rights.Append('\n'); added = true; } rights.Append('\n').Append(value ? '+' : '-').Append(' '); rights.Append(label); } //if (o.IsViewMessages != n.IsViewMessages) //{ // AppendChange(n.IsViewMessages, Strings.Resources.EventLogRestrictedReadMessages); //} if (o.Permissions.CanSendMessages != n.Permissions.CanSendMessages) { AppendChange(n.Permissions.CanSendMessages, Strings.Resources.EventLogRestrictedSendMessages); } if (o.Permissions.CanSendOtherMessages != n.Permissions.CanSendOtherMessages) { AppendChange(n.Permissions.CanSendOtherMessages, Strings.Resources.EventLogRestrictedSendStickers); } if (o.Permissions.CanSendMediaMessages != n.Permissions.CanSendMediaMessages) { AppendChange(n.Permissions.CanSendMediaMessages, Strings.Resources.EventLogRestrictedSendMedia); } if (o.Permissions.CanSendPolls != n.Permissions.CanSendPolls) { AppendChange(n.Permissions.CanSendPolls, Strings.Resources.EventLogRestrictedSendPolls); } if (o.Permissions.CanAddWebPagePreviews != n.Permissions.CanAddWebPagePreviews) { AppendChange(n.Permissions.CanAddWebPagePreviews, Strings.Resources.EventLogRestrictedSendEmbed); } if (o.Permissions.CanChangeInfo != n.Permissions.CanChangeInfo) { AppendChange(n.Permissions.CanChangeInfo, Strings.Resources.EventLogRestrictedChangeInfo); } if (o.Permissions.CanInviteUsers != n.Permissions.CanInviteUsers) { AppendChange(n.Permissions.CanInviteUsers, Strings.Resources.EventLogRestrictedSendEmbed); } if (o.Permissions.CanPinMessages != n.Permissions.CanPinMessages) { AppendChange(n.Permissions.CanPinMessages, Strings.Resources.EventLogRestrictedPinMessages); } text = rights.ToString(); } else { String str; if (o == null || memberRestricted.NewStatus is ChatMemberStatusBanned) { str = Strings.Resources.EventLogChannelRestricted; } else { str = Strings.Resources.EventLogChannelUnrestricted; } text = String.Format(str, GetUserName(whoUser, entities, str.IndexOf("{0}"))); } return(new MessageText(new FormattedText(text, entities), null)); } else if (item.Action is ChatEventMemberPromoted memberPromoted) { var entities = new List <TextEntity>(); var whoUser = _protoService.GetUser(memberPromoted.UserId); var str = Strings.Resources.EventLogPromoted; var userName = GetUserName(whoUser, entities, str.IndexOf("{0}")); var builder = new StringBuilder(string.Format(str, userName)); var added = false; ChatMemberStatusAdministrator o = null; ChatMemberStatusAdministrator n = null; if (memberPromoted.OldStatus is ChatMemberStatusAdministrator oldAdmin) { o = oldAdmin; } if (memberPromoted.NewStatus is ChatMemberStatusAdministrator newAdmin) { n = newAdmin; } if (o == null) { o = new ChatMemberStatusAdministrator(); } if (n == null) { n = new ChatMemberStatusAdministrator(); } void AppendChange(bool value, string label) { if (!added) { builder.Append('\n'); added = true; } builder.Append('\n').Append(value ? '+' : '-').Append(' '); builder.Append(label); } if (o.CanChangeInfo != n.CanChangeInfo) { AppendChange(n.CanChangeInfo, _channel ? Strings.Resources.EventLogPromotedChangeChannelInfo : Strings.Resources.EventLogPromotedChangeGroupInfo); } if (_channel) { if (o.CanPostMessages != n.CanPostMessages) { AppendChange(n.CanPostMessages, Strings.Resources.EventLogPromotedPostMessages); } if (o.CanEditMessages != n.CanEditMessages) { AppendChange(n.CanEditMessages, Strings.Resources.EventLogPromotedEditMessages); } } if (o.CanDeleteMessages != n.CanDeleteMessages) { AppendChange(n.CanDeleteMessages, Strings.Resources.EventLogPromotedDeleteMessages); } if (o.CanPromoteMembers != n.CanPromoteMembers) { AppendChange(n.CanPromoteMembers, Strings.Resources.EventLogPromotedAddAdmins); } if (!_channel) { if (o.CanRestrictMembers != n.CanRestrictMembers) { AppendChange(n.CanRestrictMembers, Strings.Resources.EventLogPromotedBanUsers); } } if (o.CanInviteUsers != n.CanInviteUsers) { AppendChange(n.CanInviteUsers, Strings.Resources.EventLogPromotedAddUsers); } if (!_channel) { if (o.CanPinMessages != n.CanPinMessages) { AppendChange(n.CanPinMessages, Strings.Resources.EventLogPromotedPinMessages); } } return(new MessageText(new FormattedText(builder.ToString(), entities), null)); } return(new MessageChatEvent(item, true)); }
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); }