Skip to content

Instantly share code, notes, and snippets.

@tuscen
Last active February 16, 2019 15:22
Show Gist options
  • Save tuscen/094cd3850bc94de1bc8067a3f7d309f5 to your computer and use it in GitHub Desktop.
Save tuscen/094cd3850bc94de1bc8067a3f7d309f5 to your computer and use it in GitHub Desktop.
using System;
using System.Text;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
public class MarkdownEntitiesTransformer
{
public string Transform(string message, MessageEntity[] entities)
{
var currentEntityIndex = 0;
var currentCharacter = 0;
var builder = new StringBuilder();
while (currentCharacter < message.Length)
{
if (entities.Length == 0 || currentEntityIndex >= entities.Length)
{
builder.Append(message.Substring(currentCharacter));
break;
}
var currentEntity = entities[currentEntityIndex];
if (currentEntity.Offset == currentCharacter)
{
var currentEntityBody = message.Substring(currentEntity.Offset, currentEntity.Length);
var transformedEntity = string.Empty;
switch (currentEntity.Type)
{
case MessageEntityType.TextLink:
transformedEntity = $"[{currentEntityBody}]({currentEntity.Url})";
break;
case MessageEntityType.Pre:
transformedEntity = $"```\n{currentEntityBody}```";
break;
case MessageEntityType.Bold:
transformedEntity = $"*{currentEntityBody}*";
break;
case MessageEntityType.Italic:
transformedEntity = $"_{currentEntityBody}_";
break;
case MessageEntityType.Code:
transformedEntity = $"`{currentEntityBody}`";
break;
case MessageEntityType.TextMention:
transformedEntity = $"[{currentEntityBody}](tg://user?id={currentEntity.User.Id})";
break;
case MessageEntityType.Mention:
case MessageEntityType.Hashtag:
case MessageEntityType.BotCommand:
case MessageEntityType.Url:
case MessageEntityType.Email:
transformedEntity = currentEntityBody;
break;
}
builder.Append(transformedEntity);
currentCharacter += currentEntity.Length;
}
else
{
builder.Append(message[currentCharacter]);
currentCharacter += 1;
}
if (currentEntity.Offset < currentCharacter)
{
currentEntityIndex += 1;
}
}
return builder.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment