wiz0u / wtelegramclient Goto Github PK
View Code? Open in Web Editor NEWTelegram Client API (MTProto) library written 100% in C# and .NET
Home Page: https://wiz0u.github.io/WTelegramClient/
License: MIT License
Telegram Client API (MTProto) library written 100% in C# and .NET
Home Page: https://wiz0u.github.io/WTelegramClient/
License: MIT License
I will attach an example code below, in the indicated place the code does not work and the application simply closes.
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 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);
After using one account once, the second time is banned!
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
Heroku does not support: Console.ReadKey();
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");
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
}
}
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 :)
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.
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:");
Hi, wiz0u.
Can you provide simple example of using WebHook API with ASP.NET Core?
I don't know how to organize listening updates in the ASP.NET Core.
Thank you in advance!
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
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
Hello
May i ask a question that How to export session as a .dat file?
Thank you
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
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 ...
Hello!
How do I forward a received message?
Thanks
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
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)
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
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
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);
}
}
`
How i can send message to new user via your client?
var peer = new InputPeerUser(user.id,user.access_hash); await _client.SendMessageAsync(peer, "hello");
but it returns peer_id_invalid !!why ?
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:
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.
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);
}
}
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);
thanks for your effort
I get error CryptographicException: Padding is invalid and cannot be removed. when using an specific api hash
for other api hashes every thing is charm
any suggestion why?
thanks in advance
Can anyone please say how to use this in .NET Framework 4.7 dependency projects?
I see it only supports .NET Core and .NET Standard!
Thank You in advance!
Example of method to download file without reading updates
Guys account will be deleted after connect with library!!! are u scamers???
Hey,
The sample listen to updates doesn't work: https://github.com/wiz0u/WTelegramClient/blob/master/Examples/Program_ListenUpdates.cs
After signin via code, nothing really happens when I send a message to myself from another Telegram account. Nor do I get any updates about messages in my channels etc ..
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
Is it possible to use this library in Unity (2020.3.32) to build an Android application?
I think it would be better if you use C# naming conventions standards as described here:
https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions
https://github.com/ktaranov/naming-convention/blob/master/C%23%20Coding%20Standards%20and%20Naming%20Conventions.md
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
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?
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.
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'
Please, help
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?
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...
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?
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
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?
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.
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?
Hello!
How did you generate "TL.Schema.cs
"?
Is there any generator?
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 have been stuck on this, someone here please tell me if this is possible and how?
Thanks a lot
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.