Giter Club home page Giter Club logo

telegram.bots's Introduction

Telegram.Bots

A .NET Standard 2.1 wrapper for the Telegram Bot API 6.2.

Status Nuget Downloads License

Usage

Configure the Bot Client

using System;
using Microsoft.Extensions.DependencyInjection;
using Telegram.Bots;

IServiceProvider provider = new ServiceCollection()
  .AddBotClient("<bot-token>")
  .Services
  .BuildServiceProvider();

IBotClient bot = provider.GetRequiredService<IBotClient>();

Or Configure the Bot Client with a Web Proxy

using System;
using Microsoft.Extensions.DependencyInjection;
using Telegram.Bots;

IServiceProvider provider = new ServiceCollection()
  .AddBotClient("<bot-token>")
  .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
  {
    Proxy = new WebProxy(Host: "<your-host>", Port: 1234),
    UseProxy = true
  })
  .Services
  .BuildServiceProvider();

IBotClient bot = provider.GetRequiredService<IBotClient>();

Get Bot Information

using Telegram.Bots.Requests;
using Telegram.Bots.Types;

// ...

GetMe request = new();

Response<MyBot> response = await bot.HandleAsync(request);

if (response.Ok)
{
  MyBot myBot = response.Result;

  Console.WriteLine(myBot.Id);
  Console.WriteLine(myBot.FirstName);
  Console.WriteLine(myBot.Username);
}
else
{
  Failure failure = response.Failure;

  Console.WriteLine(failure.Description);
}

Send a Text via Chat Id

using Telegram.Bots.Requests;
using Telegram.Bots.Types;

// ...

SendText request = new(chatId: 123456789, text: "Hello!");

Response<TextMessage> response = await bot.HandleAsync(request);

if (response.Ok)
{
  TextMessage message = response.Result;

  Console.WriteLine(message.Id);
  Console.WriteLine(message.Text);
  Console.WriteLine(message.Date.ToString("G"));
}
else
{
  Failure failure = response.Failure;

  Console.WriteLine(failure.Description);
}

Send a Text via Chat Username

using Telegram.Bots.Requests.Usernames;
using Telegram.Bots.Types;

// ...

SendText request = new(username: "@chat", text: "Hello!");

Response<TextMessage> response = await bot.HandleAsync(request);

if (response.Ok)
{
  TextMessage message = response.Result;

  // ...
}
else
{
  Failure failure = response.Failure;

  // ...
}

Send an Audio File via Chat Id

using Telegram.Bots.Requests;
using Telegram.Bots.Types;

// ...

await using var audioStream = System.IO.File.OpenRead("/path/to/audio.mp3");

SendAudioFile request = new(chatId: 123456789, audio: audioStream);

Response<AudioMessage> response = await bot.HandleAsync(request);

if (response.Ok)
{
  AudioMessage message = response.Result;

  Console.WriteLine(message.Id);
  Console.WriteLine(message.Audio.Id);
  Console.WriteLine(message.Audio.Title);
  Console.WriteLine(message.Audio.Performer);
  Console.WriteLine(message.Audio.Duration);
}
else
{
  Failure failure = response.Failure;

  Console.WriteLine(failure.Description);
}

Send a Cached Video via Chat Username

using Telegram.Bots.Requests.Usernames;
using Telegram.Bots.Types;

// ...

SendCachedVideo request = new(username: "@chat", video: "<file-id>")
{
  Caption = "New Caption"
};

Response<VideoMessage> response = await bot.HandleAsync(request);

if (response.Ok)
{
  VideoMessage message = response.Result;

  Console.WriteLine(message.Id);
  Console.WriteLine(message.Video.Id);
  Console.WriteLine(message.Video.Name);
  Console.WriteLine(message.Caption);
}
else
{
  Failure failure = response.Failure;

  Console.WriteLine(failure.Description);
}

Send a Media Group via Chat Id

using Telegram.Bots.Requests;
using Telegram.Bots.Types;

await using var photoStream = System.IO.File.OpenRead("path/to/photo.png");
await using var videoStream = System.IO.File.OpenRead("path/to/video.mp4");

var request = new SendMediaGroup(chatId: 123456789, new List<IGroupableMedia>
{
  new CachedPhoto("<photo-file-id>"),
  new CachedVideo("<video-file-id>"),
  new PhotoUrl(new Uri("https://example.com/photo.png")),
  new VideoUrl(new Uri("https://example.com/video.mp4")),
  new PhotoFile(photoStream),
  new VideoFile(videoStream)
})
{
  DisableNotification = true
};

