Skip to content

Commit

Permalink
Merge pull request #1462 from TelegramBots/develop
Browse files Browse the repository at this point in the history
Added helper DownloadFile(TGFile file, ...)
  • Loading branch information
wiz0u authored Feb 24, 2025
2 parents 06e0c26 + da5c749 commit 80dbc8d
Show file tree
Hide file tree
Showing 8 changed files with 35 additions and 56 deletions.
2 changes: 1 addition & 1 deletion .azure-pipelines/variables.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
variables:
- group: Integration Tests Variables
- name: versionPrefix
value: 22.4.3
value: 22.4.4
- name: versionSuffix
value: ''
- name: ciVersionSuffix
Expand Down
1 change: 0 additions & 1 deletion .gitpod.yml

This file was deleted.

18 changes: 5 additions & 13 deletions Telegram.Bot.sln
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,25 @@ EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C45387C6-C93F-4FD2-84A8-A69CCE93B7EE}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
.gitattributes = .gitattributes
.gitignore = .gitignore
CHANGELOG.md = CHANGELOG.md
CONTRIBUTING.md = CONTRIBUTING.md
Directory.Build.props = Directory.Build.props
global.json = global.json
LICENSE = LICENSE
README.md = README.md
THIRD_PARTY_NOTICES = THIRD_PARTY_NOTICES
.gitattributes = .gitattributes
.gitignore = .gitignore
.gitpod.yml = .gitpod.yml
LICENSE = LICENSE
Directory.Build.props = Directory.Build.props
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".azure-pipelines", ".azure-pipelines", "{71662597-40F2-4192-AC4D-5FB9A1F12642}"
ProjectSection(SolutionItems) = preProject
.azure-pipelines\ci.yml = .azure-pipelines\ci.yml
.azure-pipelines\external-release-publish.yml = .azure-pipelines\external-release-publish.yml
.azure-pipelines\full-integration-tests.yml = .azure-pipelines\full-integration-tests.yml
.azure-pipelines\non-interactive-integration-tests.yml = .azure-pipelines\non-interactive-integration-tests.yml
.azure-pipelines\release-pipeline.yml = .azure-pipelines\release-pipeline.yml
.azure-pipelines\variables.yml = .azure-pipelines\variables.yml
.azure-pipelines\external-release-publish.yml = .azure-pipelines\external-release-publish.yml
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "jobs", "jobs", "{C20A563E-603B-49E8-A954-DB90D4F351DE}"
Expand All @@ -51,8 +50,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".devcontainer", ".devcontai
.devcontainer\Dockerfile = .devcontainer\Dockerfile
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EnumSerializer.Generator", "src\EnumSerializer.Generator\EnumSerializer.Generator.csproj", "{C246B54F-018B-4589-B26D-C38D7846FFF2}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -71,10 +68,6 @@ Global
{AAB9E3BA-D749-4D38-9021-EBD8D0BC8975}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AAB9E3BA-D749-4D38-9021-EBD8D0BC8975}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AAB9E3BA-D749-4D38-9021-EBD8D0BC8975}.Release|Any CPU.Build.0 = Release|Any CPU
{C246B54F-018B-4589-B26D-C38D7846FFF2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C246B54F-018B-4589-B26D-C38D7846FFF2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C246B54F-018B-4589-B26D-C38D7846FFF2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C246B54F-018B-4589-B26D-C38D7846FFF2}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -86,7 +79,6 @@ Global
{71662597-40F2-4192-AC4D-5FB9A1F12642} = {C45387C6-C93F-4FD2-84A8-A69CCE93B7EE}
{C20A563E-603B-49E8-A954-DB90D4F351DE} = {71662597-40F2-4192-AC4D-5FB9A1F12642}
{4897F36C-2F57-48A7-B425-D8F695E0AC0D} = {C45387C6-C93F-4FD2-84A8-A69CCE93B7EE}
{C246B54F-018B-4589-B26D-C38D7846FFF2} = {838231A4-B081-44B0-AC16-DC4C2FABAE86}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F6A9C4CA-DF26-4772-9119-627935D70E7C}
Expand Down
13 changes: 10 additions & 3 deletions src/Telegram.Bot/ITelegramBotClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,21 @@ public interface ITelegramBotClient
/// <returns><see langword="true"/> if token is valid</returns>
Task<bool> TestApi(CancellationToken cancellationToken = default);

