Skip to content

Commit

Permalink
Add env vars to set private API server URL and file size limit.
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianAllred committed Jan 2, 2024
1 parent f422650 commit 2dac2e1
Show file tree
Hide file tree
Showing 7 changed files with 19 additions and 10 deletions.
2 changes: 1 addition & 1 deletion Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ private static void Main(string[] args)
builder.Services.AddHttpClient("telegram_bot_client")
.AddTypedClient<ITelegramBotClient>((httpClient, sp) =>
{
var options = new TelegramBotClientOptions(config.TelegramBotToken);
var options = new TelegramBotClientOptions(config.TelegramBotToken, config.TelegramApiServer);
return new TelegramBotClient(options, httpClient);
});

Expand Down
4 changes: 3 additions & 1 deletion Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
"ASPNETCORE_ENVIRONMENT": "Development",
"TG_BOT_TOKEN": "",
"TG_BOT_NAME": "Test Video Bot",
"UPDATE_YTDLP_ON_START": "false"
"UPDATE_YTDLP_ON_START": "false",
"TG_API_SERVER": "http://localhost:8081",
"FILE_SIZE_LIMIT": "50"
}
},
"IIS Express": {
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

[![Docker](https://img.shields.io/docker/pulls/brianallred/telegram-video-bot)](https://hub.docker.com/r/brianallred/telegram-video-bot/)

Telegram bot that facilitates downloading videos from various websites and services in order to more easily to distribute them. This bot is mostly intended for shorter videos (for example, TikTok and Twitter). Due to Telegram API limits, videos bigger than 50MB have to be transcoded to 50MB or less. This means long videos will take a long time to process and will be of (potentially greatly) reduced quality.
Telegram bot that facilitates downloading videos from various websites and services in order to more easily to distribute them. This bot is mostly intended for shorter videos (for example, TikTok and Twitter). Due to public Telegram API limits, videos bigger than 50MB have to be transcoded to 50MB or less. This means long videos will take a long time to process and will be of (potentially greatly) reduced quality. This can be avoided by providing a private API server base URL.

Uses YT-DLP and FFMpeg under the hood. Supports hardware acceleration, but it will fall back to software transcoding.

Expand All @@ -12,9 +12,11 @@ Uses YT-DLP and FFMpeg under the hood. Supports hardware acceleration, but it wi

- `TG_BOT_TOKEN`: Bot token obtained from Botfather. Required.
- `TG_BOT_NAME`: Name used in `/help` and `/start` command text. Optional, defaults to `Frozen's Video Bot`.
- `TG_API_SERVER`: Base URL of the Telegram API server to use. Optional, defaults to the public API.
- `UPDATE_YTDLP_ON_START`: Update the local installation of YT-DLP on start. Optional, defaults to false. Highly recommended in container deployments.
- `YTDLP_UPDATE_BRANCH`: The code branch to use when YT-DLP updates on start (if `UPDATE_YTDLP_ON_START` is true). Optional, defaults to `release`.
- `DOWNLOAD_QUEUE_LIMIT`: Number of videos allowed in each user's download queue. Optional, defaults to 5.
- `FILE_SIZE_LIMIT`: File size limit of videos in megabytes. Optional, defaults to 50.
- `TZ`: Timezone. Optional, defaults to UTC.

### Docker Compose
Expand Down
2 changes: 1 addition & 1 deletion TelegramVideoBot.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<PackageReference Include="FFMpegCore" Version="5.1.0" />
<PackageReference Include="Telegram.Bot" Version="19.0.0" />
<PackageReference Include="GitVersion.MsBuild" Version="5.12.0">
<PrivateAssets>All</PrivateAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

Expand Down
4 changes: 4 additions & 0 deletions Utilities/EnvironmentConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,8 @@ public class EnvironmentConfig
public bool UpdateYtDlpOnStart => bool.Parse(Environment.GetEnvironmentVariable("UPDATE_YTDLP_ON_START") ?? "false");
public int DownloadQueueLimit => int.Parse(Environment.GetEnvironmentVariable("DOWNLOAD_QUEUE_LIMIT") ?? "5");
public string YtDlpUpdateBranch => Environment.GetEnvironmentVariable("YTDLP_UPDATE_BRANCH") ?? "release";
public string? TelegramApiServer => Environment.GetEnvironmentVariable("TG_API_SERVER");

// The Telegram public API limit is 50MB
public int FileSizeLimit => int.Parse(Environment.GetEnvironmentVariable("FILE_SIZE_LIMIT") ?? "50");
}
7 changes: 4 additions & 3 deletions Workers/DownloadManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@

namespace TelegramVideoBot.Workers;

public class DownloadManager(ITelegramBotClient client, long userId, int queueLimit, ILogger logger)
public class DownloadManager(ITelegramBotClient client, long userId, int queueLimit, int fileSizeLimit, ILogger logger)
{
private readonly ConcurrentQueue<DownloadInfo> downloads = new();
private readonly long userId = userId;
private readonly ITelegramBotClient client = client;
private readonly int queueLimit = queueLimit;
private readonly ILogger logger = logger;
private readonly int fileSizeLimit = fileSizeLimit;

private bool downloading;

Expand Down Expand Up @@ -89,7 +90,7 @@ private async Task StartDownloads()
filePath = Directory.GetFiles("./").Where(file => file.StartsWith($"./{userId}")).First()[2..];

var videoFileInfo = new FileInfo(filePath);
if (videoFileInfo.Length > 50 * 1000 * 1000)
if (videoFileInfo.Length > fileSizeLimit * 1000 * 1000)
{
await client.SendTextMessageAsync(download.ChatId, $"Video `{download.VideoUrl}` is larger than 50MB and requires further compression, please wait\\.", parseMode: ParseMode.MarkdownV2, replyToMessageId: download.ReplyId);
CompressVideo(filePath);
Expand Down Expand Up @@ -135,7 +136,7 @@ private void CompressVideo(string filePath)
{
var newFilePath = $"{Path.GetFileNameWithoutExtension(filePath)}_new.mp4";

var targetSizeInKiloBits = 45 * 1000 * 8; // 45MB target size, API limit is 50
var targetSizeInKiloBits = (fileSizeLimit - 5) * 1000 * 8;
var mediaInfo = FFProbe.Analyse(filePath);
var totalBitRate = (targetSizeInKiloBits / mediaInfo.Duration.TotalSeconds) + 1;
var audioBitRate = 128;
Expand Down
6 changes: 3 additions & 3 deletions Workers/UpdateHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ public class UpdateHandler(EnvironmentConfig config, ILogger<UpdateHandler> logg
{
private readonly Dictionary<long, DownloadManager> downloadManagers = new();
private readonly string botName = config.TelegramBotName ?? "Frozen's Video Bot";
private readonly int queueLimit = config.DownloadQueueLimit;
private readonly ILogger<UpdateHandler> logger = logger;
private readonly EnvironmentConfig config = config;

public async Task HandleUpdateAsync(ITelegramBotClient client, Update update, CancellationToken cancellationToken = new())
{
Expand Down Expand Up @@ -65,7 +65,7 @@ public class UpdateHandler(EnvironmentConfig config, ILogger<UpdateHandler> logg

if (!downloadManagers.TryGetValue(userId, out var manager))
{
manager = new(client, userId, queueLimit, logger);
manager = new(client, userId, config.DownloadQueueLimit, config.FileSizeLimit, logger);
downloadManagers.Add(userId, manager);
}

Expand Down Expand Up @@ -140,7 +140,7 @@ public class UpdateHandler(EnvironmentConfig config, ILogger<UpdateHandler> logg
logger.LogError(ex, ex.Message);
}

replyBuilder = new StringBuilder($"Also, each user can queue up to {queueLimit} videos at a time. You can do this by sending multiple messages or alternatively sending multiple video links within the same message separated by line breaks or spaces.");
replyBuilder = new StringBuilder($"Also, each user can queue up to {config.DownloadQueueLimit} videos at a time. You can do this by sending multiple messages or alternatively sending multiple video links within the same message separated by line breaks or spaces.");

try
{
Expand Down

0 comments on commit 2dac2e1

Please sign in to comment.