Introduction to C# User Bots with WTelegramClient
Tags: csharp, telegram, opensource, tutorial
Published: 2023-12-17 19:30:16

In the dynamic landscape of bot development, Telegram stands out as a popular platform, offering a rich(and sometimes confusing) set of APIs for creating fascinating User Bots. If you're venturing into Telegram API development using C#, the `WTelegramClient`(AKA _WTC_) library is a powerful tool that deserves your attention.


## Different Types of Bots In Telegram

before we continue, lets talk about Different bots in Telegram Ecosystem, what the heck is "User Bot" or "Client Bot" or "API" Bot ? what's the difference?

### First One
Telegram allows you to create bots (daaah?) that runs on the cloud and can receives and send content;

> some popular examples of these bots are [BotFather](https://t.me/BotFather) or [ChatId Bot](https://t.me/chatIDrobot) which is used to get the users numerical IDS and many other bots.

these bots are known as "API bots" or "Telegram Bots" mainly because they have a separate and dedicated API that is much simpler and easier to work with, which is not the topic of this article. BUT there is also another type of Bot.

### Second One
the second types are the one that can log-in to your account via your phone number, these bots are known as "**_User Bots_**" / "**_Client Bots_**" or in some cases "**_Self Bot_**" because, well they are basically what the Official Client Applications use on Android Or other platforms, that's right, Your Telegram App in your Phone is using "**Client API**" to interact with Telegram, which is what we are going to talk about in this article.

## So what `WTelegramClient` can do ? what roles it plays?

well, It can do anything! you can create Both User Bots and API Bots. But it is mainly used to create user bots; and That's what we are going to do now!

WTC handles all the low-level details of Communications between Telegram and your C# code and gives you a nice and *Right amount* of abstractions to work with, what I mean by "Right Amount"? well, it's not something like other libraries(e.g: [telethon](https://docs.telethon.dev/en/stable/) which is a great tool BTW ) that abstract most of the details and exposes a little bit of information.

> well isn't that a good thing? you might say

yes and no, too much abstraction "can" take away the flexibility, at least this is what I saw in my experience. The `WTelegramClient` library only abstract the painful part of The Code and lets you do whatever you want to do with the rest! you can build basically a fully functional Client Application that can do 100% of the official client features. with less pain indeed.

alright enough with the talking and theory BS, Lets Write some Code!

## Creating A `Hello world` application in WTC


## 1. Install The Library
first of all add the WTC ([nuget](https://www.nuget.org/packages/WTelegramClient/)) to your dependencies:

`$ dotnet add package WTelegramClient`

great! now that you installed the library its time to gather some information.

## 2.required properties

in order to write Telegram User Bots, unlike regular "Bot APIs" you need 2 unique things besides your **phone number**: 

- API Hash
- API ID

what are these? well we are not going into detail but these are used to Identify who is sending the request to telegram and who created the application in the first place.
to fetch these you can easily go to the [Telegram Site](https://my.telegram.org/), Enter your phone number, enter the code and after that you see 3 options: 

- API development tools
- Delete account
- Log out

click `Delete Account` and .. no Just Kidding, **click the First one which** will redirect you to [this url](https://my.telegram.org/apps) then you can create a application with whatever name you want and WALLA!, you got your **Api_id** and **api_hash**

now that we have these things we can continue writing our code.

## 3. writing the Basic

first we need to provide our information to WTC, so we create a function called `Config`: 
```csharp
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
    }
}
```
this function accepts a string and also returns a string, its like a `Dictionary<String, String>`, we are just mapping the WTC requirements to their proper values, so here you can put your ApiHash, ApiId, Phone and your 2FA password.

and now we can create our first instance of WTC:
```csharp
using var client = new WTelegram.Client(Config);
```
simple as that! notice that we are not doing `Client(Config());` but rather we are passing the `Function` itself and not its returning value! that's really important because WTC will automatically determine which piece of data it needs!
also don't forget the `using` at the beginning, otherwise you might face some issues related to resources not getting released!

alright, we have a client now, what can we do with it ? nothing...yet.
if you run the code now, nothing will happen, why? because you didn't **login**!

## 4.login
logging in to telegram is simple as writing a single line of code:

```csharp
await client.LoginUserIfNeeded();
```

notice that you also have a `client.LoginBotIfNeeded()` which is used for creating "API bots", cool!.
now if we run the code you should see something similar to this in the console:
```
WTelegramClient {version} running under .NET {version}
Connecting to {IP of the DC}
4>Sending   InvokeWithLayer`1                        #D8BE
4>Receiving RpcResult                                2023-12-14 14:18:19Z
             → Config                                #D8BE
Connected to DC 4... default_p2p_contacts, revoke_pm_inbox

....
             → Auth_SentCode                         #AE32
A verification code has been sent via App
Code: 
```
now its the time to enter the code that telegram sent to your account, note that you "can't" create new accounts with unofficial clients, this means you have to create your account with an official client first and then use the "Client API", unfortunately!

after entering the code, if you have a 2FA password enabled, you should see something like this:

```
→ RpcError 401 SESSION_PASSWORD_NEEDED  #66D1
→ Account_Password                      #878D

Verifying encryption key safety... (this should happen only once per DC)
This account has enabled 2FA. A password is needed. 
```
now if you wrote the correct password in the `Config` function, you should be able to login successfully and see the client disposing without errors:

```
4>Disposing the client
4>Sending   MsgsAck                                  2023-12-14  (svc)

Process finished with exit code 0.

```
BUT if you entered the wrong password you will get: 

```
→ RpcError 400 PASSWORD_HASH_INVALID    #B05E
Wrong password!
```
don't worry, just check your password and run the program again!

## 5.the session

before we move on, lets talk a little bit about sessions, what are they? well go to the `bin` directory in your project, next to the `Debug/Release` directories, you see a file named `WTelegram.session` which **if** you logged in successfully you should see it and its size should be more than 0 Bytes.

this is there WTC stores everything related to your state, Authentication and some other details.
> some libraries store information about messages, chats, `access_hashes` (which we will discuss later) ..etc. WTC does NOT store these information and its up to the users of this library to handle them

using this file, you can login once and the next time resume the existing session instead of login.
now go ahead and run your program one more time:

```
Loaded previous session
WTelegramClient {version} running under .NET {version}
Connecting to {DC IP}
....
4>Disposing the client
Process finished with exit code 0.

```
notice the first line :`Loaded previous session`, you are using the pre-stored data to connect to the telegram, without entering the code again, that why our login method is called `client.LoginUserIfNeeded()` and not `client.LoginUser()`, we only login if we don't have a valid session file present in the **default session path**.

### changing the default session path

you can also change this `path`, for example I want the session to be next to my application.exe file, we need to add one more line to the `Config` function:

```csharp
// create the path

static string Config(string what)
{
    switch (what)
    {
        // the new "parameter"
        case "session_pathname": return Path.Combine(Environment.CurrentDirectory, "mysessionFILE.session");
        // other stuff
        default: return null;
    }
}
```

now if you run the program again, you should see that it doesn't say `Loaded previous session` and its asking for a code, because we moved the session to a new place.
after this if we run it one more time, it reads the `mysessionFILE.session` and does not ask for the code again! pretty cool.

> if you are facing any issue related to the session not being parsed or corruption, just try to delete the session file and login again!

## 6. HELLO WORLD, finally

now that we are familiar with sessions, lets just print hello world!

```csharp
//login stuff
//...

await client.SendMessageAsync(InputPeer.Self, "hello WTC world!");
```
now run the program and take a look at your saved messages inside the official client, can you see the "hello WTC world!" ? you should.


## Conclusion 
well congratulations! you finally made it! welcome to the world of Telegram Client Development where you will suffer every single second trying to understand the [telegram documentations](https://core.telegram.org/methods) and figure out how to do things! but don't worry, we will help you:

[Examples of different methods](https://wiz0u.github.io/WTelegramClient/EXAMPLES)

[WTC Telegram Chat](https://t.me/WTelegramClient)

[WTC Documentations](https://wiz0u.github.io/WTelegramClient/)

[Github Page](https://github.com/wiz0u/WTelegramClient)

[Telegram Documentations](https://core.telegram.org/api)

[All Telegram Method](https://core.telegram.org/methods)

all the code written in this article are available [here](https://github.com/MrAliSalehi/HelloWtc).