/// <summary>Use this method to download a file. Get <paramref name="filePath"/> by calling
/// <see cref="TelegramBotClientExtensions.GetFile(ITelegramBotClient, string, CancellationToken)"/></summary>
/// <param name="filePath">Path to file on server</param>
/// <summary>Use this method to download a file after calling <see cref="TelegramBotClientExtensions.GetFile">GetFile</see></summary>
/// <param name="filePath">Path to file on Telegram</param>
/// <param name="destination">Destination stream to write file to</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="ArgumentException">filePath is <see langword="null"/>, empty or too short</exception>
/// <exception cref="ArgumentNullException"><paramref name="destination"/> is <see langword="null"/></exception>
Task DownloadFile(string filePath, Stream destination, CancellationToken cancellationToken = default);

/// <summary>Use this method to download a file after calling <see cref="TelegramBotClientExtensions.GetFile">GetFile</see></summary>
/// <param name="file">File on Telegram</param>
/// <param name="destination">Destination stream to write file to</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="ArgumentException">filePath is <see langword="null"/>, empty or too short</exception>
/// <exception cref="ArgumentNullException"><paramref name="destination"/> is <see langword="null"/></exception>
Task DownloadFile(TGFile file, Stream destination, CancellationToken cancellationToken = default);
}

public static partial class TelegramBotClientExtensions
Expand Down
4 changes: 4 additions & 0 deletions src/Telegram.Bot/TelegramBotClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,10 @@ public async Task<bool> TestApi(CancellationToken cancellationToken = default)
/// <param name="fileId">Identifier of file (Base64)</param>
public static FileIdType GetFileIdType(string fileId) => (FileIdType)Convert.FromBase64String(fileId[0..4])[0];

/// <inheritdoc/>
public Task DownloadFile(TGFile file, Stream destination, CancellationToken cancellationToken = default)
=> DownloadFile(file.FilePath!, destination, cancellationToken);

/// <inheritdoc/>
public async Task DownloadFile(string filePath, Stream destination, CancellationToken cancellationToken = default)
{
Expand Down
1 change: 1 addition & 0 deletions src/Telegram.Bot/TelegramBotClientExtensions.ApiMethods.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// MOSTLY GENERATED FILE - DO NOT MODIFY MANUALLY unless you know what you're doing
using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot.Requests;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ public async Task Should_Send_Contact()
[Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SendContact)]
public async Task Should_Send_Contact_With_VCard()
{
string vcard =
"""
string vcard = """
BEGIN:VCARD
VERSION:2.1
N:Gump;Forrest;;Mr.
Expand All @@ -52,7 +51,7 @@ public async Task Should_Send_Contact_With_VCard()
EMAIL:[email protected]
REV:20080424T195243Z
END:VCARD
""".Replace("\r", "");
""";

Message message = await BotClient.SendContact(
chatId: Fixture.SupergroupChat,
Expand All @@ -63,6 +62,6 @@ public async Task Should_Send_Contact_With_VCard()

Assert.Equal(MessageType.Contact, message.Type);
Assert.NotNull(message.Contact);
Assert.Equal(vcard, message.Contact.Vcard);
Assert.Equal(vcard.Replace("\r", ""), message.Contact.Vcard);
}
}
45 changes: 11 additions & 34 deletions test/Telegram.Bot.Tests.Unit/Polling/MockTelegramBotClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ public class MockClientOptions
public int RequestDelay { get; set; } = 10;
public Exception? ExceptionToThrow { get; set; }
public CancellationToken GlobalCancelToken { get; set; }

}

