All Projects → wiz0u → WTelegramClient

wiz0u / WTelegramClient

Licence: MIT license
Telegram client API library written 100% in C# and .NET Standard

Programming Languages

C#
18002 projects

Projects that are alternatives of or similar to WTelegramClient

telegram client
library for help you make userbot or bot telegram and support tdlib telegram database and only support nodejs dart and google-apps-script
Stars: ✭ 38 (-80.21%)
Mutual labels:  telegram-api, telegram-client, userbot, telegram-userbot
Telegram-UserBot
Abandoned.. Moved to https://github.com/TeamDerUntergang/Telegram-SedenUserBot
Stars: ✭ 38 (-80.21%)
Mutual labels:  mtproto, userbot, telegram-userbot
nimgram
An MTProto client written in Nim 👑
Stars: ✭ 61 (-68.23%)
Mutual labels:  telegram-api, mtproto, telegram-client
tdlight-java
Complete Bot and Userbot Telegram library based on TDLib
Stars: ✭ 128 (-33.33%)
Mutual labels:  telegram-api, mtproto, telegram-userbot
telecharm-userbot
A powerful, cool and well-made userbot for your Telegram profile, with promising extension capabilities.
Stars: ✭ 17 (-91.15%)
Mutual labels:  telegram-api, userbot, telegram-userbot
DevelopersUserbot
Telegram Userbot Made for Developers by Developers
Stars: ✭ 25 (-86.98%)
Mutual labels:  userbot, telegram-userbot
AsenaUserBot
Asena UserBot is the most advantageous and fast UserBot with changeable language and permanent plugin system.
Stars: ✭ 133 (-30.73%)
Mutual labels:  userbot, telegram-userbot
Telegram-mailer
Web-application for sending messages to list of users. Use several accounts to avoid ban.
Stars: ✭ 28 (-85.42%)
Mutual labels:  telegram-api, telegram-client
aiotdlib
Python asyncio Telegram client based on TDLib https://github.com/tdlib/td
Stars: ✭ 63 (-67.19%)
Mutual labels:  telegram-api, mtproto
Nana-Bot
Telegram Modular Userbot using python3.7
Stars: ✭ 38 (-80.21%)
Mutual labels:  userbot, telegram-userbot
pyrubrum
An intuitive framework for creating Telegram bots.
Stars: ✭ 33 (-82.81%)
Mutual labels:  telegram-api, telegram-client
Mtproto Core
Telegram API JS (MTProto) client library for browser and nodejs
Stars: ✭ 242 (+26.04%)
Mutual labels:  telegram-api, mtproto
Telegramapi
Java library to create Telegram Clients
Stars: ✭ 198 (+3.13%)
Mutual labels:  telegram-api, mtproto
TelegramCommunicationJS
A pure script to communicate with Telegram server without any Third-party tools and library.
Stars: ✭ 21 (-89.06%)
Mutual labels:  mtproto, telegram-client
Pyrogram
Telegram MTProto API Client Library and Framework in Pure Python for Users and Bots
Stars: ✭ 2,252 (+1072.92%)
Mutual labels:  telegram-api, mtproto
Madelineproto
Async PHP client/server API for the telegram MTProto protocol
Stars: ✭ 1,776 (+825%)
Mutual labels:  telegram-api, mtproto
tgcf
The ultimate tool to automate custom telegram message forwarding. Live-syncer, Auto-poster, backup-bot, cloner, chat-forwarder, duplicator, ... Call it whatever you like! tgcf can fulfill your custom needs.
Stars: ✭ 378 (+96.88%)
Mutual labels:  mtproto, telegram-userbot
tdlight-telegram-bot-api
The TDLight Telegram Bot API is an actively enhanced fork of the original Bot API, featuring experimental user support, proxies, unlimited files size, and more.
Stars: ✭ 71 (-63.02%)
Mutual labels:  telegram-api, mtproto
Grammers
(tele)gramme.rs - use Telegram's API from Rust
Stars: ✭ 109 (-43.23%)
Mutual labels:  telegram-api, mtproto
Novagram
An Object-Oriented PHP library for Telegram Bots
Stars: ✭ 112 (-41.67%)
Mutual labels:  telegram-api, mtproto

