Coder Social home page Coder Social logo

wiz0u / wtelegramclient Goto Github PK

View Code? Open in Web Editor NEW
934.0 29.0 153.0 4.8 MB

Telegram Client API (MTProto) library written 100% in C# and .NET

Home Page: https://wiz0u.github.io/WTelegramClient/

License: MIT License

C# 100.00%
telegram telegram-api dotnet csharp userbot client mtproto client-api clientapi tlsharp

wtelegramclient's Introduction

API Layer NuGet version NuGet prerelease Donate

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

This library allows you to connect to Telegram and control a user programmatically (or a bot, but WTelegramBot 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 requires understanding advanced C# techniques such as asynchronous programming or subclass pattern matching...
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 myself = await client.LoginUserIfNeeded();
    Console.WriteLine($"We are logged-in as {myself} (id {myself.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, Email, 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.
In some case, Telegram may request that you associate an email with your account for receiving login verification codes, you may skip this step by leaving email empty, otherwise the email address will first receive an email_verification_code.
All these login scenarios are handled automatically within the call to LoginUserIfNeeded.

After login, you now have access to the full range of Telegram Client APIs. All 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(...)

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, write permissions) 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 (see FAQ #3 for WinForms)
Returning "" for verification_code requests the resending of the code through another system (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.

Alternative simplified configuration & login

Since version 3.0.0, a new approach to login/configuration has been added. Some people might find it easier to deal with:

WTelegram.Client client = new WTelegram.Client(YOUR_API_ID, "YOUR_API_HASH"); // this constructor doesn't need a Config method
await DoLogin("+12025550156"); // initial call with user's phone_number
...
//client.Dispose(); // the client must be disposed when you're done running your userbot.

async Task DoLogin(string loginInfo) // (add this method to your code)
{
   while (client.User == null)
      switch (await client.Login(loginInfo)) // returns which config is needed to continue login
      {
         case "verification_code": Console.Write("Code: "); loginInfo = Console.ReadLine(); break;
         case "name": loginInfo = "John Doe"; break;    // if sign-up is required (first/last_name)
         case "password": loginInfo = "secret!"; break; // if user has enabled 2FA
         default: loginInfo = null; break;
      }
   Console.WriteLine($"We are logged-in as {client.User} (id {client.User.id})");
}

With this method, you can choose in some cases to interrupt the login loop via a return instead of break, and resume it later by calling DoLogin(requestedCode) again once you've obtained the requested code/password/etc... See WinForms example and ASP.NET example

Example of API call

The Telegram API makes extensive usage of base and derived classes, so be ready to use the various C# syntaxes 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)
    if (chat.IsActive)
        Console.WriteLine($"{id,10}: {chat}");
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 and more detailed programs in the Examples subdirectory.
➡️ Check the FAQ if example codes don't compile correctly on your machine, or other troubleshooting.

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 basic 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 will 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 (therefore, no private user discussions)
  • Peer: Either a Chat, a Channel or a User
  • Dialog: Status of chat with a Peer (draft, last message, unread count, pinned...). It represents each line from your Telegram chat list.
  • 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.
  • DC (DataCenter): There are a few datacenters depending on where in the world the user (or an uploaded media file) is from.
  • Session or Authorization: Pairing between a device and a phone number. You can have several active sessions for the same phone number.
  • Participant: A member/subscriber of a chat group or channel

Other things to know

The 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.
You can also use the UpdateManager class to simplify the handling of such updates.
See Examples/Program_ListenUpdates.cs and Examples/Program_ReactorError.cs

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

To prevent getting banned during dev, you can connect to test servers, by adding this line in your Config callback:
case "server_address": return "2>149.154.167.40:443"; // test DC

The 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

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, as well as generic handling of chats/channels.

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 scenario including:

  • Sequential or parallel automated steps based on API requests/responses
  • Real-time monitoring of incoming Updates/Messages
  • Download/upload of files/media
  • Exchange end-to-end encrypted messages/files in Secret Chats
  • Building a full-featured interactive client

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

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.

If you read all this ReadMe, the Frequently Asked Questions, the Examples codes and still have questions, feedback is welcome in our Telegram group @WTelegramClient

If you like this library, you can buy me a coffee ❤ This will help the project keep going.

© 2024 Olivier Marcoux

wtelegramclient's People

Contributors

habeebmatrix avatar mralisalehi avatar richi-developer avatar wiz0u 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 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

wtelegramclient's Issues

API call hangs

The following code hangs and never returns a response; without the call to Bots_SetBotCommands communication is fine.

var commands = new [] {new BotCommand {command = "translate", description = "Translates text"}};
await Client.Bots_SetBotCommands(new BotCommandScopeDefault(), "en", commands);

It would seem Telegram simply never offers a response as it hangs in:

WTelegram.Client.SendAsync(IObject msg, bool isContent, Rpc rpc = null)

at line

await _sendSemaphore.WaitAsync();

I apologize for the barren Issue, but I'm not sure what additional information would be useful.

SMS sending code doesn't work

Hello.
I am trying to receive a code via SMS but seems it doesn't work even the phone number isn't existed on telegram (new sign up) even though I still got response including with phone code hash.
I still received the code via telegram app for existed account.
Can you please help to explain why this happens and how to fix it?

Long time waiting without response

I've tested many APIs, (Channels_GetAllParticipants, Messages_GetAllChats, ...) but they don't respond and waiting forever!

var chats = await client.Messages_GetAllChats(null);
WTelegramClient source running under .NET 6.0.0-rc.2.21480.5

How send message to bot?

Hi.
How i can send message to bot via your client? Bot now one of my dialog but when i get channels or messages lists - bot not included in list. Only groupes or users.
Please say how i can resolve my problem.
thx.

Cannot write the start of an object or array without a property name. Current token type is 'None'.

System.Text.Json.JsonException: "The object or value could not be serialized. Path: $."

First Autoriazition - Check - succes

Two Client check autorization - get error

using var client = GetClient();
var user = await client.LoginUserIfNeeded();
Console.WriteLine($"We are logged-in as {user.username ?? user.first_name + " " + user.last_name} (id {user.id})");

var chats = await client.Messages_GetAllChats(); // chats = groups/channels (does not include users dialogs)
Console.WriteLine("This user has joined the following:");

My code doesn`t work, plz explain.

I will attach an example code below, in the indicated place the code does not work and the application simply closes.

Screenshot_1

Console message before closing:
WTelegramClient 2.3.1 running under .NET 5.0.12 Connecting to 149.154.167.50:443...

I'm using consoleApp under .Net 5.0 and a completely clean project with no extra dependencies.
I count on your help!

How to Save and Load session file with other name?

WTelegramClient saves (typically in the encrypted file bin\WTelegram.session) its state and the authentication keys that were negociated with Telegram so that you needn't sign-in again every time. But I want save with other path name and load it

Cannot use back the Signed-in Session

Hello. My project has already signed in for the user, as i know it should be saved at file WTelegram.session and can re-use again the file for the next running.
But when I run again the project, it shows an error "You must provide a config value for bot_token" at "await _client.LoginBotIfNeeded();" row
Can you please help to correct me if i am wrong at any step:
thank you!
This is my code
`
public virtual async void NewClient()
{
try
{
_ApiId = Convert.ToInt32(ConfigurationManager.AppSettings["ApiId"]);
_ApiHash = ConfigurationManager.AppSettings["ApiHash"];
//_PhoneNo = ConfigurationManager.AppSettings["PhoneNumber"];
_client = new WTelegram.Client(Config);
await _client.LoginBotIfNeeded();
await _client.ConnectAsync();
}
catch (IOException e)
{
System.Windows.Forms.MessageBox.Show("Session was using by another process. Restarting..");
_client.Dispose();
_client = new WTelegram.Client(Config);
}
}

`

Auth_SendCode only working for existed account

Hello,
I am using Auth_SendCode to use for Auth_SignUp, and this does not send any SMS to the new phone number.
But it works for existed account which is used for Auth_SignIn (Sending by Telegram App).
Please help me out of this stuck, thanks a lot

TL.Schema.cs

Hello!
How did you generate "TL.Schema.cs"?
Is there any generator?

How can i send button in message not bot

How can i send button in message not bot

here my code but its not working

 var keyboardButton1 = new KeyboardButton { text = "Yes" };
            var keyboardButton2 = new KeyboardButton { text = "No" };
            var keyboardButtonRow = new KeyboardButtonRow();
            keyboardButtonRow.buttons = new KeyboardButton[] { keyboardButton1, keyboardButton2 };
            var rkm = new ReplyKeyboardMarkup();
            rkm.rows = new KeyboardButtonRow[] { keyboardButtonRow };
            await client.Messages_SendMessage(contacts.users[m.Peer.ID], msg, m.id, false, false, false, false, false, null, rkm);

cannot convert from 'method group' to 'CodeSettings

I try to get the example running in a .net5 project but I get the following error when including the Config in the client.LoginUserIfNeeded.

user = await client.LoginUserIfNeeded(Config);

Error:
Argument 1: cannot convert from 'method group' to 'CodeSettings'

how to connect to Telegram using external session files

Hello .
I have a jsion file and a session file that I bought on the Internet to control my chat - the jsion file already has (app_hash id_hash and other information) the session is already authorized (checked for Teletnon (python)) but when I try to enter Telegram it asks me to specify also api_hash I specified app_hash as in json, but the error writes incorrect data, how can I log in?

System.IO.IOException: 'Unable to remove the file to be replaced. '

This error happens so frequently, and apparently can happen after any request....

This exception was originally thrown at this call stack:
System.IO.__Error.WinIOError(int, string)
System.IO.__Error.WinIOError()
System.IO.File.InternalReplace(string, string, string, bool)
System.IO.File.Replace(string, string, string)
WTelegram.Session.Save()
WTelegram.Client.NewMsgId(bool)
WTelegram.Client.SendAsync(TL.IObject, bool)
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
WTelegram.Client.CallAsync(TL.IMethod)

		internal void Save()
		{
			var utf8Json = JsonSerializer.SerializeToUtf8Bytes(this, Helpers.JsonOptions);
			var finalBlock = new byte[16];
			var output = new byte[(16 + 32 + utf8Json.Length + 16) & ~15];
			Encryption.RNG.GetBytes(output, 0, 16);
			using var aes = Aes.Create();
			using var encryptor = aes.CreateEncryptor(_apiHash, output[0..16]);
			encryptor.TransformBlock(_sha256.ComputeHash(utf8Json), 0, 32, output, 16);
			encryptor.TransformBlock(utf8Json, 0, utf8Json.Length & ~15, output, 48);
			utf8Json.AsSpan(utf8Json.Length & ~15).CopyTo(finalBlock);
			encryptor.TransformFinalBlock(finalBlock, 0, utf8Json.Length & 15).CopyTo(output.AsMemory(48 + utf8Json.Length & ~15));
			if (!File.Exists(_pathname))
				File.WriteAllBytes(_pathname, output);
			else lock (this)
				{
					string tempPathname = _pathname + ".tmp";
					File.WriteAllBytes(tempPathname, output);
					File.Replace(tempPathname, _pathname, null);
				}
		}

Cannot find type for ctor #5b29a91f

hi, everyone!
First of all, I would like to say that you are doing a great job.
And I need help. The Messages_GetHistory method worked fine this morning, but in the afternoon it only returns the error Cannot find type for ctor # 5b29a91f. That the telegram would deploy a new version of the API?

An exception occured in the reactor: System.ApplicationException: Cannot find type for ctor #5b29a91f
at TL.Serialization.ReadTLObject(BinaryReader reader, UInt32 ctorNb)
at TL.Serialization.ReadTLValue(BinaryReader reader, Type type)
at TL.Serialization.ReadTLObject(BinaryReader reader, UInt32 ctorNb)
at TL.Serialization.ReadTLValue(BinaryReader reader, Type type)
at TL.Serialization.ReadTLVector(BinaryReader reader, Type type)
at TL.Serialization.ReadTLValue(BinaryReader reader, Type type)
at TL.Serialization.ReadTLObject(BinaryReader reader, UInt32 ctorNb)
at TL.Serialization.UnzipPacket(GzipPacked obj, Client client)
at TL.Serialization.ReadTLObject(BinaryReader reader, UInt32 ctorNb)
at TL.Serialization.ReadTLValue(BinaryReader reader, Type type)
at WTelegram.Client.ReadRpcResult(BinaryReader reader)
at WTelegram.Client.ReadFrame(Byte[] data, Int32 dataLen)
at WTelegram.Client.Reactor(NetworkStream stream, CancellationTokenSource cts)

Thank you in advance for your reply

Messages_ReadHistory DONT WORKING

i dont see any example of mark messages as reas so i did like the tl.layer Messages_ReadHistory(peer,-1);
yes i tryed many ways nothing working
so how can i mark message (private chat) as read? help here please

How to Upload Streamable Video?

Hi, I want to ask. I upload video with UploadFileAsync and Post with SendMediaAsync but when I check chat there is show file without thumbnail and can't streaming (like common doc file). Can you show me how to use it for watch stream?

Here is my code:

WTelegram.Client.ProgressCallback progress = new WTelegram.Client.ProgressCallback((p,r) => {
     Console.Write(p*100/r+"%\r");
 });
SetLog("Uploading File...");
var inputFile = await client.UploadFileAsync("video\\myfile.mp4", progress);
 var target = chats.chats[channelId];
SetLog($"Sending a message in chat {target.ID}: {target.Title}");
await client.SendMediaAsync(target, "Tes", inputFile);

Can't connect (System.ArgumentOutOfRangeException)

Hey, I can't get ConnectAsync nor the LoginUserIfNeeded to work as it always triggers this error:
System.ArgumentOutOfRangeException : 'Length cannot be less than zero. Parameter name : length'

Config seems to be good (Filled the X with the right informations of course) and I cannot figure out why it's happening.

    public async Task Login()
    {

        Client _client = new Client(Config);
        await _client.ConnectAsync();
        User _user = await _client.LoginUserIfNeeded();
    }
    static string Config(string what)
    {
        switch (what)
        {
            case "api_id": return "X";
            case "api_hash": return "X";
            case "phone_number": return "+X";
            case "verification_code": return Interaction.InputBox("Enter verification code");
            case "first_name": return "X";      // if sign-up is required
            case "last_name": return "X";        // if sign-up is required
            case "password": return "secret!";     // if user has enabled 2FA
            case "server_address": return "149.154.167.50";
            case "server_port": return "443";
            default: return null;                  // let WTelegramClient decide the default config
        }
    }

Save session to database

I want to log in with multiple accounts in the program, but I don't want to save multiple session files, so what should I do? Can I save the session to the database?

Forward

Hello!

How do I forward a received message?

Thanks

Exception on Messages_GetHistory

I tried to get messages from chat using your example but I get an exception on first iteration:

An exception occured in the reactor: System.ArgumentException: An item with the same key has already been added. Key: 1470197156
   at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at TL.Serialization.ReadTLDictionary[T](BinaryReader reader, Func`2 getID)
   at TL.Serialization.ReadTLValue(BinaryReader reader, Type type)
   at TL.Serialization.ReadTLObject(BinaryReader reader, UInt32 ctorNb)
   at TL.Serialization.UnzipPacket(GzipPacked obj, Client client)
   at TL.Serialization.ReadTLObject(BinaryReader reader, UInt32 ctorNb)
   at WTelegram.Client.ReadRpcResult(BinaryReader reader)
   at WTelegram.Client.ReadFrame(Byte[] data, Int32 dataLen)
   at WTelegram.Client.Reactor(Stream stream, CancellationTokenSource cts)

Version: 1.9.2

Winforms sample cannot receive channel updates

I cannot get private channel updates with winforms and Client_Update event. chat messages are okay but no channel messages. Can you help me please, or better yet, can you place an example on documentation at least ?

best...

Document.LargestThumbSize generated Argument Null Exception

When calling Document.LargestThumbSize on a Document object without an associated image, GetThumbSize causes a null exception error.

This exception was originally thrown at this call stack:
    [External Code]
    TL.Document.LargestThumbSize.get() in TL.Helpers.cs
    Application.Telegram.DownloadDocument(int, long?, long, TL.Document, string) in Telegram.cs
public PhotoSizeBase LargestThumbSize => thumbs.Aggregate((agg, next) => (long)next.Width * next.Height > (long)agg.Width * agg.Height ? next : agg);

In a normal situation I would work around this by checking first, but in this particular example I am attempting to serialize the whole object so I am unable to be picky about properties.

var json = JsonSerializer.Serialize(document.LargestThumbSize)

Readme Guide Not Working

When I try to build readme guide, there is error :


using var client = new WTelegram.Client(Config); // or Client(Environment.GetEnvironmentVariable)
            await client.LoginUserIfNeeded();
            //var result = await client.Contacts_ResolveUsername("USERNAME");
            //await client.SendMessageAsync(result.User, "Hello");


            //or by phone number:
            var result = await client.Contacts_ImportContacts(new[] { new InputPhoneContact { phone = "085716141499" } });
            client.SendMessageAsync(result.users[result.imported[0].user_id], "Hello dari M Toha send Telegram Notif");

[QUESTION] How to join a channel with its username?

Hello

I'm trying to join a channel with its username.
I python I know I can make something like this:
result = client(functions.channels.JoinChannelRequest(channel = serverToJoin))

serverToJoin is a string like @mychannel.

But here, I can't use username in InputChannel

var targetChannel = new InputChannel { }; account.Client.Channels_JoinChannel(targetChannel);

So I need to find a way to retreive channel ID and channel Hash with its username.

Any idea?
Thank you

How to get Api_id and Api_Hash for new user?

Hello.
I am trying to get access api_id and Api Hash for new user.This function I saw from some tools which is on youtube for previewing.

And I am using a tool which created by someone also able to get api_id and api_hash without creating telegram app on my.telegram.org

  • I want to get Api_id and api_hash through telegram Clients Api for new user which just have done for register. Not by manually access to https://my.telegram.org/ . it will be great if able to do with WTelegramClient

I have been stuck on this, someone here please tell me if this is possible and how?
Thanks a lot

How to get sessionkey from tdlib?

Hello, thanks for sharing. It's very helpful to me. I'm using tdlib to build my own telegraph client, but I'm having trouble logging in with multiple accounts. I can't get it to save the session key. Can you tell me how you got it from tdlib?

Problem with LoginUserIfNeeded after Auth_SendCode

Hi, friend.
When I singin in using:
client = new WTelegram.Client(Config)
client.ConnectAsync();
var hash = client.Auth_SendCode(phone, api_id, api_hash, null).Result
client.Auth_SignIn(phone, hash.phone_code_hash, code);

Everything is fine. The session is saved, messages are sent.

BUT if I use client.LoginUserIfNeeded(); it re-requests the SMS code revoking the old authorization.
Moreover, further, after re-confirming the code, everything works without SMS when using both code options.
That is, client.LoginUserIfNeeded() does not see that we are authorized through client.Auth_SignIn.
I assume that everything is saving the session file.

P.S. It is also not clear why client.Auth_SendCode(phone, api_id, api_hash, null) needs to be written in the phone number, id and hash, if they are already registered in string Confi (otherwise WTelegram.Client() requests them in the console and the code is not executed further)
P.P.S. How can I explicitly specify that the telegram sends only verification code via App?

Thanks

Mono/Android - Integrity check failed in session loading

Hey there, I was trying to use this library in my small Android app but I got some issues.

Issue 1 - enum serialization on Mono.
I was able to solve myself the first issue I've ran into. I wanted to publish a branch and create a PR but I got http 403. So, here it is:
image

Not sure why, but GetTypeCode return different values when passing enum into it on Desktop/Windows and Mono/Android.
So, InitConnection.Flags enum on windows is TypeCode.Int32, but on Mono it's TypeCode.Object. This breaks initial calls and there is no way to sign in.

After I applied the fix above (which works on both mono and desktop) I'm able to sign in, confirm verification code and call other APIs. (I tried to send messages and it was working for me).

Issue 2 - session persistance
When I create a new instance of Client, and do LoginIfNeeded I'm always getting 'Integrity check failed in session loading' error. I set a app private directory as working directory and specified valid file through session_pathname config entry. It seems to write some data into it, but when it will read it it will find it incomplete. I tried to Dispose the client after successfull login thinking it will force to store the session on file system but it didn't helped much.

Is there a method I could call to store session data into the file?
I'm using VS2019, Mono 6.12, target android version = 11, Xamarin app (not xamarin forms).
Let me know if you need any additional info.

How can I contact you

Hello,

how can we contact you by email ?
my email is : [email protected]
if you answer me, use as a name (title of email): WTelegramClient

I have a few questions about the 'integration' of your code into our application and
I don't want to break any rules ...

Session file occupied

I created a WinForm application. Now I need to operate on the saved session file, but the system prompts that the session file is occupied and cannot be operated. How can I close it and where can I close the opened session file.

Latency

Hello,
How long does it take to capture a message when a message is sent to a large group?
I was using some modules in Python but they were very slow (like 10-40 seconds) and
Since I have no previous C# experience, I cannot test it in a short time.
I know that issues is not best place to ask this but I'm also new to github

Make Helpers class a property of Client

This would open up possibilities for multiclient applications to have independent logging for each client. In my honest opinion this also makes more sense architecture wise, as all properties in Helpers class are bound to client and there is no need for putting them into separate class

Wrong account "John Doe"

Good afternoon. When using a project from the "src" folder, when entering a phone number, the activation code does not come to the telegram client. However, if you enter it incorrectly, it comes in the form of SMS to your phone. I drive it, but after that it connects to someone else's John Doe account. How to connect your account?

Get more information about RpcException PEER_FLOOD

Hello,

I'm trying to create a little bot with your lib and I'm currently have a little RpcException "PEER_FLOOD". But nothing more.
I now in Python, a message from Telegram's API is returned, like "You need to wait xx seconds...."

Thank you :)

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.