{"id":13414771,"url":"https://github.com/wiz0u/WTelegramClient","last_synced_at":"2025-03-14T22:32:03.546Z","repository":{"id":37772029,"uuid":"392475510","full_name":"wiz0u/WTelegramClient","owner":"wiz0u","description":"Telegram Client API (MTProto) library written 100% in C# and .NET","archived":false,"fork":false,"pushed_at":"2025-03-08T00:09:31.000Z","size":2710,"stargazers_count":1069,"open_issues_count":4,"forks_count":168,"subscribers_count":28,"default_branch":"master","last_synced_at":"2025-03-08T00:24:28.109Z","etag":null,"topics":["client","client-api","clientapi","csharp","dotnet","mtproto","tdlib","telegram","telegram-api","telegram-client","telegram-userbot","tlsharp","userbot"],"latest_commit_sha":null,"homepage":"https://wiz0u.github.io/WTelegramClient/","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/wiz0u.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"wiz0u","custom":["https://www.buymeacoffee.com/wizou","http://t.me/WTelegramClientBot?start=donate"]}},"created_at":"2021-08-03T22:40:10.000Z","updated_at":"2025-03-07T23:21:58.000Z","dependencies_parsed_at":"2023-11-07T04:00:04.310Z","dependency_job_id":"75c71e2b-f6fd-4215-97dc-430a9082c2f7","html_url":"https://github.com/wiz0u/WTelegramClient","commit_stats":{"total_commits":663,"total_committers":6,"mean_commits":110.5,"dds":0.3438914027149321,"last_synced_commit":"cbcb11e25e8b083c66909c1d0569ad8b8e10f608"},"previous_names":[],"tags_count":105,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wiz0u%2FWTelegramClient","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wiz0u%2FWTelegramClient/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wiz0u%2FWTelegramClient/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wiz0u%2FWTelegramClient/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/wiz0u","download_url":"https://codeload.github.com/wiz0u/WTelegramClient/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243456497,"owners_count":20293896,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["client","client-api","clientapi","csharp","dotnet","mtproto","tdlib","telegram","telegram-api","telegram-client","telegram-userbot","tlsharp","userbot"],"created_at":"2024-07-30T21:00:36.267Z","updated_at":"2025-03-14T22:32:03.536Z","avatar_url":"https://github.com/wiz0u.png","language":"C#","readme":"﻿[![API Layer](https://img.shields.io/badge/API_Layer-200-blueviolet)](https://corefork.telegram.org/methods)\n[![NuGet version](https://img.shields.io/nuget/v/WTelegramClient?color=00508F)](https://www.nuget.org/packages/WTelegramClient/)\n[![NuGet prerelease](https://img.shields.io/nuget/vpre/WTelegramClient?color=C09030\u0026label=dev+nuget)](https://www.nuget.org/packages/WTelegramClient/absoluteLatest)\n[![Donate](https://img.shields.io/badge/Help_this_project:-Donate-ff4444)](https://buymeacoffee.com/wizou)\n\n## *_Telegram Client API library written 100% in C# and .NET_*\n\nThis library allows you to connect to Telegram and control a user programmatically (or a bot, but [WTelegramBot](https://www.nuget.org/packages/WTelegramBot) is much easier for that).\nAll the Telegram Client APIs (MTProto) are supported so you can do everything the user could do with a full Telegram GUI client.\n\nLibrary was developed solely by one unemployed guy. [Donations are welcome](https://buymeacoffee.com/wizou).\n\nThis ReadMe is a **quick but important tutorial** to learn the fundamentals about this library. Please read it all.\n\n\u003e ⚠️ This library requires understanding advanced C# techniques such as **asynchronous programming** or **subclass pattern matching**...  \n\u003e If you are a beginner in C#, starting a project based on this library might not be a great idea.\n\n# How to use\n\nAfter installing WTelegramClient through [Nuget](https://www.nuget.org/packages/WTelegramClient/), your first Console program will be as simple as:\n```csharp\nstatic async Task Main(string[] _)\n{\n    using var client = new WTelegram.Client();\n    var myself = await client.LoginUserIfNeeded();\n    Console.WriteLine($\"We are logged-in as {myself} (id {myself.id})\");\n}\n```\nWhen run, this will prompt you interactively for your App **api_hash** and **api_id** (that you obtain through Telegram's\n[API development tools](https://my.telegram.org/apps) page) and try to connect to Telegram servers.\nThose api hash/id represent your application and one can be used for handling many user accounts.\n\nThen it will attempt to sign-in *(login)* as a user for which you must enter the **phone_number** and the **verification_code**\nthat will be sent to this user (for example through SMS, Email, or another Telegram client app the user is connected to).\n\nIf the verification succeeds but the phone number is unknown to Telegram, the user might be prompted to sign-up\n*(register their account by accepting the Terms of Service)* and provide their **first_name** and **last_name**.  \nIf the account already exists and has enabled two-step verification (2FA) a **password** might be required.  \nIn some case, Telegram may request that you associate an **email** with your account for receiving login verification codes,\nyou may skip this step by leaving **email** empty, otherwise the email address will first receive an **email_verification_code**.  \nAll these login scenarios are handled automatically within the call to `LoginUserIfNeeded`.\n\nAfter login, you now have access to the **[full range of Telegram Client APIs](https://corefork.telegram.org/methods)**. \nAll those API methods require `using TL;` namespace and are called with an underscore instead of a dot in the method name, like this: `await client.Method_Name(...)`\n\n# Saved session\nIf 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.\n\nThis is because WTelegramClient saves (typically in the encrypted file **bin\\WTelegram.session**) its state\nand the authentication keys that were negotiated with Telegram so that you needn't sign-in again every time.\n\nThat file path is configurable (**session_pathname**), and under various circumstances *(changing user or server address, write permissions)*\nyou may want to change it or simply delete the existing session file in order to restart the authentification process.\n\n# Non-interactive configuration\nYour 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.\n\nTo do this, you need to write a method that will provide the answers, and pass it on the constructor:\n```csharp\nstatic string Config(string what)\n{\n    switch (what)\n    {\n        case \"api_id\": return \"YOUR_API_ID\";\n        case \"api_hash\": return \"YOUR_API_HASH\";\n        case \"phone_number\": return \"+12025550156\";\n        case \"verification_code\": Console.Write(\"Code: \"); return Console.ReadLine();\n        case \"first_name\": return \"John\";      // if sign-up is required\n        case \"last_name\": return \"Doe\";        // if sign-up is required\n        case \"password\": return \"secret!\";     // if user has enabled 2FA\n        default: return null;                  // let WTelegramClient decide the default config\n    }\n}\n...\nusing var client = new WTelegram.Client(Config);\n```\nThere are other configuration items that are queried to your method but returning `null` let WTelegramClient choose a default adequate value.\nThose shown above are the only ones that have no default values and should be provided by your method.\n\nReturning `null` for verification_code or password will show a prompt for console apps, or an error otherwise\n*(see [FAQ #3](https://wiz0u.github.io/WTelegramClient/FAQ#GUI) for WinForms)*  \nReturning `\"\"` for verification_code requests the resending of the code through another system (SMS or Call).\n\nAnother simple approach is to pass `Environment.GetEnvironmentVariable` as the config callback and define the configuration items as environment variables\n*(undefined variables get the default `null` behavior)*.\n\nFinally, 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.\nIts `int` argument is the log severity, compatible with the [LogLevel enum](https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel).\n\n# Alternative simplified configuration \u0026 login\nSince version 3.0.0, a new approach to login/configuration has been added. Some people might find it easier to deal with:\n\n```csharp\nWTelegram.Client client = new WTelegram.Client(YOUR_API_ID, \"YOUR_API_HASH\"); // this constructor doesn't need a Config method\nawait DoLogin(\"+12025550156\"); // initial call with user's phone_number\n...\n//client.Dispose(); // the client must be disposed when you're done running your userbot.\n\nasync Task DoLogin(string loginInfo) // (add this method to your code)\n{\n   while (client.User == null)\n      switch (await client.Login(loginInfo)) // returns which config is needed to continue login\n      {\n         case \"verification_code\": Console.Write(\"Code: \"); loginInfo = Console.ReadLine(); break;\n         case \"name\": loginInfo = \"John Doe\"; break;    // if sign-up is required (first/last_name)\n         case \"password\": loginInfo = \"secret!\"; break; // if user has enabled 2FA\n         default: loginInfo = null; break;\n      }\n   Console.WriteLine($\"We are logged-in as {client.User} (id {client.User.id})\");\n}\n```\n\nWith this method, you can choose in some cases to interrupt the login loop via a `return` instead of `break`, and resume it later\nby calling `DoLogin(requestedCode)` again once you've obtained the requested code/password/etc...\nSee [WinForms example](https://wiz0u.github.io/WTelegramClient/Examples/WinForms_app.zip) and [ASP.NET example](https://wiz0u.github.io/WTelegramClient/Examples/ASPnet_webapp.zip)\n\n# Example of API call\n\n\u003e The Telegram API makes extensive usage of base and derived classes, so be ready to use the various C# syntaxes\nto check/cast base classes into the more useful derived classes (`is`, `as`, `case DerivedType` )\n\nAll the Telegram API classes/methods are fully documented through Intellisense: Place your mouse over a class/method name,\nor 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.\n\nThe Telegram [API object classes](https://corefork.telegram.org/schema) are defined in the `TL` namespace,\nand the [API functions](https://corefork.telegram.org/methods) are available as async methods of `Client`.\n\nBelow is an example of calling the [messages.getAllChats](https://corefork.telegram.org/method/messages.getAllChats) API function,\nenumerating the various groups/channels the user is in, and then using `client.SendMessageAsync` helper function to easily send a message:\n```csharp\nusing TL;\n...\nvar chats = await client.Messages_GetAllChats();\nConsole.WriteLine(\"This user has joined the following:\");\nforeach (var (id, chat) in chats.chats)\n    if (chat.IsActive)\n        Console.WriteLine($\"{id,10}: {chat}\");\nConsole.Write(\"Type a chat ID to send a message: \");\nlong chatId = long.Parse(Console.ReadLine());\nvar target = chats.chats[chatId];\nConsole.WriteLine($\"Sending a message in chat {chatId}: {target.Title}\");\nawait client.SendMessageAsync(target, \"Hello, World\");\n```\n\n➡️ You can find lots of useful code snippets in [EXAMPLES](https://wiz0u.github.io/WTelegramClient/EXAMPLES)\nand more detailed programs in the [Examples subdirectory](https://github.com/wiz0u/WTelegramClient/tree/master/Examples).  \n➡️ Check [the FAQ](https://wiz0u.github.io/WTelegramClient/FAQ#compile) if example codes don't compile correctly on your machine, or other troubleshooting.\n\n\u003ca name=\"terminology\"\u003e\u003c/a\u003e\n# Terminology in Telegram Client API\n\nIn the API, Telegram uses some terms/classnames that can be confusing as they differ from the terms shown to end-users:\n- `Channel`: A (large or public) chat group *(sometimes called [supergroup](https://corefork.telegram.org/api/channel#supergroups))*,\nor a [broadcast channel](https://corefork.telegram.org/api/channel#channels) (the `broadcast` flag differentiate those)\n- `Chat`: A private [basic chat group](https://corefork.telegram.org/api/channel#basic-groups) with less than 200 members\n(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 will be `deactivated`)  \n**⚠️ Most chat groups you see are really of type `Channel`, not `Chat`!**\n- **chats**: In plural or general meaning, it means either `Chat` or `Channel` *(therefore, no private user discussions)*\n- `Peer`: Either a `Chat`, a `Channel` or a `User`\n- **Dialog**: Status of chat with a `Peer` *(draft, last message, unread count, pinned...)*. It represents each line from your Telegram chat list.\n- **Access Hash**: Telegram requires you to provide a specific `access_hash` for users, channels, and other resources before interacting with them.\nSee [FAQ #4](https://wiz0u.github.io/WTelegramClient/FAQ#access-hash) to learn more about it.\n- **DC** (DataCenter): There are a few datacenters depending on where in the world the user (or an uploaded media file) is from.\n- **Session** or **Authorization**: Pairing between a device and a phone number. You can have several active sessions for the same phone number.\n- **Participant**: A member/subscriber of a chat group or channel\n\n# Other things to know\n\nThe Client class offers `OnUpdates` and `OnOther` events that are triggered when Telegram servers sends Updates (like new messages or status) or other notifications, independently of your API requests.  \nYou can also use the [UpdateManager class](https://wiz0u.github.io/WTelegramClient/FAQ#manager) to simplify the handling of such updates.  \nSee [Examples/Program_ListenUpdates.cs](https://github.com/wiz0u/WTelegramClient/blob/master/Examples/Program_ListenUpdates.cs?ts=4#L21) and [Examples/Program_ReactorError.cs](https://github.com/wiz0u/WTelegramClient/blob/master/Examples/Program_ReactorError.cs?ts=4#L30)\n\nAn invalid API request can result in a `RpcException` being raised, reflecting the [error code and status text](https://revgram.github.io/errors.html) of the problem.\n\nTo [prevent getting banned](https://wiz0u.github.io/WTelegramClient/FAQ#prevent-ban) during dev, you can connect to [test servers](https://docs.pyrogram.org/topics/test-servers), by adding this line in your Config callback:  \n`case \"server_address\": return \"2\u003e149.154.167.40:443\"; // test DC`\n\nThe other configuration items that you can provide include: **session_pathname, email, email_verification_code, session_key, device_model, system_version, app_version, system_lang_code, lang_pack, lang_code, firebase, user_id, bot_token**\n\nOptional API parameters have a default value of `null` when unset. Passing `null` for a required string/array is the same as *empty* (0-length).\nRequired API parameters/fields can sometimes be set to 0 or `null` when unused (check API documentation or experiment).\n\nI've added several useful converters, implicit cast or helper properties to various API objects so that they are more easy to manipulate.\n\nBeyond the TL async methods, the Client class offers a few other methods to simplify the sending/receiving of files, medias or messages,\nas well as generic handling of chats/channels.\n\nThis library works best with **.NET 5.0+** (faster, no dependencies) and is also available for **.NET Standard 2.0** (.NET Framework 4.6.1+ \u0026 .NET Core 2.0+) and **Xamarin/Mono.Android**\n\n# Library uses and limitations\nThis library can be used for any Telegram scenario including:\n- Sequential or parallel automated steps based on API requests/responses\n- Real-time [monitoring](https://wiz0u.github.io/WTelegramClient/EXAMPLES#updates) of incoming Updates/Messages\n- [Download](https://wiz0u.github.io/WTelegramClient/EXAMPLES#download)/[upload](https://wiz0u.github.io/WTelegramClient/EXAMPLES#upload) of files/media\n- Exchange end-to-end encrypted messages/files in [Secret Chats](https://wiz0u.github.io/WTelegramClient/EXAMPLES#e2e)\n- Building a full-featured interactive client\n\nIt has been tested in a Console app, [in Windows Forms](https://wiz0u.github.io/WTelegramClient/Examples/WinForms_app.zip),\n[in ASP.NET webservice](https://wiz0u.github.io/WTelegramClient/Examples/ASPnet_webapp.zip), and in Xamarin/Android.  \n\nDon't use this library for Spam or Scam. Respect Telegram [Terms of Service](https://telegram.org/tos)\nas well as the [API Terms of Service](https://core.telegram.org/api/terms) or you might get banned from Telegram servers.\n\nIf you read all this ReadMe, the [Frequently Asked Questions](https://wiz0u.github.io/WTelegramClient/FAQ),\nthe [Examples codes](https://wiz0u.github.io/WTelegramClient/EXAMPLES) and still have questions, feedback is welcome in our Telegram group [@WTelegramClient](https://t.me/WTelegramClient)\n\nIf you like this library, you can [buy me a coffee](https://buymeacoffee.com/wizou) ❤ This will help the project keep going.\n\n© 2021-2025 Olivier Marcoux\n","funding_links":["https://github.com/sponsors/wiz0u","https://www.buymeacoffee.com/wizou","http://t.me/WTelegramClientBot?start=donate","https://buymeacoffee.com/wizou"],"categories":["API","C# #"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwiz0u%2FWTelegramClient","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwiz0u%2FWTelegramClient","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwiz0u%2FWTelegramClient/lists"}