NuGet version Build Status API Layer dev nuget Support Chat Donate

Telegram Client API library written 100% in C# and .NET Standard

This library allows you to connect to Telegram and control a user programmatically (or a bot, but Telegram.Bot is much easier for that). All the Telegram Client APIs (MTProto) are supported so you can do everything the user could do with a full Telegram GUI client.

This ReadMe is a quick but important tutorial to learn the fundamentals about this library. Please read it all.

⚠️ This library relies on asynchronous C# programming (async/await) so make sure you are familiar with this advanced topic before proceeding.
If you are a beginner in C#, starting a project based on this library might not be a great idea.

How to use

After installing WTelegramClient through Nuget, your first Console program will be as simple as:

static async Task Main(string[] _)
{
    using var client = new WTelegram.Client();
    var my = await client.LoginUserIfNeeded();
    Console.WriteLine($"We are logged-in as {my.username ?? my.first_name + " " + my.last_name} (id {my.id})");
}

When run, this will prompt you interactively for your App api_hash and api_id (that you obtain through Telegram's API development tools page) and try to connect to Telegram servers. Those api hash/id represent your application and one can be used for handling many user accounts.

Then it will attempt to sign-in (login) as a user for which you must enter the phone_number and the verification_code that will be sent to this user (for example through SMS or another Telegram client app the user is connected to).

If the verification succeeds but the phone number is unknown to Telegram, the user might be prompted to sign-up (register their account by accepting the Terms of Service) and provide their first_name and last_name.
If the account already exists and has enabled two-step verification (2FA) a password might be required.
All these login scenarios are handled automatically within the call to LoginUserIfNeeded.

And that's it, you now have access to the full range of Telegram Client APIs. All those API methods are available (with an underscore in the method name, instead of a dot), like this: await client.Method_Name(...)

Saved session

If you run this program again, you will notice that only api_hash is requested, the other prompts are gone and you are automatically logged-on and ready to go.

This is because WTelegramClient saves (typically in the encrypted file bin\WTelegram.session) its state and the authentication keys that were negotiated with Telegram so that you needn't sign-in again every time.

That file path is configurable (session_pathname), and under various circumstances (changing user or server address) you may want to change it or simply delete the existing session file in order to restart the authentification process.

Non-interactive configuration

Your next step will probably be to provide a configuration to the client so that the required elements are not prompted through the Console but answered by your program.

To do this, you need to write a method that will provide the answers, and pass it on the constructor:

static string Config(string what)
{
    switch (what)
    {
        case "api_id": return "YOUR_API_ID";
        case "api_hash": return "YOUR_API_HASH";
        case "phone_number": return "+12025550156";
        case "verification_code": Console.Write("Code: "); return Console.ReadLine();
        case "first_name": return "John";      // if sign-up is required
        case "last_name": return "Doe";        // if sign-up is required
        case "password": return "secret!";     // if user has enabled 2FA
        default: return null;                  // let WTelegramClient decide the default config
    }
}
...
using var client = new WTelegram.Client(Config);

There are other configuration items that are queried to your method but returning null let WTelegramClient choose a default adequate value. Those shown above are the only ones that have no default values and should be provided by your method. Returning null for verification_code or password will show a prompt for console apps, or an error otherwise. Returning "" for verification_code requests resending the code through another method (SMS or Call).

Another simple approach is to pass Environment.GetEnvironmentVariable as the config callback and define the configuration items as environment variables. Undefined variables get the default null behavior.

Finally, if you want to redirect the library logs to your logger instead of the Console, you can install a delegate in the WTelegram.Helpers.Log static property. Its int argument is the log severity, compatible with the LogLevel enum

Example of API call

ℹ️ The Telegram API makes extensive usage of base and derived classes, so be ready to use the various syntaxes C# offer to check/cast base classes into the more useful derived classes (is, as, case DerivedType )

All the Telegram API classes/methods are fully documented through Intellisense: Place your mouse over a class/method name, or start typing the call arguments to see a tooltip displaying their description, the list of derived classes and a web link to the official API page.

The Telegram API object classes are defined in the TL namespace, and the API functions are available as async methods of Client.

Below is an example of calling the messages.getAllChats API function, enumerating the various groups/channels the user is in, and then using client.SendMessageAsync helper function to easily send a message:

using TL;
...
var chats = await client.Messages_GetAllChats();
Console.WriteLine("This user has joined the following:");
foreach (var (id, chat) in chats.chats)
    switch (chat) // example of downcasting to their real classes:
    {
        case Chat smallgroup when smallgroup.IsActive:
            Console.WriteLine($"{id}:  Small group: {smallgroup.title} with {smallgroup.participants_count} members");
            break;
        case Channel group when group.IsGroup:
            Console.WriteLine($"{id}: Group {group.username}: {group.title}");
            break;
        case Channel channel:
            Console.WriteLine($"{id}: Channel {channel.username}: {channel.title}");
            break;
    }
Console.Write("Type a chat ID to send a message: ");
long chatId = long.Parse(Console.ReadLine());
var target = chats.chats[chatId];
Console.WriteLine($"Sending a message in chat {chatId}: {target.Title}");
await client.SendMessageAsync(target, "Hello, World");

➡️ You can find lots of useful code snippets in EXAMPLES.md and in the Examples subdirectory.

Terminology in Telegram Client API

In the API, Telegram uses some terms/classnames that can be confusing as they differ from the terms shown to end-users:

  • Channel : A (large or public) chat group (sometimes called supergroup) or a broadcast channel (the broadcast flag differentiate those)
  • Chat : A private simple chat group with less than 200 members (it may be migrated to a supergroup Channel with a new ID when it gets bigger or public, in which case the old Chat will still exist but be deactivated)
    ⚠️ Most chat groups you see are really of type Channel, not Chat!
  • chats : In plural or general meaning, it means either Chat or Channel
  • Peer : Either a Chat, Channel or a private chat with a User
  • Dialog : The current status of a chat with a Peer (draft, last message, unread count, pinned...). It represents each line from your Telegram chat list.
  • DC (DataCenter) : There are a few datacenters depending on where in the world the user (or an uploaded media file) is from.
  • Access Hash : Telegram requires you to provide a specific access_hash for users, channels, and other resources before interacting with them. See FAQ #4 to learn more about it.

Other things to know

The Client class also offers an Update event that is triggered when Telegram servers sends Updates (like new messages or status), independently of your API requests. See Examples/Program_ListenUpdates.cs

An invalid API request can result in a RpcException being raised, reflecting the error code and status text of the problem.

The other configuration items that you can override include: session_pathname, session_key, server_address, device_model, system_version, app_version, system_lang_code, lang_pack, lang_code, user_id

Optional API parameters have a default value of null when unset. Passing null for a required string/array is the same as empty (0-length). Required API parameters/fields can sometimes be set to 0 or null when unused (check API documentation or experiment).

I've added several useful converters, implicit cast or helper properties to various API objects so that they are more easy to manipulate.

Beyond the TL async methods, the Client class offers a few other methods to simplify the sending/receiving of files, medias or messages.

This library works best with .NET 5.0+ (faster, no dependencies) and is also available for .NET Standard 2.0 (.NET Framework 4.6.1+ & .NET Core 2.0+) and Xamarin/Mono.Android

Library uses and limitations

This library can be used for any Telegram scenarios including:

  • Sequential or parallel automated steps based on API requests/responses
  • Real-time monitoring of incoming Updates/Messages
  • Download/upload of files/media
  • Building a full-featured interactive client

It has been tested in a Console app, in a WinForms app, in ASP.NET webservice, and in Xamarin/Android.

Please don't use this library for Spam or Scam. Respect Telegram Terms of Service as well as the API Terms of Service or you might get banned from Telegram servers.

Developers feedback is welcome in the Telegram support group @WTelegramClient
You can also check our 📖 Frequently Asked Questions for more help and troubleshooting guide.

If you like this library, please consider a donation. This will help the project keep going.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].