public class MockTelegramBotClient : ITelegramBotClient
Expand All @@ -33,25 +32,21 @@ public class MockTelegramBotClient : ITelegramBotClient

public MockTelegramBotClient(MockClientOptions? options = default)
{
Options = options ?? new MockClientOptions();
_messages = new(
Options.Messages.Select(message => message.Split('-').ToArray())
);
Options = options ?? new();
_messages = new(Options.Messages.Select(message => message.Split('-')));
}

public MockTelegramBotClient(params string[] messages)
{
Options = new();
_messages = new(messages.Select(message => message.Split('-').ToArray()));
_messages = new(messages.Select(message => message.Split('-')));
}

public Task<TResponse> MakeRequestAsync<TResponse>(IRequest<TResponse> request, CancellationToken cancellationToken = default)
=> SendRequest(request, cancellationToken);
public Task<TResponse> MakeRequest<TResponse>(IRequest<TResponse> request, CancellationToken cancellationToken = default)
=> SendRequest(request, cancellationToken);
public async Task<TResponse> SendRequest<TResponse>(
IRequest<TResponse> request,
CancellationToken cancellationToken = default)
public async Task<TResponse> SendRequest<TResponse>(IRequest<TResponse> request, CancellationToken cancellationToken = default)
{
if (request is not GetUpdatesRequest getUpdatesRequest)
throw new NotSupportedException() { Data = { ["request"] = request } };
Expand All @@ -62,60 +57,42 @@ public async Task<TResponse> SendRequest<TResponse>(
if (getUpdatesRequest.Offset.HasValue && getUpdatesRequest.Offset == lastOffsetRequested && _messages.Count != 0)
throw new InvalidOperationException("Repeating same request.Offset is not supported");
lastOffsetRequested = getUpdatesRequest.Offset;
if (Options.ExceptionToThrow is not null) { throw Options.ExceptionToThrow; }
if (Options.ExceptionToThrow is not null) throw Options.ExceptionToThrow;

if (Options.HandleNegativeOffset && getUpdatesRequest.Offset == -1)
{
int messageCount = _messages.Select(group => @group.Length).Sum() + 1;
string lastMessage = _messages.Last().Last();

_messages.Clear();

return (TResponse)(object) new[]
{
new Update
{
Message = new()
{
Text = lastMessage
},
Message = new() { Text = lastMessage },
Id = messageCount
}
};
}

if (!_messages.TryDequeue(out string[]? messages))
{
return (TResponse)(object)Array.Empty<Update>();
}

return (TResponse)(object)messages.Select((_, i) => new Update
{
Message = new()
{
Text = messages[i]
},
Message = new() { Text = messages[i] },
Id = getUpdatesRequest.Offset ?? 0 + i + 1
}).ToArray();
}

public TimeSpan Timeout { get; set; } = TimeSpan.FromMilliseconds(50);

public IExceptionParser ExceptionsParser { get; set; } = new DefaultExceptionParser();

// ---------------
// NOT IMPLEMENTED
// ---------------

// NOT IMPLEMENTED:
public bool LocalBotServer => throw new NotImplementedException();
public long BotId => throw new NotImplementedException();
public event AsyncEventHandler<ApiRequestEventArgs>? OnMakingApiRequest;
public event AsyncEventHandler<ApiResponseEventArgs>? OnApiResponseReceived;
public Task DownloadFile(
string filePath,
Stream destination,
CancellationToken cancellationToken = default) =>
throw new NotImplementedException();
public Task<bool> TestApi(CancellationToken cancellationToken = default) =>
throw new NotImplementedException();
public Task DownloadFile(string filePath, Stream destination, CancellationToken cancellationToken = default) => throw new NotImplementedException();
public Task DownloadFile(TGFile file, Stream destination, CancellationToken cancellationToken = default) => throw new NotImplementedException();
public Task<bool> TestApi(CancellationToken cancellationToken = default) => throw new NotImplementedException();
}

0 comments on commit 80dbc8d

Please sign in to comment.