Response<IReadOnlyList<MediaGroupMessage>> response = await bot.HandleAsync(request);

if (response.Ok)
{
  foreach (var mediaGroupMessage in response.Result)
  {
    switch (mediaGroupMessage)
    {
      case PhotoMessage message:
        Console.WriteLine(message.PhotoSet.Count);
        break;
      case VideoMessage message:
        Console.WriteLine(message.Video.Name);
        break;
    }
  }
}
else
{
  Failure failure = response.Failure;

  Console.WriteLine(failure.Description);
}

Download a File

using Telegram.Bots.Types;

await using var stream = System.IO.File.OpenWrite("path/to/file.extension");

Response<FileInfo> response = await bot.HandleAsync("<file-id>", stream);

Configuring the Serializer with ASP.NET Core

using Microsoft.Extensions.DependencyInjection;
using Telegram.Bots.Extensions.AspNetCore;

// ...

IServiceCollection services = ...

services.AddControllers()
        .AddBotSerializer();

Configuring Long Polling with Telegram.Bots

using Microsoft.Extensions.DependencyInjection;
using Telegram.Bots;
using Telegram.Bots.Extensions.Polling;

...

IServiceCollection services = ...

services.AddBotClient("<bot-token>");
services.AddPolling<UpdateHandler>();

Configuring an Update Handler for Polled Updates

using Telegram.Bots.Extensions.Polling;
using Telegram.Bots.Requests;
using Telegram.Bots.Types;

...

public sealed class UpdateHandler : IUpdateHandler
{
  public Task HandleAsync(IBotClient bot, Update update, CancellationToken token)
  {
    return update switch
    {
      MessageUpdate u when u.Data is TextMessage message =>
        bot.HandleAsync(new SendText(message.Chat.Id, message.Text), token),

      EditedMessageUpdate u when u.Data is TextMessage message =>
        bot.HandleAsync(new SendText(message.Chat.Id, message.Text)
        {
          ReplyToMessageId = message.Id
        }, token),

      _ => Task.CompletedTask
    };
  }
}

License

Telegram.Bots is a .NET Standard 2.1 wrapper for the Telegram Bot API 6.2.
Copyright © 2020-2023 Aman Agnihotri ([email protected])

Telegram.Bots is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Telegram.Bots is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with Telegram.Bots. If not, see GNU Licenses.


telegram.bots's People

Contributors

amanagnihotri avatar miloradowicz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

telegram.bots's Issues

No support for MessageEntity.TextLink to add URL to caption text

I'm building a little app to share photos from Flickr to a Telegram channel. As part of that, I'd like to link back to the original photo in the caption.

I can easily drop a link in there and that works fine, but ideally I'd like to have it look nicer, by e.g. having something like View the original on Flickr! instead of just the URL.

Going by the Telegram docs, what I need is a message entity of type "textUrl". The value is present on the MessageEntity enum, but I can't find a way to add the fourth parameter (the URL) onto the message entity. Any advice? 🙏

The code I'm using looks like follows:

var caption = $"{photoToPost.Title}\n\nView original on Flickr";

var request = new SendPhotoUrl(_options.TargetChatId, photoToPost.PhotoUrl, UriKind.Absolute))
{
    Caption = caption,
    CaptionEntities = new List<MessageEntity>
    {
        new MessageEntity(MessageEntityType.Bold, 0, (uint)photoToPost.Title.Length),
        // this no worky:
        new MessageEntity(MessageEntityType.TextLink, (uint)photoToPost.Title.Length, 23, photoToPost.WebUrl), // no parameter for URL available.
    }
};

return await _botClient.HandleAsync(request);

SendPhoto use MemoryStream is it possible?

When i trying to send photo with MemoryStream I get this:

Send Telegram photo {"ChatId":304667397, "Photo":{"Id":"79d1d33d-f54b-48a1-b337-b557622baad5", "Data":"System.IO.MemoryStream"}, "Method":"sendPhoto"} and get response {"Failure":{"Description":"Bad Request: file must be non-empty", "ErrorCode":400}, "Ok":false}.

Data is just use MemoryStream.ToString()?

Can you help me?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.