Skip to content

Отправка сообщений в Telegram по логинам #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
216ae36
поменяли апи и добавили возможность отправки сообщения с логином
postcretinism Jun 3, 2025
0dec3d1
исправили документацию для нового апи телеграм бота
postcretinism Jun 3, 2025
0ce8115
исправил ошибку в документации
postcretinism Jun 3, 2025
eca13d0
Исправили ошибку в документации датабазы
postcretinism Jun 5, 2025
4c258fd
создали модель чата новую
postcretinism Jun 7, 2025
b87486d
Создали новый плагин TelegramChatList
postcretinism Jun 12, 2025
4c5a7a3
подписали TelegramChatListPlugin на событие получения сообщения в Tel…
postcretinism Jun 13, 2025
1fd4fd2
перенесли миграцию из плагина телеграм бота в телеграмчатлист
postcretinism Jun 13, 2025
448a854
сделали обновление данных о чате
postcretinism Jun 14, 2025
ed801f0
Добавили новые колонки в таблицу и обновили модель
postcretinism Jun 27, 2025
d2f6e77
откатили документацию
postcretinism Jun 28, 2025
cdef35b
откатили изменения апи чатбота телеги
postcretinism Jun 28, 2025
3939681
добавили в общий ридми новый плагин
postcretinism Jun 28, 2025
2e7134a
добавили в плагин чатлиста вспомогательную информацию для публикации …
postcretinism Jun 28, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ ThinkingHome - кроссплатформенное приложение, поз
- [ThinkingHome.Plugins.Scripts](./ThinkingHome.Plugins.Scripts) - выполнение сценариев автоматизации
- [ThinkingHome.Plugins.Scripts.WebApi](./ThinkingHome.Plugins.Scripts.WebApi) - web API для управления сценариями
- [ThinkingHome.Plugins.TelegramBot](./ThinkingHome.Plugins.TelegramBot) - Telegram бот
- [ThinkingHome.Plugins.TelegramChatList](./ThinkingHome.Plugins.TelegramChatList) - сохранение информации о чатах с Telegram ботом
- [ThinkingHome.Plugins.Timer](./ThinkingHome.Plugins.Timer) - выполнение действий по таймеру
- [ThinkingHome.Plugins.WebServer](./ThinkingHome.Plugins.WebServer) - инфраструктура для обращения к методам плагинов по HTTP
- [ThinkingHome.Plugins.WebServer.UrlValidation](./ThinkingHome.Plugins.WebServer.UrlValidation) - валидация URL методов плагинов на соответствие правилам
Expand Down
1 change: 1 addition & 0 deletions ThinkingHome.Console/ThinkingHome.Console.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
<ProjectReference Include="..\ThinkingHome.Core.Plugins\ThinkingHome.Core.Plugins.csproj" />
<ProjectReference Include="..\ThinkingHome.Plugins.Database\ThinkingHome.Plugins.Database.csproj" />
<ProjectReference Include="..\ThinkingHome.Plugins.Mail\ThinkingHome.Plugins.Mail.csproj" />
<ProjectReference Include="..\ThinkingHome.Plugins.TelegramChatList\ThinkingHome.Plugins.TelegramChatList.csproj" />
<ProjectReference Include="..\ThinkingHome.Plugins.Tmp\ThinkingHome.Plugins.Tmp.csproj" />
<ProjectReference Include="..\ThinkingHome.Plugins.Mqtt\ThinkingHome.Plugins.Mqtt.csproj" />
<ProjectReference Include="..\ThinkingHome.Plugins.NooLite\ThinkingHome.Plugins.NooLite.csproj" />
Expand Down
1 change: 1 addition & 0 deletions ThinkingHome.Console/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"ThinkingHome.Plugins.Mqtt",
"ThinkingHome.Plugins.NooLite",
"ThinkingHome.Plugins.TelegramBot",
"ThinkingHome.Plugins.TelegramChatList",
"ThinkingHome.Plugins.Scripts",
"ThinkingHome.Plugins.Cron",
"ThinkingHome.Plugins.Cron.WebApi",
Expand Down
2 changes: 1 addition & 1 deletion ThinkingHome.Core.Plugins/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public class MyPlugin : PluginBase
{
private readonly OtherPlugin otherPlugin;

public PluginBase(OtherPlugin otherPlugin) {
public MyPlugin(OtherPlugin otherPlugin) {
// сохраняем полученный экземпляр плагина в поле своего плагина
this.otherPlugin = otherPlugin;
}
Expand Down
2 changes: 1 addition & 1 deletion ThinkingHome.Plugins.Database/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@

Вы можете отметить методы своего плагина атрибутом `ThinkingHome.Plugins.Database.DbModelBuilderAttribute` и реализовать там логику по настройке мэппинга вашей модели на структуру БД, используя EF Fluent API.

Сигнатура метода, вызываемого по таймеру, должна соответствовать делегату `DbModelBuilderDelegate`:
Сигнатура метода, который настраивает модель, должна соответствовать делегату `DbModelBuilderDelegate`:

```csharp
public delegate void DbModelBuilderDelegate(ModelBuilder modelBuilder);
Expand Down
8 changes: 4 additions & 4 deletions ThinkingHome.Plugins.TelegramBot/TelegramBotPlugin.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -16,9 +15,10 @@

namespace ThinkingHome.Plugins.TelegramBot {
public class TelegramBotPlugin : PluginBase, IUpdateHandler {
public event Action<Message> OnMessageReceived;

private HashSet<string> logins;

private static readonly Regex CommandRegex = new Regex("^\\s*/([a-z0-9-_]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);

private ObjectSetRegistry<TelegramMessageHandlerDelegate> handlers;
Expand Down Expand Up @@ -73,7 +73,7 @@ public override void StopPlugin()
public Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
if (update.Message is { } msg) {

OnMessageReceived?.Invoke(update.Message);
if (msg.Chat.Type == ChatType.Private) {
if (logins.Contains(msg.Chat.Username)) {
var command = ParseCommand(msg.Text);
Expand All @@ -87,7 +87,7 @@ public Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, Cance
_ = SafeInvokeAsync(handlers[TelegramMessageHandlerAttribute.ALL_COMMANDS], fn => fn(command, msg));
}
else {
Logger.LogInformation("Received message from unknown user with username {0}", msg.Chat.Username);
Logger.LogInformation("Received message from unknown user with username {Username} ({ChatId})", msg.Chat.Username, msg.Chat.Id);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.1" />
<PackageReference Include="Telegram.Bot" Version="22.3.0" />
<PackageReference Include="Telegram.Bot" Version="22.5.1" />
</ItemGroup>
</Project>
15 changes: 15 additions & 0 deletions ThinkingHome.Plugins.TelegramChatList/Model/Chat.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace ThinkingHome.Plugins.TelegramChatList.Model;

public class Chat {
public Guid Id { get; set; }

public string? Login { get; set; }

public long ChatId { get; set; }

public string? FirstName { get; set; }

public string? LastName { get; set; }

public DateTime Date { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System.Data;
using ThinkingHome.Migrator.Framework;
using ThinkingHome.Migrator.Framework.Extensions;

namespace ThinkingHome.Plugins.TelegramChatList.Model.Migrations;

[Migration(1)]
public class Migration01 : Migration {
private const int MAX_LOGIN_LENGTH = 32;
public override void Apply()
{
Database.AddTable("TelegramChatList_Chat",
new Column("Id", DbType.Guid, ColumnProperty.PrimaryKey),
new Column("Login", DbType.String.WithSize(MAX_LOGIN_LENGTH), ColumnProperty.Null),
new Column("ChatId", DbType.Int64, ColumnProperty.NotNull),
new Column("Date", DbType.DateTime, ColumnProperty.NotNull),
new Column("FirstName", DbType.String.WithSize(int.MaxValue), ColumnProperty.Null),
new Column("LastName", DbType.String.WithSize(int.MaxValue), ColumnProperty.Null));

Database.AddUniqueConstraint("UK_TelegramChatList_Chat_ChatId", "TelegramChatList_Chat", "ChatId");

}

public override void Revert()
{
Database.RemoveTable("TelegramChatList_Chat");
}
}
7 changes: 7 additions & 0 deletions ThinkingHome.Plugins.TelegramChatList/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
*ThinkingHome.Plugins.TelegramChatList*

[![NuGet Pre Release](https://img.shields.io/nuget/vpre/ThinkingHome.Plugins.TelegramChatList.svg)]()

# TelegramChatListPlugin

Сохраняет в базу данных информацию о чатах Telegram бота. В базу данных сохраняются ID чата, логин (username), имя, фамилия и дата последнего принятого сообщения.
47 changes: 47 additions & 0 deletions ThinkingHome.Plugins.TelegramChatList/TelegramChatListPlugin.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using Microsoft.EntityFrameworkCore;
using Telegram.Bot.Types;
using ThinkingHome.Core.Plugins;
using ThinkingHome.Plugins.Database;
using ThinkingHome.Plugins.TelegramBot;
using Chat = ThinkingHome.Plugins.TelegramChatList.Model.Chat;

namespace ThinkingHome.Plugins.TelegramChatList;

public class TelegramChatListPlugin(TelegramBotPlugin telegramBot, DatabasePlugin database) : PluginBase {
[DbModelBuilder]
public void InitModel(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Chat>(cfg => cfg.ToTable("TelegramChatList_Chat"));
}

public override void InitPlugin()
{
telegramBot.OnMessageReceived += TelegramBotOnMessageReceived;
}

private void TelegramBotOnMessageReceived(Message msg)
{
using var db = database.OpenSession();

var savedChat = db.Set<Chat>().SingleOrDefault(c => c.ChatId == msg.Chat.Id);

if (savedChat == null) {
savedChat = new Chat {
Id = Guid.NewGuid(), ChatId = msg.Chat.Id
};

db.Set<Chat>().Add(savedChat);
}
savedChat.Login = msg.Chat.Username;
savedChat.FirstName = msg.Chat.FirstName;
savedChat.LastName = msg.Chat.LastName;
savedChat.Date = msg.Date;

db.SaveChanges();
}

public override void StartPlugin()
{
telegramBot.SendMessage(353206782, "чатлисту весело он работает !");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="../Package.xml" />
<PropertyGroup>
<Description>ThinkingHome plugin which store TelegramBot chats data.</Description>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\ThinkingHome.Core.Plugins\ThinkingHome.Core.Plugins.csproj" />
<ProjectReference Include="..\ThinkingHome.Plugins.Database\ThinkingHome.Plugins.Database.csproj" />
<ProjectReference Include="..\ThinkingHome.Plugins.TelegramBot\ThinkingHome.Plugins.TelegramBot.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="ThinkingHome.Migrator.Framework" Version="3.9.0" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion ThinkingHome.Plugins.Tmp/ThinkingHome.Plugins.Tmp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,6 @@
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.1"/>
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.1"/>
<PackageReference Include="ThinkingHome.Migrator.Framework" Version="3.9.0"/>
<PackageReference Include="Telegram.Bot" Version="22.3.0"/>
<PackageReference Include="Telegram.Bot" Version="22.5.1" />
</ItemGroup>
</Project>
15 changes: 15 additions & 0 deletions ThinkingHome.sln
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ThinkingHome.Plugins.Telegr
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ThinkingHome.Plugins.WebUi", "ThinkingHome.Plugins.WebUi\ThinkingHome.Plugins.WebUi.csproj", "{003AE996-5F8D-414E-A084-CB93B91D10B1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ThinkingHome.Plugins.TelegramChatList", "ThinkingHome.Plugins.TelegramChatList\ThinkingHome.Plugins.TelegramChatList.csproj", "{0599B53C-C02C-4B37-8A08-76A7B810E06D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -148,6 +150,18 @@ Global
{003AE996-5F8D-414E-A084-CB93B91D10B1}.Release|x64.Build.0 = Release|Any CPU
{003AE996-5F8D-414E-A084-CB93B91D10B1}.Release|x86.ActiveCfg = Release|Any CPU
{003AE996-5F8D-414E-A084-CB93B91D10B1}.Release|x86.Build.0 = Release|Any CPU
{0599B53C-C02C-4B37-8A08-76A7B810E06D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0599B53C-C02C-4B37-8A08-76A7B810E06D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0599B53C-C02C-4B37-8A08-76A7B810E06D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0599B53C-C02C-4B37-8A08-76A7B810E06D}.Release|Any CPU.Build.0 = Release|Any CPU
{0599B53C-C02C-4B37-8A08-76A7B810E06D}.Debug|x64.ActiveCfg = Debug|Any CPU
{0599B53C-C02C-4B37-8A08-76A7B810E06D}.Debug|x64.Build.0 = Debug|Any CPU
{0599B53C-C02C-4B37-8A08-76A7B810E06D}.Debug|x86.ActiveCfg = Debug|Any CPU
{0599B53C-C02C-4B37-8A08-76A7B810E06D}.Debug|x86.Build.0 = Debug|Any CPU
{0599B53C-C02C-4B37-8A08-76A7B810E06D}.Release|x64.ActiveCfg = Release|Any CPU
{0599B53C-C02C-4B37-8A08-76A7B810E06D}.Release|x64.Build.0 = Release|Any CPU
{0599B53C-C02C-4B37-8A08-76A7B810E06D}.Release|x86.ActiveCfg = Release|Any CPU
{0599B53C-C02C-4B37-8A08-76A7B810E06D}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -169,6 +183,7 @@ Global
{CDCBFFD1-7FBD-496E-BD42-581F66BEB085} = {5DF04DCB-BC26-42FA-B7D6-CFC24963F1A8}
{960A9C44-3D0F-42F4-8F81-F89588EAC9E0} = {5DF04DCB-BC26-42FA-B7D6-CFC24963F1A8}
{003AE996-5F8D-414E-A084-CB93B91D10B1} = {5DF04DCB-BC26-42FA-B7D6-CFC24963F1A8}
{0599B53C-C02C-4B37-8A08-76A7B810E06D} = {5DF04DCB-BC26-42FA-B7D6-CFC24963F1A8}
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
Policies = $0
Expand Down