Skip to content

Instantly share code, notes, and snippets.

@Pzixel
Created March 6, 2019 09:39
Show Gist options
  • Save Pzixel/a8123e0731baed76fa52d6ee5a8d3c2e to your computer and use it in GitHub Desktop.
Save Pzixel/a8123e0731baed76fa52d6ee5a8d3c2e to your computer and use it in GitHub Desktop.
private static string GetTelegramMessage(string message)
{
const int telegramMessageMaxLength = 4096; // https://core.telegram.org/method/messages.sendMessage#return-errors
const int ellipsisDotsCount = 3;
var encoding = Encoding.UTF8;
if (string.IsNullOrEmpty(message) || encoding.GetByteCount(message) <= telegramMessageMaxLength)
{
return message;
}
byte[] buffer = new byte[telegramMessageMaxLength];
char[] messageChars = message.ToCharArray();
encoding.GetEncoder().Convert(
chars: messageChars,
charIndex: 0,
charCount: messageChars.Length,
bytes: buffer,
byteIndex: 0,
byteCount: buffer.Length - ellipsisDotsCount,
flush: false,
charsUsed: out int _,
bytesUsed: out int bytesUsed,
completed: out bool _);
for (int i = 0; i < ellipsisDotsCount; i++)
{
buffer[bytesUsed + i] = (byte) '.';
}
return encoding.GetString(buffer, 0, bytesUsed + ellipsisDotsCount);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment