Skip to content
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

Fix social embed #98

Merged
merged 2 commits into from
Jan 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,17 @@ await _commandQueue.DispatchAsync(

// Handle Social Link (better preview)
if ((update.Message.Text ?? update.Message.Caption) is { } textOrCaption) {
IEnumerable<Uri> betterLinks = SocialLinkEmbedFixer.GetPossibleUrls(textOrCaption);
IEnumerable<Uri> possibleUrls = SocialLinkEmbedFixer.GetPossibleUrls(textOrCaption);

if (betterLinks.Any()) {
if (possibleUrls.Any()) {
// Fire and forget
Task _ = Task.Run(async () => {
try {
foreach (Uri betterLink in betterLinks) {
foreach (Uri url in possibleUrls) {
Uri fixedUrl = SocialLinkEmbedFixer.Fix(url);
await _telegramBotClient.SendTextMessageAsync(
chatId: update.Message.Chat.Id,
text: $"Preview: {betterLink.OriginalString}",
text: $"Preview: {fixedUrl.OriginalString}",
replyToMessageId: update.Message.MessageId,
cancellationToken: cancellationToken
);
Expand Down
11 changes: 11 additions & 0 deletions BotNet.Services/SocialLink/SocialLinkEmbedFixer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@

namespace BotNet.Services.SocialLink {
public partial class SocialLinkEmbedFixer {

/// <summary>
/// Fixes the given URI by replacing specific host names with new host names.
/// </summary>
/// <param name="link">The original URI to be fixed.</param>
/// <returns>A new URI with the host names replaced.</returns>
public static Uri Fix(Uri link) {
string url = link.ToString();
string newUrl = link.Host switch {
Expand All @@ -18,6 +24,11 @@ public static Uri Fix(Uri link) {
return new Uri(newUrl);
}

/// <summary>
/// Extracts possible URLs from the given message that match Twitter and Instagram patterns.
/// </summary>
/// <param name="message">The message to search for URLs.</param>
/// <returns>An enumerable collection of URLs.</returns>
public static IEnumerable<Uri> GetPossibleUrls(string message) {
MatchCollection twitterMatches = TwitterRegex().Matches(message);
foreach (Match match in twitterMatches) {
Expand Down
Loading