Files
telegram-bot/modules/UserGroupTag/Handler.cs
T
2023-07-29 15:03:45 +03:00

107 lines
3.7 KiB
C#

#nullable enable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BotFramework;
using BotFramework.Attributes;
using BotFramework.Enums;
using BotFramework.Utils;
using Kruzya.TelegramBot.Core.Cache;
using Kruzya.TelegramBot.Core.Data;
using Kruzya.TelegramBot.Core.Extensions;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace UserGroupTag
{
public class Handler : BotEventHandler
{
private readonly CoreContext _db;
private readonly ICacheStorage<long, User> _userCache;
public Handler(CoreContext db, ICacheStorage<long, User> userCache)
{
_db = db;
_userCache = userCache;
}
[InChat(InChat.Public)]
[ParametrizedCommand("add_group", CommandParseMode.Both)]
public async Task HandleAddGroup(string groupName)
{
// var groupName = group.Text;
var repliedMessage = RawUpdate.Message!.ReplyToMessage;
if (repliedMessage == null || repliedMessage.From!.IsBot || !(await Bot.CanPunishMember(Chat, From)) || string.IsNullOrEmpty(groupName))
{
return;
}
var from = repliedMessage.From;
var fromId = from.Id;
var chatId = Chat!.Id;
var userGroupOption = await _db.UserValues.FindOrCreateOption(Chat.Id, "userGroups");
var tagDictionary = userGroupOption.GetValue(new Dictionary<string, List<long>>());
var memberList = tagDictionary.GetValueOrDefault(groupName, new List<long>());
if (memberList.Contains(fromId))
{
await Bot.SendTextMessageAsync(chatId, $"{from.ToHtml()} уже находится в группе {groupName}",
parseMode: ParseMode.Html);
return;
}
memberList.Add(repliedMessage.From.Id);
tagDictionary[groupName] = memberList;
userGroupOption.SetValue(tagDictionary);
_db.AddOrUpdate(userGroupOption);
_userCache.SetValue(repliedMessage.From.Id, repliedMessage.From, Int32.MaxValue);
await Bot.SendTextMessageAsync(chatId, $"{from.ToHtml()} добавлен в группу {groupName}",
parseMode: ParseMode.Html);
}
[InChat(InChat.Public)]
[ParametrizedCommand("tag_group", CommandParseMode.Both)]
public async Task HandleTagGroup(string groupName)
{
if (string.IsNullOrEmpty(groupName))
{
return;
}
var userGroupOption = await _db.UserValues.FindOption(Chat.Id, "userGroups");
var userList = userGroupOption?.GetValue<Dictionary<string, List<long>>>()?[groupName];
if (userList == null || userList.Count == 0)
{
return;
}
var msg = new HtmlString()
.Text("Пользователь ")
.UserMention(From)
.Text($" призывает группу пользователей {groupName}: ");
foreach (var userId in userList)
{
msg.UserMention(await GetUser(userId, Chat)).Text(", ");
}
await Bot.SendTextMessageAsync(Chat.Id, msg.ToString().TrimEnd(',', ' '), parseMode: ParseMode.Html);
}
protected async Task<User> GetUser(long userId, Chat chat)
{
User user;
if (!_userCache.TryGetValue(userId, out user))
{
user = (await Bot.GetChatMemberAsync(Chat.Id, userId)).User;
_userCache.SetValue(userId, user, Int32.MaxValue);
}
return user;
}
}
}