Files

72 lines
2.7 KiB
C#

using System.Globalization;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace Volcanic.AgenticCore.Telegram.Groups;
/// <summary>The message a group message replies to.</summary>
public sealed record GroupReply(string Sender, string? Text);
/// <summary>A group message as triggers see it: who, where, when, the text (or caption) and what it replies to.</summary>
public sealed record GroupMessage(
long GroupId,
string GroupTitle,
string? GroupUsername,
bool IsSupergroup,
int MessageId,
DateTimeOffset Time,
string Sender,
string? Text,
GroupReply? ReplyTo = null)
{
/// <summary>
/// A link to the message: <c>t.me/&lt;username&gt;/&lt;id&gt;</c> for public groups, <c>t.me/c/&lt;id without -100&gt;/&lt;id&gt;</c>
/// for private supergroups (members only), none for basic groups.
/// </summary>
public string? Link
{
get
{
var mid = MessageId.ToString(CultureInfo.InvariantCulture);
if (!string.IsNullOrEmpty(GroupUsername)) return $"https://t.me/{GroupUsername}/{mid}";
if (!IsSupergroup) return null;
var id = (-GroupId).ToString(CultureInfo.InvariantCulture);
return id.StartsWith("100", StringComparison.Ordinal) && id.Length > 3 ? $"https://t.me/c/{id[3..]}/{mid}" : null;
}
}
public static GroupMessage From(Message message)
{
ArgumentNullException.ThrowIfNull(message);
var reply = message.ReplyToMessage is { } replied
? new GroupReply(SenderOf(replied), replied.Text ?? replied.Caption)
: null;
return new GroupMessage(
message.Chat.Id,
TitleOf(message.Chat),
message.Chat.Username,
message.Chat.Type == ChatType.Supergroup,
message.Id,
new DateTimeOffset(DateTime.SpecifyKind(message.Date, DateTimeKind.Utc)),
SenderOf(message),
message.Text ?? message.Caption,
reply);
}
public static string TitleOf(Chat chat)
{
ArgumentNullException.ThrowIfNull(chat);
return string.IsNullOrWhiteSpace(chat.Title) ? chat.Id.ToString(CultureInfo.InvariantCulture) : chat.Title;
}
/// <summary>"First Last (@username)", or the chat an anonymous admin / channel posted as.</summary>
public static string SenderOf(Message message)
{
ArgumentNullException.ThrowIfNull(message);
if (message.SenderChat is { } chat) return TitleOf(chat);
if (message.From is not { } user) return "unknown";
var name = string.IsNullOrWhiteSpace(user.LastName) ? user.FirstName : $"{user.FirstName} {user.LastName}";
return string.IsNullOrWhiteSpace(user.Username) ? name : $"{name} (@{user.Username})";
}
}