Compare commits
3
Commits
608c79d3de
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5acf3f9c96 | ||
|
|
34efa36d8b | ||
|
|
a205f274b5 |
@@ -438,3 +438,4 @@ FodyWeavers.xsd
|
||||
# JetBrains Rider
|
||||
*.sln.iml
|
||||
|
||||
unique_contacts_backup/*
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"cSpell.enabled": false
|
||||
}
|
||||
@@ -9,6 +9,7 @@ public class Employee
|
||||
public string Department { get; set; } = string.Empty; // Название отдела
|
||||
public string DepartmentCode { get; set; } = string.Empty; // Код отдела
|
||||
public string Position { get; set; } = string.Empty; // Должность
|
||||
public bool Birthday { get; set; } = false;
|
||||
public string? Phone { get; set; } // Опциональное поле для телефона
|
||||
public string? Mobile { get; set; } // Опциональное поле для хранения номера мобильного телефона
|
||||
public string? Mail { get; set; } // Опциональное поле для электронной почты
|
||||
|
||||
+15
-8
@@ -3,6 +3,7 @@
|
||||
public class EmployeeContact
|
||||
{
|
||||
public static string GeneralPhoneNumber => "+78123352577";
|
||||
|
||||
public EmployeeContact(Employee employee)
|
||||
{
|
||||
FullName = employee.FullName;
|
||||
@@ -11,16 +12,20 @@ public class EmployeeContact
|
||||
{
|
||||
LastName = nameParts[0];
|
||||
FirstName = nameParts[1];
|
||||
ShortName = $"{LastName} {FirstName}";
|
||||
}
|
||||
else
|
||||
{
|
||||
FirstName = FullName;
|
||||
ShortName = FullName;
|
||||
LastName = string.Empty;
|
||||
}
|
||||
Department = employee.Department;
|
||||
Position = employee.Position;
|
||||
ExtensionNumber = employee.Phone ?? null; //string.IsNullOrEmpty(employee.Phone) ? null : employee.Phone;
|
||||
Phone = string.IsNullOrEmpty(ExtensionNumber) ? GeneralPhoneNumber : $"{GeneralPhoneNumber},{ExtensionNumber}";
|
||||
Phone = string.IsNullOrEmpty(ExtensionNumber)
|
||||
? GeneralPhoneNumber
|
||||
: $"{GeneralPhoneNumber},{ExtensionNumber}";
|
||||
if (!string.IsNullOrEmpty(employee.Mobile))
|
||||
{
|
||||
Mobile = employee.Mobile;
|
||||
@@ -34,13 +39,14 @@ public class EmployeeContact
|
||||
{
|
||||
get
|
||||
{
|
||||
string text = "BEGIN:VCARD\n"
|
||||
+ "VERSION:2.1\n"
|
||||
+ $"N:{LastName};{FirstName}\n"
|
||||
+ $"FN:{FullName}\n"
|
||||
+ "ORG:NSSZ\n"
|
||||
+ $"ROLE:{Department}\n"
|
||||
+ $"TITLE:{Position}\n";
|
||||
string text =
|
||||
"BEGIN:VCARD\n"
|
||||
+ "VERSION:2.1\n"
|
||||
+ $"N:{LastName};{FirstName}\n"
|
||||
+ $"FN:{FullName}\n"
|
||||
+ "ORG:NSSZ\n"
|
||||
+ $"ROLE:{Department}\n"
|
||||
+ $"TITLE:{Position}\n";
|
||||
if (!string.IsNullOrEmpty(Mobile))
|
||||
text += $"TEL;CELL:{Mobile}\n";
|
||||
|
||||
@@ -56,6 +62,7 @@ public class EmployeeContact
|
||||
}
|
||||
}
|
||||
public string FullName { get; set; } // Полное имя сотрудника
|
||||
public string ShortName { get; set; }
|
||||
public string FirstName { get; set; }
|
||||
public string LastName { get; set; }
|
||||
public string Department { get; set; } // Название отдела
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
using StackExchange.Redis;
|
||||
|
||||
|
||||
namespace nsszcontactbot;
|
||||
public class FavoriteContactsManager
|
||||
{
|
||||
private readonly IDatabase _redisDb;
|
||||
|
||||
public FavoriteContactsManager(ConnectionMultiplexer redis)
|
||||
{
|
||||
_redisDb = redis.GetDatabase();
|
||||
}
|
||||
|
||||
private static string GetUserKey(long userId) => $"user:favorites:{userId}";
|
||||
private static string GetContactKey(string contactId) => $"contact:favorites:{contactId}";
|
||||
|
||||
/// <summary>
|
||||
/// Добавить контакт в избранное.
|
||||
/// </summary>
|
||||
public async Task AddFavoriteAsync(long userId, string contactId)
|
||||
{
|
||||
string userKey = GetUserKey(userId);
|
||||
string contactKey = GetContactKey(contactId);
|
||||
await Task.WhenAll(
|
||||
_redisDb.SetAddAsync(userKey, contactId),
|
||||
_redisDb.SetAddAsync(contactKey, userId.ToString())
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Удалить контакт из избранного.
|
||||
/// </summary>
|
||||
public async Task RemoveFavoriteAsync(long userId, string contactId)
|
||||
{
|
||||
string userKey = GetUserKey(userId);
|
||||
string contactKey = GetContactKey(contactId);
|
||||
await Task.WhenAll(
|
||||
_redisDb.SetRemoveAsync(userKey, contactId),
|
||||
_redisDb.SetRemoveAsync(contactKey, userId.ToString())
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Проверить, является ли контакт избранным.
|
||||
/// </summary>
|
||||
public async Task<bool> IsFavoriteAsync(long userId, string contactId)
|
||||
{
|
||||
string key = GetUserKey(userId);
|
||||
return await _redisDb.SetContainsAsync(key, contactId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получить список всех избранных контактов пользователя.
|
||||
/// </summary>
|
||||
public async Task<List<string>> GetAllFavoritesAsync(long userId)
|
||||
{
|
||||
string key = GetUserKey(userId);
|
||||
var members = await _redisDb.SetMembersAsync(key);
|
||||
return [.. members.Select(m => m.ToString())];
|
||||
}
|
||||
|
||||
public async Task<List<long>> GetUsersWithFavoriteAsync(string contactId)
|
||||
{
|
||||
string contactKey = GetContactKey(contactId);
|
||||
var members = await _redisDb.SetMembersAsync(contactKey);
|
||||
return [.. members.Select(m => long.Parse(m.ToString()))];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
|
||||
namespace nsszcontactbot
|
||||
{
|
||||
internal static class InlineKeyboardMarkupExtensions
|
||||
{
|
||||
internal static InlineKeyboardMarkup AddCloseButton(this InlineKeyboardMarkup markup, string text = "❌ Закрыть", bool newRow = true)
|
||||
{
|
||||
var buttonRow = newRow ? markup.AddNewRow() : markup;
|
||||
return buttonRow.AddButton(text, "close");
|
||||
}
|
||||
|
||||
internal static InlineKeyboardMarkup AddPrevPageButton(this InlineKeyboardMarkup markup, int currentPage, string context = "", string text = "⬅️ Назад")
|
||||
{
|
||||
return markup.AddButton(text, $"page/{currentPage - 1}{(string.IsNullOrEmpty(context) ? "" : "/")}{context}");
|
||||
}
|
||||
|
||||
internal static InlineKeyboardMarkup AddNextPageButton(this InlineKeyboardMarkup markup, int currentPage, string context = "", string text = "Вперед ➡️")
|
||||
{
|
||||
return markup.AddButton(text, $"page/{currentPage + 1}{(string.IsNullOrEmpty(context) ? "" : "/")}{context}");
|
||||
}
|
||||
|
||||
internal static InlineKeyboardMarkup AddPaginator(this InlineKeyboardMarkup markup, int currentPage, int totalPages, string context = "", string textPrev = "⬅️ Назад", string textNext = "Вперед ➡️")
|
||||
{
|
||||
if (totalPages > 1)
|
||||
{
|
||||
if (currentPage > 1)
|
||||
AddPrevPageButton(markup, currentPage, context, textPrev);
|
||||
if (currentPage < totalPages)
|
||||
AddNextPageButton(markup, currentPage, context, textNext);
|
||||
}
|
||||
return markup;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
[
|
||||
{
|
||||
"id": "cp",
|
||||
"fullName": "Центральная проходная",
|
||||
"department": "Проходные",
|
||||
"departmentCode": 8888,
|
||||
"position": "",
|
||||
"phone": "8057",
|
||||
"category": 1
|
||||
},
|
||||
{
|
||||
"id": "tp",
|
||||
"fullName": "Транспортная проходная",
|
||||
"department": "Проходные",
|
||||
"departmentCode": 8888,
|
||||
"position": "",
|
||||
"phone": "8059",
|
||||
"category": 2
|
||||
},
|
||||
{
|
||||
"id": "po701",
|
||||
"fullName": "Пост охраны проект 701",
|
||||
"department": "Посты охраны",
|
||||
"departmentCode": 9999,
|
||||
"position": "",
|
||||
"phone": "8443",
|
||||
"category": 2
|
||||
},
|
||||
{
|
||||
"id": "po702",
|
||||
"fullName": "Пост охраны проект 702",
|
||||
"department": "Посты охраны",
|
||||
"departmentCode": 9999,
|
||||
"position": "",
|
||||
"phone": "8168",
|
||||
"category": 2
|
||||
},
|
||||
{
|
||||
"id": "po402",
|
||||
"fullName": "Пост охраны проект 402",
|
||||
"department": "Посты охраны",
|
||||
"departmentCode": 9999,
|
||||
"position": "",
|
||||
"phone": "8498",
|
||||
"category": 2
|
||||
},
|
||||
{
|
||||
"id": "po703",
|
||||
"fullName": "Пост охраны проект 703",
|
||||
"department": "Посты охраны",
|
||||
"departmentCode": 9999,
|
||||
"position": "",
|
||||
"phone": "8169",
|
||||
"category": 2
|
||||
},
|
||||
{
|
||||
"id": "pov",
|
||||
"fullName": "Пост охраны видеонаблюдения",
|
||||
"department": "Посты охраны",
|
||||
"departmentCode": 9999,
|
||||
"position": "",
|
||||
"phone": "8468",
|
||||
"category": 2
|
||||
},
|
||||
{
|
||||
"id": "mk",
|
||||
"fullName": "Медицинский кабинет",
|
||||
"department": "Дежурные службы",
|
||||
"departmentCode": -1,
|
||||
"position": "",
|
||||
"mobile": "79312040016",
|
||||
"phone": "8220",
|
||||
"mail": "medkab@nssz.ru",
|
||||
"category": 1
|
||||
},
|
||||
{
|
||||
"id": "de",
|
||||
"fullName": "Дежурный электрик",
|
||||
"department": "Дежурные службы",
|
||||
"departmentCode": -1,
|
||||
"position": "",
|
||||
"mobile": "79213973747",
|
||||
"phone": "8143",
|
||||
"mail": "medkab2@nssz.ru",
|
||||
"category": 2
|
||||
},
|
||||
{
|
||||
"id": "dves",
|
||||
"fullName": "Дежурный ВЭС",
|
||||
"department": "Дежурные службы",
|
||||
"departmentCode": -1,
|
||||
"position": "",
|
||||
"phone": "8147",
|
||||
"mobile": "79213279276",
|
||||
"category": 2
|
||||
},
|
||||
{
|
||||
"id": "dvtk",
|
||||
"fullName": "Дежурный водоснабжения, теплоснабжения, канализации",
|
||||
"department": "Дежурные службы",
|
||||
"departmentCode": -1,
|
||||
"position": "",
|
||||
"phone": "8129",
|
||||
"category": 2
|
||||
},
|
||||
{
|
||||
"id": "durptm",
|
||||
"fullName": "Дежурный по участку ремонта ПТМ",
|
||||
"department": "Дежурные службы",
|
||||
"departmentCode": -1,
|
||||
"position": "",
|
||||
"phone": "8142",
|
||||
"category": 2
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,50 @@
|
||||
using StackExchange.Redis;
|
||||
using Telegram.Bot.Types;
|
||||
|
||||
namespace nsszcontactbot;
|
||||
|
||||
public class PhotosManager(ConnectionMultiplexer redis, string PhotoBasePath)
|
||||
{
|
||||
private readonly IDatabase _redisDb = redis.GetDatabase();
|
||||
private readonly string _basePath = PhotoBasePath;
|
||||
private const string Key = "cache:photos";
|
||||
private const string DefaultPhotoFileId = "AgACAgIAAxkDAAIDTWgtK4jsuoRTb7C4p0uhfVAOvWy2AAK1-TEb3cloSdmbxB-nuRFCAQADAgADcwADNgQ";
|
||||
|
||||
public async Task CacheEmployeePhotoAsync(Employee employee, string fileId, TimeSpan ttl = default)
|
||||
{
|
||||
string entryName = GetEntryName(employee);
|
||||
#pragma warning disable CS4014 // Так как этот вызов не ожидается, выполнение существующего метода продолжается до тех пор, пока вызов не будет завершен
|
||||
_redisDb.HashSetAsync(Key, [new(entryName, fileId)]).ConfigureAwait(false);
|
||||
ttl = ttl == default ? TimeSpan.FromDays(30) : ttl;
|
||||
_redisDb.HashFieldExpireAsync(Key, [new(entryName)], ttl).ConfigureAwait(false);
|
||||
#pragma warning restore CS4014 // Так как этот вызов не ожидается, выполнение существующего метода продолжается до тех пор, пока вызов не будет завершен
|
||||
}
|
||||
|
||||
public async Task<InputFile?> GetEmployeePhotoAsync(Employee employee)
|
||||
{
|
||||
string entryName = GetEntryName(employee);
|
||||
var val = await _redisDb.HashGetAsync(Key, entryName);
|
||||
if (val != RedisValue.Null && val.HasValue)
|
||||
{
|
||||
return InputFile.FromFileId(val!);
|
||||
}
|
||||
else
|
||||
{
|
||||
string photoPath = Path.Combine(_basePath, $"{employee.Id}.jpg");
|
||||
photoPath = File.Exists(photoPath) ? photoPath : Path.Combine(_basePath, $"{employee.FullName}.jpg");
|
||||
|
||||
if (File.Exists(photoPath))
|
||||
{
|
||||
var fileStream = new FileStream(
|
||||
photoPath,
|
||||
FileMode.Open,
|
||||
FileAccess.Read
|
||||
);
|
||||
return InputFile.FromStream(fileStream);
|
||||
}
|
||||
return InputFile.FromFileId(DefaultPhotoFileId); ;
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetEntryName(Employee employee) => $"employee:{employee.Id}:fileid";
|
||||
}
|
||||
+642
-147
@@ -1,59 +1,109 @@
|
||||
using Newtonsoft.Json;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Newtonsoft.Json;
|
||||
using Serilog;
|
||||
using StackExchange.Redis;
|
||||
using System.IO.Hashing;
|
||||
using System.Text;
|
||||
using System.Timers;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Polling;
|
||||
using Telegram.Bot.Types;
|
||||
using Telegram.Bot.Types.Enums;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
using Timer = System.Timers.Timer;
|
||||
|
||||
namespace nsszcontactbot;
|
||||
|
||||
public class Program
|
||||
{
|
||||
private static ITelegramBotClient Bot;
|
||||
private static List<Employee> Employees = new();
|
||||
private static List<string> Departments = new();
|
||||
private static int CurrentPage = 0; // Текущая страница для пагинации
|
||||
private static int PageSize = 5; // Количество подразделений на странице
|
||||
private static ITelegramBotClient Bot = default!;
|
||||
private static List<Employee> Employees = [];
|
||||
private static List<string> Departments = [];
|
||||
private static IConfigurationRoot config = default!;
|
||||
private static FavoriteContactsManager FavoritesManager = default!;
|
||||
private static PhotosManager PhotosManager = default!;
|
||||
//private static ILogger<Program> Logger;
|
||||
|
||||
public static async Task Main(string[] args)
|
||||
public static async Task<int> Main(string[] args)
|
||||
{
|
||||
Bot = new TelegramBotClient("6237449447:AAEGMmpx-1hUEApFZZS_ySAMZErseKJ8dHo"); // Укажите ваш токен
|
||||
List<BotCommand> cmds = new();
|
||||
await Bot.SetMyCommandsAsync(cmds);
|
||||
LoadEmployees();
|
||||
var me = await Bot.GetMeAsync();
|
||||
Console.WriteLine($"Бот запущен: @{me.Username}");
|
||||
config = new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile("appsettings.json")
|
||||
.Build();
|
||||
|
||||
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(config).CreateLogger();
|
||||
|
||||
var botToken = config["Telegram:BotToken"];
|
||||
if (botToken == null)
|
||||
{
|
||||
Log.Error("Токен Telegram-бота не указан в конфигурации.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(config["Redis:Configuration"]!, (conf) =>
|
||||
{
|
||||
conf.User = config["Redis:User"];
|
||||
conf.Password = config["Redis:Password"];
|
||||
});
|
||||
|
||||
FavoritesManager = new FavoriteContactsManager(redis);
|
||||
PhotosManager = new PhotosManager(redis, config["Paths:PhotoBasePath"]!);
|
||||
Bot = new TelegramBotClient(botToken);
|
||||
List<BotCommand> cmds = [];
|
||||
await Bot.SetMyCommands(cmds);
|
||||
if (!LoadEmployees())
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
StartUpdatingEmployeesData(15 * 60 * 1000); // обновлять данные каждые 15 минут
|
||||
|
||||
var me = await Bot.GetMe();
|
||||
|
||||
Log.Information("Бот запущен: @{Username}", me.Username);
|
||||
|
||||
// Запуск обработки обновлений
|
||||
var cancellationToken = new CancellationTokenSource().Token;
|
||||
ReceiverOptions receiverOptions =
|
||||
new()
|
||||
{
|
||||
AllowedUpdates = Array.Empty<UpdateType>() // receive all update types except ChatMember related updates
|
||||
};
|
||||
Bot.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions: receiverOptions, cancellationToken: cancellationToken);
|
||||
new()
|
||||
{
|
||||
AllowedUpdates = Array.Empty<UpdateType>() // receive all update types except ChatMember related updates
|
||||
};
|
||||
Bot.StartReceiving(
|
||||
HandleUpdateAsync,
|
||||
HandleErrorAsync,
|
||||
receiverOptions: receiverOptions,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
StartBirthdayNotifications();
|
||||
|
||||
Console.WriteLine("Нажмите Enter для выхода...");
|
||||
Console.ReadLine();
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
|
||||
private static async Task HandleUpdateAsync(
|
||||
ITelegramBotClient botClient,
|
||||
Update update,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
if (update.Type == UpdateType.Message && update.Message?.Text != null)
|
||||
{
|
||||
var message = update.Message;
|
||||
Log.Debug("Входящий текст (From=\"{Username}\", MessageId=\"{MessageId}\"): {Text}", message.From?.ToString() ?? "<!--message.From is null-->", message.Id, message.Text);
|
||||
|
||||
if (message.Text.StartsWith("/start"))
|
||||
{
|
||||
await StartCommand(message);
|
||||
}
|
||||
else if (message.Text.StartsWith("/choose_department"))
|
||||
else if (message.Text.EndsWith("Подразделения"))
|
||||
{
|
||||
await ChooseDepartment(message);
|
||||
await HandleShowDepartments(message);
|
||||
}
|
||||
else if (message.ReplyToMessage != null && message.ReplyToMessage.Text!.StartsWith("Выберите подразделение"))
|
||||
else if (message.Text.EndsWith("Избранные"))
|
||||
{
|
||||
await HandleDepartmentSelection(message);
|
||||
await HandleShowFavorites(message);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -62,8 +112,9 @@ public class Program
|
||||
}
|
||||
else if (update.Type == UpdateType.CallbackQuery)
|
||||
{
|
||||
var message = update.CallbackQuery.Message;
|
||||
string data = update.CallbackQuery.Data ?? string.Empty;
|
||||
string data = update.CallbackQuery!.Data ?? string.Empty;
|
||||
var callbackQuery = update.CallbackQuery!;
|
||||
Log.Debug("Нажатие кнопки (From=\"{Username}\", CallbackQueryId=\"{CallbackQueryId}\"): {Data}", callbackQuery.From?.ToString() ?? "<!--cbquery.From is null-->", callbackQuery.Id, data);
|
||||
string[] dataParts = data.Split('/');
|
||||
if (dataParts.Length > 0)
|
||||
{
|
||||
@@ -74,57 +125,139 @@ public class Program
|
||||
await HandleAddContact(update.CallbackQuery, dataParts[1]);
|
||||
break;
|
||||
}
|
||||
|
||||
case "addfavorite":
|
||||
{
|
||||
if (dataParts.Length != 2)
|
||||
break;
|
||||
await HandleAddFavorite(update.CallbackQuery, dataParts[1]);
|
||||
break;
|
||||
}
|
||||
|
||||
case "delfavorite":
|
||||
{
|
||||
if (dataParts.Length != 2)
|
||||
break;
|
||||
await HandleDelFavorite(update.CallbackQuery, dataParts[1]);
|
||||
break;
|
||||
}
|
||||
|
||||
case "showdepartment":
|
||||
{
|
||||
if (dataParts.Length != 2)
|
||||
break;
|
||||
await HandleShowDepartment(update.CallbackQuery, int.Parse(dataParts[1]));
|
||||
break;
|
||||
}
|
||||
|
||||
case "showemployee":
|
||||
{
|
||||
if (dataParts.Length != 2)
|
||||
break;
|
||||
await HandleShowEmployee(update.CallbackQuery, dataParts[1]);
|
||||
break;
|
||||
}
|
||||
|
||||
case "page":
|
||||
{
|
||||
if (dataParts.Length < 3)
|
||||
break;
|
||||
var arg = dataParts.Length == 3 ? dataParts[2] : dataParts[2] + "/" + dataParts[3];
|
||||
await HandlePageNavigation(update.CallbackQuery, int.Parse(dataParts[1]), arg);
|
||||
break;
|
||||
}
|
||||
|
||||
case "close":
|
||||
{
|
||||
await HandleClose(
|
||||
update.CallbackQuery,
|
||||
dataParts.Length > 1 ? dataParts[1] : null
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task StartCommand(Message message)
|
||||
{
|
||||
string text = "Привет! Я бот для поиска контактов сотрудников. Введите запрос.\n";
|
||||
//text += "/choose_department - Выбрать подразделение\n";
|
||||
await Bot.SendTextMessageAsync(message.Chat.Id, text);
|
||||
string text = "Привет! Я бот для поиска контактов сотрудников. Введите критерии поиска или воспользуйтесь кнопками внизу.\n";
|
||||
await Bot.SendMessage(message.Chat.Id, text, replyMarkup: new string[] { "❤️ Избранные", "🏢 Подразделения" });
|
||||
}
|
||||
|
||||
private static async Task ChooseDepartment(Message message)
|
||||
private static async Task HandleShowDepartments(Message message)
|
||||
{
|
||||
Departments = Employees.Select(e => e.Department).Distinct().ToList();
|
||||
CurrentPage = 0; // Сброс страницы
|
||||
Departments = [.. Employees.OrderBy(e => e.DepartmentCode).Select(e => e.Department).Distinct()];
|
||||
await ShowDepartments(message.Chat.Id);
|
||||
}
|
||||
|
||||
private static async Task ShowDepartments(long chatId)
|
||||
private static async Task ShowDepartments(long chatId, int page = 1, int pageSize = 10)
|
||||
{
|
||||
var totalDepartments = Departments.Count;
|
||||
var totalPages = (int)Math.Ceiling((double)totalDepartments / PageSize);
|
||||
var departmentsToShow = Departments.Skip(CurrentPage * PageSize).Take(PageSize).ToList();
|
||||
|
||||
string text = "Выберите подразделение:\n";
|
||||
text += string.Join("\n", departmentsToShow.Select((d, i) => $"{i + 1 + CurrentPage * PageSize}. {d}"));
|
||||
|
||||
// Создание кнопок
|
||||
var inlineKeyboard = new List<List<InlineKeyboardButton>>();
|
||||
if (CurrentPage > 0)
|
||||
if (Departments.Count == 0)
|
||||
{
|
||||
inlineKeyboard.Add(new List<InlineKeyboardButton>
|
||||
{
|
||||
InlineKeyboardButton.WithCallbackData("◀️ Назад", "prev")
|
||||
});
|
||||
}
|
||||
if (CurrentPage < totalPages - 1)
|
||||
{
|
||||
inlineKeyboard.Add(new List<InlineKeyboardButton>
|
||||
{
|
||||
InlineKeyboardButton.WithCallbackData("Вперед ▶️", "next")
|
||||
});
|
||||
await Bot.SendMessage(chatId, "Подразделения не найдены.");
|
||||
return;
|
||||
}
|
||||
|
||||
var keyboardMarkup = new InlineKeyboardMarkup(inlineKeyboard);
|
||||
var totalPages = (int)Math.Ceiling((double)Departments.Count / pageSize);
|
||||
var pagedDepartments = Departments.Skip((page - 1) * pageSize).Take(pageSize).ToList();
|
||||
|
||||
await Bot.SendTextMessageAsync(chatId, text, replyMarkup: keyboardMarkup);
|
||||
string text = $"Выберите подразделение (страница {page}/{totalPages}):";
|
||||
var keyboardMarkup = new InlineKeyboardMarkup();
|
||||
|
||||
var departmentIndex = (page - 1) * pageSize;
|
||||
foreach (var department in pagedDepartments)
|
||||
{
|
||||
keyboardMarkup
|
||||
.AddNewRow()
|
||||
.AddButton($"{department}", $"showdepartment/{departmentIndex++}");
|
||||
}
|
||||
|
||||
if (totalPages > 1)
|
||||
{
|
||||
var navigationRow = keyboardMarkup.AddNewRow();
|
||||
navigationRow.AddPaginator(page, totalPages, "departments");
|
||||
}
|
||||
|
||||
//keyboardMarkup.AddCloseButton();
|
||||
await Bot.SendMessage(chatId, text, replyMarkup: keyboardMarkup);
|
||||
await Task.Delay(999);
|
||||
}
|
||||
|
||||
class EmployeeComparer : IComparer<Employee>
|
||||
{
|
||||
public int Compare(Employee? a, Employee? b)
|
||||
{
|
||||
if (a == null || b == null) return 0;
|
||||
|
||||
// Сортировка по DepartmentCode
|
||||
int cd = CompareDepartmentCode(a.DepartmentCode, b.DepartmentCode);
|
||||
if (cd != 0) return cd;
|
||||
|
||||
// Сортировка по Category
|
||||
int cc = a.Category.CompareTo(b.Category);
|
||||
if (cc != 0) return cc;
|
||||
|
||||
// Сортировка по Position (с учетом пустых значений)
|
||||
int cp = string.Compare(a.Position ?? "", b.Position ?? "", StringComparison.OrdinalIgnoreCase);
|
||||
if (cp != 0) return cp;
|
||||
|
||||
// Сортировка по FullName
|
||||
return string.Compare(a.FullName, b.FullName, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static int CompareDepartmentCode(string codeA, string codeB)
|
||||
{
|
||||
if (int.TryParse(codeA, out int a) && int.TryParse(codeB, out int b))
|
||||
{
|
||||
return a.CompareTo(b);
|
||||
}
|
||||
return string.Compare(codeA, codeB, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task HandleSearchInput(Message message)
|
||||
@@ -132,23 +265,56 @@ public class Program
|
||||
if (!string.IsNullOrEmpty(message.Text))
|
||||
{
|
||||
string query = message.Text.Trim().ToLower();
|
||||
if (query.Length < 3)
|
||||
if (query.Length < 4)
|
||||
{
|
||||
await Bot.SendTextMessageAsync(message.Chat.Id, "Минимальная длина строки поиска - 3 символа.");
|
||||
await Bot.SendMessage(
|
||||
message.Chat.Id,
|
||||
"Минимальная длина строки поиска - 4 символа."
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Поиск сотрудников по полям
|
||||
var results = Employees.Where(e =>
|
||||
e.FullName.ToLower().Contains(query) ||
|
||||
(e.Mail != null && e.Mail.ToLower().Contains(query)) ||
|
||||
(e.Phone != null && e.Phone.Contains(query)) ||
|
||||
(e.Mobile != null && e.Mobile.Contains(query)) ||
|
||||
(e.IP != null && e.IP.Contains(query))
|
||||
).OrderBy(e => e.FullName.ToLower().IndexOf(query)).ToList();
|
||||
var queries = query.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
var results = Employees
|
||||
.Where(e =>
|
||||
queries.All(q =>
|
||||
{
|
||||
var res = e.FullName.Contains(q, StringComparison.CurrentCultureIgnoreCase) ||
|
||||
(e.Mail != null && e.Mail.Contains(q, StringComparison.CurrentCultureIgnoreCase)) ||
|
||||
(e.Phone != null && e.Phone.Contains(q)) ||
|
||||
(e.Mobile != null && e.Mobile.Contains(q)) ||
|
||||
(e.IP != null && e.IP.Contains(q));
|
||||
if (queries.Length == 1) return res;
|
||||
|
||||
return res ||
|
||||
(e.Department != null && e.Department.Contains(q, StringComparison.CurrentCultureIgnoreCase)) ||
|
||||
(e.Position != null && e.Position.Contains(q, StringComparison.CurrentCultureIgnoreCase));
|
||||
}
|
||||
))
|
||||
.Order(new EmployeeComparer())
|
||||
.ToList();
|
||||
// Отправка результатов поиска
|
||||
await ShowEmployeeResults(message, results, null);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task HandleShowFavorites(Message message)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(message.Text))
|
||||
{
|
||||
var ids = await FavoritesManager.GetAllFavoritesAsync(message.From!.Id);
|
||||
// Поиск сотрудников по полям
|
||||
var results = Employees
|
||||
.Where(
|
||||
e => ids.Contains(e.Id)
|
||||
)
|
||||
.OrderBy(e => e.FullName)
|
||||
//.Order(new EmployeeComparer())
|
||||
.ToList();
|
||||
|
||||
// Отправка результатов поиска
|
||||
await ShowEmployeeResults(message.Chat.Id, results);
|
||||
await ShowEmployeeResults(message, results, true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,91 +322,278 @@ public class Program
|
||||
{
|
||||
if (callbackQuery.Message != null)
|
||||
{
|
||||
var employee = Employees.Where(e => e.Id == id).First();
|
||||
var employee = Employees.First(e => e.Id == id);
|
||||
if (employee != null)
|
||||
{
|
||||
EmployeeContact contact = new(employee);
|
||||
string phoneNumber = !string.IsNullOrEmpty(contact.Mobile) ? contact.Mobile : contact.Phone;
|
||||
var replyParameters = new ReplyParameters() { MessageId = callbackQuery.Message.MessageId, QuoteParseMode = ParseMode.Html, Quote = $"<b>{contact.FullName}</b>" };
|
||||
await Bot.SendContactAsync(callbackQuery.Message.Chat.Id, phoneNumber, contact.FirstName, lastName: contact.LastName, vcard: contact.VCard, replyParameters: replyParameters);
|
||||
string phoneNumber = !string.IsNullOrEmpty(contact.Mobile)
|
||||
? contact.Mobile
|
||||
: contact.Phone;
|
||||
var replyParameters = new ReplyParameters()
|
||||
{
|
||||
MessageId = callbackQuery.Message.MessageId,
|
||||
QuoteParseMode = ParseMode.Html,
|
||||
Quote = $"<b>{contact.FullName}</b>"
|
||||
};
|
||||
var keyboardMarkup = new InlineKeyboardMarkup()
|
||||
//.AddNewRow()
|
||||
.AddCloseButton();
|
||||
await Bot.SendContact(
|
||||
callbackQuery.Message.Chat.Id,
|
||||
phoneNumber,
|
||||
contact.FirstName,
|
||||
lastName: contact.LastName,
|
||||
vcard: contact.VCard,
|
||||
replyParameters: replyParameters,
|
||||
replyMarkup: keyboardMarkup,
|
||||
protectContent: false
|
||||
);
|
||||
await Task.Delay(999);
|
||||
}
|
||||
}
|
||||
await Bot.AnswerCallbackQueryAsync(callbackQuery.Id);
|
||||
await Bot.AnswerCallbackQuery(callbackQuery.Id);
|
||||
}
|
||||
|
||||
private static async Task HandleDepartmentSelection(Message message)
|
||||
private static async Task HandleAddFavorite(CallbackQuery callbackQuery, string contactId)
|
||||
{
|
||||
if (message.Text.StartsWith("◀️ Назад"))
|
||||
if (callbackQuery.Message != null)
|
||||
{
|
||||
if (CurrentPage > 0)
|
||||
var employee = Employees.First(e => e.Id == contactId);
|
||||
if (employee != null)
|
||||
{
|
||||
CurrentPage--;
|
||||
await ShowDepartments(message.Chat.Id);
|
||||
await FavoritesManager.AddFavoriteAsync(callbackQuery.From.Id, contactId);
|
||||
foreach (var row in callbackQuery.Message!.ReplyMarkup!.InlineKeyboard)
|
||||
foreach (var cell in row)
|
||||
{
|
||||
if (cell.CallbackData!.Contains("addfavorite"))
|
||||
{
|
||||
cell.CallbackData = $"delfavorite/{contactId}";
|
||||
cell.Text = "💔 Не избранный";
|
||||
}
|
||||
|
||||
}
|
||||
await Bot.EditMessageReplyMarkup(callbackQuery.Message.Chat.Id, callbackQuery.Message.MessageId, callbackQuery.Message.ReplyMarkup);
|
||||
await Bot.AnswerCallbackQuery(callbackQuery.Id, "✔️ Контакт добавлен в избранные");
|
||||
}
|
||||
}
|
||||
else if (message.Text.StartsWith("Вперед ▶️"))
|
||||
}
|
||||
|
||||
private static async Task HandleDelFavorite(CallbackQuery callbackQuery, string contactId)
|
||||
{
|
||||
if (callbackQuery.Message != null)
|
||||
{
|
||||
CurrentPage++;
|
||||
await ShowDepartments(message.Chat.Id);
|
||||
}
|
||||
else
|
||||
{
|
||||
int selectedIndex = int.Parse(message.Text) - 1;
|
||||
if (selectedIndex >= 0 && selectedIndex < Departments.Count)
|
||||
var employee = Employees.First(e => e.Id == contactId);
|
||||
if (employee != null)
|
||||
{
|
||||
string selectedDepartment = Departments[selectedIndex];
|
||||
var results = Employees.Where(e => e.Department == selectedDepartment).ToList();
|
||||
await ShowEmployeeResults(message.Chat.Id, results);
|
||||
await FavoritesManager.RemoveFavoriteAsync(callbackQuery.From.Id, contactId);
|
||||
foreach (var row in callbackQuery.Message.ReplyMarkup!.InlineKeyboard)
|
||||
foreach (var cell in row)
|
||||
{
|
||||
if (cell.CallbackData!.Contains("delfavorite"))
|
||||
{
|
||||
cell.CallbackData = $"addfavorite/{contactId}";
|
||||
cell.Text = "❤️ В избранные";
|
||||
}
|
||||
|
||||
}
|
||||
await Bot.EditMessageReplyMarkup(callbackQuery.Message.Chat.Id, callbackQuery.Message.MessageId, callbackQuery.Message.ReplyMarkup);
|
||||
await Bot.AnswerCallbackQuery(callbackQuery.Id, "✔️ Контакт удален из избранных");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task HandleShowDepartment(CallbackQuery callbackQuery, int departmentIndex)
|
||||
{
|
||||
await Bot.AnswerCallbackQuery(callbackQuery.Id);
|
||||
if (callbackQuery.Message != null)
|
||||
{
|
||||
await Bot.DeleteMessage(
|
||||
callbackQuery.Message.Chat.Id,
|
||||
callbackQuery.Message.MessageId
|
||||
);
|
||||
|
||||
var employees = Employees
|
||||
.Where(e => e.Department == Departments[departmentIndex])
|
||||
//.OrderBy(e => e.FullName)
|
||||
.Order(new EmployeeComparer())
|
||||
.ToList();
|
||||
if (employees != null)
|
||||
{
|
||||
await ShowEmployeeResults(callbackQuery.Message, employees, null);
|
||||
}
|
||||
}
|
||||
//await Bot.AnswerCallbackQueryAsync(callbackQuery.Id);
|
||||
}
|
||||
|
||||
private static async Task HandleShowEmployee(CallbackQuery callbackQuery, string id)
|
||||
{
|
||||
if (callbackQuery.Message != null)
|
||||
{
|
||||
var employee = Employees.First(e => e.Id == id);
|
||||
if (employee != null)
|
||||
{
|
||||
var isFavorite = await FavoritesManager.IsFavoriteAsync(callbackQuery.From.Id, id);
|
||||
await ShowEmployeeCard(callbackQuery.Message.Chat.Id, employee, isFavorite, closeButton: true);
|
||||
}
|
||||
}
|
||||
await Bot.AnswerCallbackQuery(callbackQuery.Id);
|
||||
}
|
||||
|
||||
private static async Task HandlePageNavigation(CallbackQuery callbackQuery, int page, string context)
|
||||
{
|
||||
if (callbackQuery.Message != null)
|
||||
{
|
||||
await Bot.DeleteMessage(callbackQuery.Message.Chat.Id, callbackQuery.Message.MessageId);
|
||||
var messageHash = (callbackQuery.Message.Chat.Id << 32) | (uint)callbackQuery.Message.Id;
|
||||
|
||||
if (context.Contains("employees"))
|
||||
{
|
||||
long hash = long.Parse(context.Split('/')[1]);
|
||||
var results = _resultsCache[hash];
|
||||
await ShowEmployeeResults(callbackQuery.Message, results, null, page);
|
||||
//_resultsCache.Remove(messageHash);
|
||||
}
|
||||
else if (context == "departments")
|
||||
{
|
||||
await ShowDepartments(callbackQuery.Message.Chat.Id, page);
|
||||
}
|
||||
}
|
||||
await Bot.AnswerCallbackQuery(callbackQuery.Id);
|
||||
}
|
||||
|
||||
private static async Task HandleClose(CallbackQuery callbackQuery, string? nextAction)
|
||||
{
|
||||
if (callbackQuery.Message != null)
|
||||
{
|
||||
await Bot.DeleteMessage(
|
||||
callbackQuery.Message.Chat.Id,
|
||||
callbackQuery.Message.MessageId
|
||||
);
|
||||
await Task.Delay(500);
|
||||
}
|
||||
await Bot.AnswerCallbackQuery(callbackQuery.Id);
|
||||
}
|
||||
|
||||
private static async Task ShowEmployeeCard(long chatId, Employee employee, bool isFavorite = false, bool contactButton = true, bool favoriteButton = true, bool closeButton = false)
|
||||
{
|
||||
{
|
||||
var keyboardMarkup = new InlineKeyboardMarkup();
|
||||
var keyboardRow = keyboardMarkup.AddNewRow();
|
||||
if (contactButton)
|
||||
keyboardRow.AddButton("👤 Контакт", $"addcontact/{employee.Id}");
|
||||
|
||||
if (favoriteButton)
|
||||
{
|
||||
if (isFavorite)
|
||||
{
|
||||
keyboardRow.AddButton("💔 Не избранный", $"delfavorite/{employee.Id}");
|
||||
}
|
||||
else
|
||||
{
|
||||
keyboardRow.AddButton("❤️ В избранные", $"addfavorite/{employee.Id}");
|
||||
}
|
||||
}
|
||||
|
||||
if (closeButton)
|
||||
keyboardRow.AddCloseButton();
|
||||
|
||||
var card = CreateEmployeeCard(employee);
|
||||
|
||||
var photo = await PhotosManager.GetEmployeePhotoAsync(employee);
|
||||
|
||||
if (photo != null)
|
||||
{
|
||||
var msg = await Bot.SendPhoto(
|
||||
chatId,
|
||||
photo,
|
||||
caption: card,
|
||||
parseMode: ParseMode.Html,
|
||||
replyMarkup: keyboardMarkup
|
||||
);
|
||||
if (photo.FileType == FileType.Stream)
|
||||
{
|
||||
FileStream? stream = (photo as InputFileStream)!.Content as FileStream;
|
||||
stream?.Dispose();
|
||||
await PhotosManager.CacheEmployeePhotoAsync(employee, msg.Photo!.FirstOrDefault()!.FileId); // TODO test !
|
||||
//await PhotosManager.CacheEmployeePhotoAsync(employee, msg.Photo.FirstOrDefault().FileId);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
await Bot.SendTextMessageAsync(message.Chat.Id, "Некорректный выбор.");
|
||||
await Bot.SendMessage(
|
||||
chatId,
|
||||
card,
|
||||
ParseMode.Html,
|
||||
replyMarkup: keyboardMarkup,
|
||||
protectContent: false
|
||||
);
|
||||
}
|
||||
await Task.Delay(999);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task ShowEmployeeResults(long chatId, List<Employee> results)
|
||||
{
|
||||
if (results.Any())
|
||||
{
|
||||
foreach (var employee in results)
|
||||
{
|
||||
var keyboardMarkup = new InlineKeyboardMarkup()
|
||||
//.AddNewRow("1.1", "1.2", "1.3")
|
||||
.AddNewRow()
|
||||
.AddButton("👤 Контакт", $"addcontact/{employee.Id}");
|
||||
//.AddButton("В избранные", $"addfavorite/{employee.Id}");
|
||||
//.AddButton(InlineKeyboardButton.WithUrl("Написать письмо", $"mailto:{employee.Mail}"));
|
||||
private static Dictionary<long, List<Employee>> _resultsCache = [];
|
||||
|
||||
var card = CreateEmployeeCard(employee);
|
||||
string photoPath = $"data/photos/{employee.FullName}.jpg";
|
||||
try
|
||||
private static async Task ShowEmployeeResults(Message message, List<Employee> results, bool? isFavorite = false, int page = 1, int pageSize = 10)
|
||||
{
|
||||
if (results.Count != 0)
|
||||
{
|
||||
if (results.Count <= pageSize)
|
||||
{
|
||||
foreach (var employee in results)
|
||||
{
|
||||
await using var fileStream = new FileStream(photoPath, FileMode.Open, FileAccess.Read);
|
||||
await Bot.SendPhotoAsync(chatId, fileStream, caption: card, parseMode: ParseMode.Html, replyMarkup: keyboardMarkup);
|
||||
bool bFavorite = isFavorite.HasValue ? isFavorite == true : await FavoritesManager.IsFavoriteAsync(message.Chat.Id, employee.Id);
|
||||
await ShowEmployeeCard(message.Chat.Id, employee, bFavorite);
|
||||
}
|
||||
catch (FileNotFoundException)
|
||||
}
|
||||
else
|
||||
{
|
||||
var totalPages = (int)Math.Ceiling((double)results.Count / pageSize);
|
||||
var pagedResults = results.Skip((page - 1) * pageSize).Take(pageSize).ToList();
|
||||
|
||||
string text = $"Найдено {results.Count} сотрудников (страница {page}/{totalPages}):";
|
||||
var keyboardMarkup = new InlineKeyboardMarkup();
|
||||
|
||||
foreach (var employee in pagedResults)
|
||||
{
|
||||
await Bot.SendTextMessageAsync(chatId, card, null, ParseMode.Html, replyMarkup: keyboardMarkup);
|
||||
var title = CreateEmployeeTitle(employee);
|
||||
keyboardMarkup
|
||||
.AddNewRow()
|
||||
.AddButton(title, $"showemployee/{employee.Id}");
|
||||
}
|
||||
finally
|
||||
|
||||
if (totalPages > 1)
|
||||
{
|
||||
await Task.Delay(999);
|
||||
var messageHash = results.GetHashCode();// (message.Chat.Id << 32) | (uint)message.Id;
|
||||
_resultsCache[messageHash] = results;
|
||||
|
||||
var navigationRow = keyboardMarkup.AddNewRow();
|
||||
navigationRow.AddPaginator(page, totalPages, $"employees/{messageHash}");
|
||||
}
|
||||
|
||||
//keyboardMarkup.AddCloseButton();
|
||||
await Bot.SendMessage(message.Chat.Id, text, replyMarkup: keyboardMarkup, protectContent: false);
|
||||
await Task.Delay(999);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
await Bot.SendTextMessageAsync(chatId, "Сотрудники не найдены.");
|
||||
await Bot.SendMessage(message.Chat.Id, "🔍 Извините, мы ничего не нашли.");
|
||||
await Task.Delay(999);
|
||||
}
|
||||
}
|
||||
|
||||
static string GetEventStatus(Employee employee)
|
||||
{
|
||||
string result = "";
|
||||
if (employee.Birthday)
|
||||
{
|
||||
result += "🎂 Празднует день рождения\n";
|
||||
}
|
||||
if (employee.StartDate == null || employee.EndDate == null)
|
||||
{
|
||||
return string.Empty;
|
||||
return result;
|
||||
}
|
||||
DateTime today = DateTime.Now;
|
||||
TimeSpan oneWeekBeforeEvent = (DateTime)employee.StartDate - today;
|
||||
@@ -248,24 +601,69 @@ public class Program
|
||||
if (employee.StartDate <= today && today <= employee.EndDate)
|
||||
{
|
||||
// Сотрудник участвует в событии
|
||||
return $"🟥 {employee.State} с {employee.StartDate:dd.MM.yyyy} по {employee.EndDate:dd.MM.yyyy}";
|
||||
result += $"🟥 {employee.State} с {employee.StartDate:dd.MM.yyyy} по {employee.EndDate:dd.MM.yyyy}";
|
||||
}
|
||||
else if (oneWeekBeforeEvent.TotalDays <= 7 && oneWeekBeforeEvent.TotalDays > 0)
|
||||
{
|
||||
// Событие начнется через неделю
|
||||
return $"🟩 {employee.State} с {employee.StartDate:dd.MM.yyyy} по {employee.EndDate:dd.MM.yyyy}";
|
||||
result += $"🟩 {employee.State} с {employee.StartDate:dd.MM.yyyy} по {employee.EndDate:dd.MM.yyyy}";
|
||||
}
|
||||
|
||||
return result;
|
||||
// Если событие не указано или неактуально
|
||||
return string.Empty;
|
||||
//return string.Empty;
|
||||
}
|
||||
|
||||
private static string CreateEmployeeTitle(Employee employee)
|
||||
{
|
||||
EmployeeContact contact = new(employee);
|
||||
|
||||
string prefix = string.Empty;
|
||||
|
||||
if (employee.StartDate != null || employee.EndDate != null)
|
||||
{
|
||||
DateTime today = DateTime.Now;
|
||||
TimeSpan oneWeekBeforeEvent = (DateTime)employee.StartDate! - today;
|
||||
|
||||
if (employee.StartDate <= today && today <= employee.EndDate)
|
||||
{
|
||||
// Сотрудник участвует в событии
|
||||
prefix += "🟥";
|
||||
}
|
||||
else if (oneWeekBeforeEvent.TotalDays <= 7 && oneWeekBeforeEvent.TotalDays > 0)
|
||||
{
|
||||
// Событие начнется через неделю
|
||||
prefix += "🟩";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (employee.Birthday)
|
||||
{
|
||||
prefix += "🎂";
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(prefix))
|
||||
{
|
||||
//prefix = "👤 ";
|
||||
}
|
||||
else
|
||||
{
|
||||
prefix += " ";
|
||||
}
|
||||
|
||||
return $"{prefix}{contact.ShortName}";
|
||||
}
|
||||
|
||||
private static string CreateEmployeeCard(Employee employee)
|
||||
{
|
||||
EmployeeContact contact = new(employee);
|
||||
string card = $"👤 <b>{contact.FullName}</b>\n" +
|
||||
$"🏢 {contact.Department}\n" +
|
||||
$"🎓 {contact.Position}\n";
|
||||
string card =
|
||||
$"👤 <b>{contact.FullName}</b>\n"
|
||||
+ $"🏢 {contact.Department}\n";
|
||||
|
||||
if (!string.IsNullOrEmpty(contact.Position))
|
||||
card += $"🎓 {contact.Position}\n";
|
||||
|
||||
if (!string.IsNullOrEmpty(contact.Mail))
|
||||
card += $"✉️ {contact.Mail}\n";
|
||||
@@ -275,47 +673,144 @@ public class Program
|
||||
if (!string.IsNullOrEmpty(contact.ExtensionNumber))
|
||||
card += $"📞 {contact.ExtensionNumber}\n";
|
||||
|
||||
//if (!string.IsNullOrEmpty(employee.IP))
|
||||
// card += $"🌐 {employee.IP}\n";
|
||||
|
||||
card += GetEventStatus(employee);
|
||||
|
||||
return card;
|
||||
}
|
||||
|
||||
private static string CreateEmployeeCard2(Employee employee)
|
||||
{
|
||||
string photoUrl = $"https://contacts.int.nssz.ru/data/photos/{employee.FullName.Replace(" ", "%20")}.jpg"; // Формирование пути к фотографии
|
||||
|
||||
string card = $"👤 <b>{employee.FullName}</b>\n" +
|
||||
$"🏢 Отдел: {employee.Department}\n" +
|
||||
$"🎓 Должность: {employee.Position}\n" +
|
||||
$"📸 Фото: <a href='{photoUrl}'>Посмотреть фото</a>\n"; // Добавление ссылки на фото
|
||||
|
||||
if (!string.IsNullOrEmpty(employee.Mail))
|
||||
card += $"✉️ Почта: {employee.Mail}\n";
|
||||
if (!string.IsNullOrEmpty(employee.Phone))
|
||||
card += $"📞 Телефон: {employee.Phone}\n";
|
||||
if (!string.IsNullOrEmpty(employee.Mobile))
|
||||
card += $"📱 Мобильный: +{employee.Mobile}\n";
|
||||
if (!string.IsNullOrEmpty(employee.IP))
|
||||
card += $"🌐 IP: {employee.IP}\n";
|
||||
card += $"🖥 {employee.IP}\n";
|
||||
|
||||
card += GetEventStatus(employee);
|
||||
|
||||
return card;
|
||||
}
|
||||
|
||||
private static void LoadEmployees()
|
||||
private static Timer? updateTimer = null;
|
||||
private static void StartUpdatingEmployeesData(int intervalMs = 1 * 60 * 60 * 1000)
|
||||
{
|
||||
// Загрузка данных сотрудников из JSON файла
|
||||
var json = System.IO.File.ReadAllText("data/contacts.json");
|
||||
Employees = JsonConvert.DeserializeObject<List<Employee>>(json)!;
|
||||
if (updateTimer != null) return;
|
||||
updateTimer = new Timer(intervalMs);
|
||||
updateTimer.Elapsed += UpdateTimer_Elapsed;
|
||||
updateTimer.AutoReset = true; // Запускать снова после завершения
|
||||
updateTimer.Enabled = true;
|
||||
}
|
||||
|
||||
private static Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
|
||||
private static void UpdateTimer_Elapsed(object? sender, ElapsedEventArgs e)
|
||||
{
|
||||
Console.WriteLine($"Произошла ошибка: {exception.Message}");
|
||||
LoadEmployees();
|
||||
}
|
||||
|
||||
private static string prevHash = string.Empty;
|
||||
private static bool LoadEmployees()
|
||||
{
|
||||
try
|
||||
{
|
||||
string filePath = config["Paths:ContactsJsonPath"] ?? string.Empty;
|
||||
if (!string.IsNullOrEmpty(filePath))
|
||||
{
|
||||
string json;
|
||||
if (filePath.StartsWith("http", StringComparison.InvariantCultureIgnoreCase))
|
||||
{
|
||||
using var client = new HttpClient();
|
||||
using HttpResponseMessage response = client.GetAsync(filePath).Result;
|
||||
using HttpContent content = response.Content;
|
||||
json = content.ReadAsStringAsync().Result;
|
||||
}
|
||||
else
|
||||
{
|
||||
json = File.ReadAllText(filePath);
|
||||
}
|
||||
// Загрузка данных сотрудников из JSON файла при наличии изменений
|
||||
var newHash = CalculateHash(json);
|
||||
if (prevHash == newHash)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
prevHash = newHash;
|
||||
Employees = JsonConvert.DeserializeObject<List<Employee>>(json)!;
|
||||
|
||||
var backupFilename = BackupContactsJSON(json);
|
||||
if (!string.IsNullOrEmpty(backupFilename))
|
||||
{
|
||||
Log.Debug("Данные обновлены, создана резервная копия: {BackupFilename}", backupFilename);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Employees.Clear();
|
||||
}
|
||||
|
||||
filePath = config["Paths:PersistentContactsJsonPath"] ?? string.Empty;
|
||||
if (!string.IsNullOrEmpty(filePath))
|
||||
{
|
||||
var json = File.ReadAllText(filePath);
|
||||
Employees.AddRange(JsonConvert.DeserializeObject<List<Employee>>(json)!);
|
||||
}
|
||||
if (Employees.Count > 0)
|
||||
{
|
||||
Log.Information("Загружены данные о {Count} сотрудниках", Employees.Count);
|
||||
return true;
|
||||
}
|
||||
Log.Error("Нет данных о сотрудниках");
|
||||
return false;
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Error(ex, "Ошибка при загрузке списка сотрудников");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string CalculateHash(string data)
|
||||
{
|
||||
byte[] hashBytes = Crc32.Hash(Encoding.UTF8.GetBytes(data));
|
||||
return Convert.ToHexString(hashBytes);
|
||||
}
|
||||
private static string BackupContactsJSON(string json)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(json, nameof(json));
|
||||
var backupDirectory = config["Paths:ContactsBackupDirectory"] ?? string.Empty;
|
||||
if (!string.IsNullOrEmpty(backupDirectory))
|
||||
{
|
||||
if (!Directory.Exists(backupDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(backupDirectory);
|
||||
}
|
||||
|
||||
var hashString = CalculateHash(json).ToUpperInvariant();
|
||||
|
||||
var filename = Path.GetFullPath(Path.Combine(backupDirectory, $"{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{Employees.Count}_contacts_{hashString}.json"));
|
||||
File.WriteAllText(filename, json);
|
||||
return filename;
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
private static void StartBirthdayNotifications()
|
||||
{
|
||||
var timer = new Timer(TimeSpan.FromHours(24).TotalMilliseconds);
|
||||
timer.Elapsed += async (sender, e) =>
|
||||
{
|
||||
var today = DateTime.Today;
|
||||
var birthdayEmployees = Employees.Where(e => e.Birthday).ToList();
|
||||
foreach (var employee in birthdayEmployees)
|
||||
{
|
||||
var users = await FavoritesManager.GetUsersWithFavoriteAsync(employee.Id);
|
||||
foreach (var userId in users)
|
||||
{
|
||||
await Bot.SendMessage(userId, $"🎂 Сегодня день рождения у {employee.FullName}!");
|
||||
await Task.Delay(999);
|
||||
}
|
||||
}
|
||||
};
|
||||
timer.AutoReset = true;
|
||||
timer.Start();
|
||||
}
|
||||
|
||||
private static Task HandleErrorAsync(
|
||||
ITelegramBotClient botClient,
|
||||
Exception exception,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
Log.Error(exception, "Произошла ошибка");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"Paths": {
|
||||
"ContactsJsonPath": "http://contacts.nssz.local/data/contacts.json",
|
||||
"PersistentContactsJsonPath": "PersistentContacts.json",
|
||||
"PhotoBasePath": "photos",
|
||||
"ContactsBackupDirectory": "unique_contacts_backup"
|
||||
},
|
||||
"Telegram": {
|
||||
"BotToken": "8155021946:AAGbfJnLa0sTWxqFB9yjbXhbTedBw4wvcQE"
|
||||
},
|
||||
"Redis": {
|
||||
"Configuration": "contacts.nssz.local:6379",
|
||||
"User": "default",
|
||||
"Password": ""
|
||||
},
|
||||
"Serilog": {
|
||||
"Using": [
|
||||
"Serilog.Sinks.Console",
|
||||
"Serilog.Sinks.File"
|
||||
],
|
||||
"MinimumLevel": "Debug",
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "Console"
|
||||
},
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "nsszcontactbot.log",
|
||||
"rollingInterval": "Day"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
+17
-2
@@ -2,13 +2,28 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.3" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="Telegram.Bot" Version="21.11.0" />
|
||||
<PackageReference Include="NRedisStack" Version="0.13.2" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="9.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
|
||||
<PackageReference Include="System.IO.Hashing" Version="10.0.10" />
|
||||
<PackageReference Include="Telegram.Bot" Version="22.4.4" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Update="appsettings.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="PersistentContacts.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
dotnet build -c Release
|
||||
cd bin\Release\net10.0
|
||||
.\nsszcontactbot
|
||||
Reference in New Issue
Block a user