GithubHelp home page GithubHelp logo

telegram.net's People

Contributors

ahmadalli avatar ahmadi173 avatar eaba avatar lonami avatar marshallmick007 avatar ra0o0f avatar sochix avatar starli0n avatar steavy29 avatar tehl avatar zerodwide avatar

Stargazers

 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

telegram.net's Issues

DC Invalid when trying to download image

When I call GetFile() I am getting the following error.. It is an image that I am trying to download...

Throwing exception for request AuthExportAuthorizationRequest because of error BadRequest - DC_ID_INVALID

Подскажите пожалуйста, что такое from_id

Помогите пожалуйста разобраться с структуре MessageConstructor.

В поле to_id - идентификатор пира отправителя сообщения. С этим всё понятно. Но вот в поле from_id - неизвестный номер, который я не знаю, как соотнести с получателем.

В результате, когда я получаю updates_Difference с отправленными мной же сообщениями, я не знаю, кому они были отправлены.

Например:

Я получаю следующий Message
(message id:259 from_id:1590 to_id:188888888 out:False unread:False date:1474534709 message:'тестовое сообщение' media:(messageMediaEmpty))
188888888 - это мой ID, так как это сообщение отправлял я. Но кому это сообщение было мной отправлено, я понять из этих данных не могу. Как мне соотнести с id'ом или from_id'ом идентификатор того пира, которому это сообщение предназначалось?

Invalid constructor code 388FA391 error when trying to use GetDialog

I want to get a chat by its name and send message to the chat.
My code is as below:

        int id = 0;
        var client = await InitializeAndAuthenticateClient();
        var chatlist = await client.GetDialogs(0, 10, 0) as MessagesDialogsConstructor;
        foreach (Chat A in chatlist.chats)
        {

            var chatreq = A as ChatConstructor;

            if (chatreq.title == "chatname")
            {
                id= chatreq.id;
                break;
            }



         }

        if(id!=0)
        {

            await client.SendChatMessage(id, "hello");

        }

but I get this error: "Invalid constructor code 388FA391 " .
How can I fix this? Or any other suggestion to get the chat id?
Thanks.

Error during SendMediaMessage

Hello!
When I try to send media message I receive this error. I send it with such way.

Program.TgApi.SendMediaMessage(new InputPeerForeignConstructor(user.id,user.accessHash), 
                        new InputMediaUploadedThumbVideoConstructor(fl, thumb, VideoInfo.Duration / 1000,
                            VideoInfo.BestVideoStream.Width, VideoInfo.BestVideoStream.Height))
System.AggregateException: Произошла одна или несколько ошибок. ---> System.Exception: Invalid constructor code 123B1D4
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader, UInt32 dataCode) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 338
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 317
   в Telegram.Net.Core.MTProto.VideoConstructor.Read(BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 4669
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader, UInt32 dataCode) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 348
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 317
   в Telegram.Net.Core.MTProto.MessageMediaVideoConstructor.Read(BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 3920
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader, UInt32 dataCode) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 348
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 317
   в Telegram.Net.Core.MTProto.MessageConstructor.Read(BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 3708
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader, UInt32 dataCode) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 348
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 317
   в Telegram.Net.Core.MTProto.MessagesStatedMessageConstructor.Read(BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 6610
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader, UInt32 dataCode) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 348
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 317
   в Telegram.Net.Core.Requests.SendMediaRequest.OnResponse(BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\Requests\SendMediaRequest.cs:строка 36
   в Telegram.Net.Core.Network.MtProtoSender.HandleRpcResult(BinaryReader messageReader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\Network\MtProtoSender.cs:строка 379
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
   в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   в System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   в Telegram.Net.Core.Network.MtProtoSender.<Send>d__25.MoveNext() в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\Network\MtProtoSender.cs:строка 187
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
   в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   в System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   в Telegram.Net.Core.TelegramClient.<SendRpcRequest>d__25.MoveNext() в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\TelegramClient.cs:строка 97
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
   в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   в System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   в Telegram.Net.Core.TelegramClient.<SendMediaMessage>d__57.MoveNext() в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\TelegramClient.cs:строка 562
   --- Конец трассировки внутреннего стека исключений ---
   в System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   в System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   в System.Threading.Tasks.Task.Wait(CancellationToken cancellationToken)
   в ConsoleUploader.UploadTask.LaunchTask() в D:\Yandex\Developing\Visual Studio\ConsoleUploader\ConsoleUploader\ConsoleUploader\UploadTask.cs:строка 747
   в ConsoleUploader.Program.Main(String[] args) в D:\Yandex\Developing\Visual Studio\ConsoleUploader\ConsoleUploader\ConsoleUploader\Program.cs:строка 217
---> (Внутреннее исключение #0) System.Exception: Invalid constructor code 123B1D4
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader, UInt32 dataCode) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 338
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 317
   в Telegram.Net.Core.MTProto.VideoConstructor.Read(BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 4669
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader, UInt32 dataCode) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 348
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 317
   в Telegram.Net.Core.MTProto.MessageMediaVideoConstructor.Read(BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 3920
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader, UInt32 dataCode) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 348
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 317
   в Telegram.Net.Core.MTProto.MessageConstructor.Read(BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 3708
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader, UInt32 dataCode) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 348
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 317
   в Telegram.Net.Core.MTProto.MessagesStatedMessageConstructor.Read(BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 6610
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader, UInt32 dataCode) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 348
   в Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\MTProto\TLObject.cs:строка 317
   в Telegram.Net.Core.Requests.SendMediaRequest.OnResponse(BinaryReader reader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\Requests\SendMediaRequest.cs:строка 36
   в Telegram.Net.Core.Network.MtProtoSender.HandleRpcResult(BinaryReader messageReader) в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\Network\MtProtoSender.cs:строка 379
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
   в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   в System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   в Telegram.Net.Core.Network.MtProtoSender.<Send>d__25.MoveNext() в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\Network\MtProtoSender.cs:строка 187
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
   в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   в System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   в Telegram.Net.Core.TelegramClient.<SendRpcRequest>d__25.MoveNext() в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\TelegramClient.cs:строка 97
--- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
   в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   в System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   в Telegram.Net.Core.TelegramClient.<SendMediaMessage>d__57.MoveNext() в D:\Yandex\Developing\Visual Studio\Telegram.net\Telegram.Net.Core\TelegramClient.cs:строка 562<---

How to send messages to the group?

[TestMethod]
        public async Task CreateChatAndSendMessage()
        {
            var client = await InitializeClient();

            var chatName = Guid.NewGuid().ToString();
            var statedMessage = await client.CreateChat(chatName, new List<string> { NumberToSendMessage });

            var createdChat = GetChatFromStatedMessage(statedMessage);

            Assert.AreEqual(chatName, createdChat.title);
            Assert.AreEqual(2, createdChat.participants_count);


            await client.SendMessage(createdChat.id, "Test message to group");
        }

Test method CreateChatAndSendMessage threw exception:
System.InvalidOperationException: PEER_ID_INVALID

AUTH_KEY_UNREGISTERED.

Now that this problem: AUTH_KEY_UNREGISTERED.
I am using the method : ImportContactByPhoneNumberAndSendMessage.

if I try to use the method 'MakeAuth' is again generated an exception:

An exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll but was not handled in user code

Error in Connect()

I'm assigning all parameters correctly and is occurring error connecting .

Stacktrace: TLSharp.Core.TelegramClient.d__13.MoveNext()

In the Teste only run AuthenticationWorks, DataCenterMigrationErrorHandling and TestConnection the others are in error.

Do u can help me?

Exception: MessageSeqNoTooLow

Passed tests:
AuthenticationWorks
DataCenterMigrationErrorHandling
TestConnection

All other tests - failed.


Test Name: AuthUser
Test FullName: Telegram.Net.Tests.Tests.AuthUser
Test Source: F:\Telegram\Telegram.Net-master\Telegram.Net.Tests\Tests.cs : line 72
Test Outcome: Failed
Test Duration: 0:00:00,2725698

Result StackTrace:
в Telegram.Net.Core.Requests.MTProtoRequest.ThrowIfHasError() в F:\Telegram\Telegram.Net-master\Telegram.Net.Core\Requests\MTProtoRequest.cs:string 59
в Telegram.Net.Core.TelegramClient.d__46.MoveNext() в F:\Telegram\Telegram.Net-master\Telegram.Net.Core\TelegramClient.cs:строка 414
...
в System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Result Message:
Test method Telegram.Net.Tests.Tests.AuthUser threw exception:
Telegram.Net.Core.TelegramReqestException: MessageSeqNoTooLow -

Joined the group via invite link

Please tell me how to implement joined the group via invite link.

Without this, it is possible to join only to the rooms, which are created by you. :(

Read unread message and set them as read or delete them

I try your library and it is awesome. It's more stable than other telegram libraries. The features like auto reconnect is very helpful.
I have no idea about sending rpc request to read unread messages and set them as read or delete them. Here's the code I'm using
If I subscribe to the UpdateMessage event then the Flood - FLOOD_WAIT_19 occurs where I have to wait 19 seconds to read next incoming text message. No idea how to read unread message without FLOOD_WAIT :(

to set message as read - no luck

var requestConfirmed = new ReceivedMessagesRequest(messageId)
{
    ConfirmReceived = true
};
await client.SendRpcRequest(requestConfirmed);

to delete message - no luck

var requestDelete = new DeleteMessagesRequest(new List<int> { messageId });
await client.SendRpcRequest(requestDelete);

One more. After creating new instance of TelegramClient and calling client.Start(); the UpdateMessage event is not fired untill I send message first then back to normal (UpdateMessage fired again)

GetDialogs new error:Invalid constructor code 6D2F6F65

Hi ,
I got the same error(issues #26) after using the fixed code :(with different constructor code error)
"Invalid constructor code 6D2F6F65"

and the top stack trace:
at Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader, UInt32 dataCode) in D:\golshan\tlsharp\telegramnew\Telegram.Net-master\Telegram.Net-master\Telegram.Net.Core\MTProto\TLObject.cs:line 341
at Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader) in D:\golshan\tlsharp\telegramnew\Telegram.Net-master\Telegram.Net-master\Telegram.Net.Core\MTProto\TLObject.cs:line 320
at Telegram.Net.Core.MTProto.VideoConstructor.Read(BinaryReader reader) in D:\golshan\tlsharp\telegramnew\Telegram.Net-master\Telegram.Net-master\Telegram.Net.Core\MTProto\TLObject.cs:line 4672
at Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader, UInt32 dataCode) in D:\golshan\tlsharp\telegramnew\Telegram.Net-master\Telegram.Net-master\Telegram.Net.Core\MTProto\TLObject.cs:line 351
at Telegram.Net.Core.MTProto.TLObject.Read[T](BinaryReader reader) in D:\golshan\tlsharp\telegramnew\Telegram.Net-master\Telegram.Net-master\Telegram.Net.Core\MTProto\TLObject.cs:line 320
at Telegram.Net.Core.MTProto.MessageMediaVideoConstructor.Read(BinaryReader reader) in D:\golshan\tlsharp\telegramnew\Telegram.Net-master\Telegram.Net-master\Telegram.Net.Core\MTProto\TLObject.cs:line 3923
........................
Best.

Try to load dialogs , Exception Invalid constructor code C7AC6496

class ContactData
    {
        public readonly int UserID;
        public readonly long AccessHash;
        public readonly string UserName;
        public ContactData(int UserID, long AccessHash, string UserName)
        {
            this.UserID = UserID;
            this.AccessHash = AccessHash;
            this.UserName = UserName;
        }
        public override string ToString()
        {
            return this.UserName;
        }
    }
private async Task load_Dialogs()
        {
            var AllDialog = await Authenticated.GetDialogs(0, 30, 0) as MessagesDialogsConstructor;
            var DialogsUsersList = AllDialog.users;
            lst_Dialogs.Items.Clear();

            foreach (User X in DialogsUsersList)
            {
                try
                {
                    var userReq = X as UserRequestConstructor;
                    if (userReq != null)
                    {
                        lst_Dialogs.Items.Add(
                            new Helper.ContactData(userReq.id, userReq.accessHash,
                            userReq.firstName + " " + userReq.lastName));
                    }
                    else
                    {
                        var userContact = X as UserContactConstructor;
                        if (userContact != null)
                        {
                            lst_Dialogs.Items.Add(
                                new Helper.ContactData(userContact.id, userContact.accessHash,
                                userContact.firstName + " " + userContact.lastName));
                        }
                        else
                        {
                            var userForeign = X as UserForeignConstructor;
                            if (userForeign != null) lst_Dialogs.Items.Add(
                                new Helper.ContactData(userForeign.id, userForeign.accessHash,
                                userForeign.firstName + " " + userForeign.lastName));

                            else
                            {
                                var UserSelf = X as UserSelfConstructor;
                                if (UserSelf != null) lst_Dialogs.Items.Add(
                                new Helper.ContactData(UserSelf.id, 0,
                                UserSelf.firstName + " " + UserSelf.lastName));
                            }
                        }
                    }
                }
                catch (Exception ex) { MessageBox.Show(ex.ToString()); }
            }
        }

Code
Session dat = http://rgho.st/8MfqSvz9s (Can't attach)
//Напиши в вк если остались вопросы(Rus text to author)

How to get offline message

private void UpdateMessage(object sender, Updates update)
        {
            switch (update.Constructor)
            {
                case Constructor.updatesTooLong:
                {
                    // need to download updates manually
                    break;
                }
                case Constructor.updateShortMessage:
                {
                    var upd = update as UpdateShortMessageConstructor;
                    // upd.message
                    break;
                }
                case Constructor.updates:
                {
                    var upd = update as UpdatesConstructor;
                    foreach (var updatePiece in upd.updates)
                    {
                        // handle update
                    }
                    break;
                }
            }
            // ...
        }

Wich updates.constructor to handle/get offline message?

got Error: Flood - FLOOD_WAIT_62720

That error raised causes by i have running 4 desktop application using same one loginNumber and online for more 2days.

How to resolve that error ?

client.SendCode(...) error

Help please,
I'm trying to use Telegram.NET, I've created developer account at telegram website and got my Api ID and Api Hash so far so good.

i'm able to perform client.Start() and it returns me "connected"

after that I got to client.SendCode() and it returns me an exception which says API_ID_INVALID.
i know how to copy and paste so i am pretty sure its not a number mistake..

it worked once on my friend computer when i used it without DeviceInfo so ill be glad if someone can send me an example of :
DeviceInfo(string deviceModel, string systemVersion, string appVersion, string langCode)

another option is the server, in my app configuration page on telegram i get 2 servers which are different than your default server:
TEST SERVER :
149.154.167.40:443
PROD SERVER:
149.154.167.50:443

tried them both but it still returns me API_ID_INVALID
any suggestions ?

How to get channel updates?

Hello,

I would like to get channel updates.
I have used the sample code you provided in issue #25, but I didn't get any update when a channel get a new post.

FileSessionStore session = new FileSessionStore();
client = new TelegramClient(session, apiId, apiHash, new DeviceInfo("Telegram Test", "Telegram Test", "1.0", "en"));
client.UpdateMessage += TelegramUpdateHandler;
bool started = (await client.Start());

and the update handler code:

private void TelegramUpdateHandler(object sender, Updates update)
        {                       
            switch (update.constructor)
            {                 
                case Constructor.UpdatesTooLong: {
                        var upd = update as UpdatesTooLongConstructor;                        
                        break; }
                case Constructor.UpdateShortMessage:
                    {
                        var upd = update as UpdateShortMessageConstructor;
                        textBox1.Text = textBox1.Text + upd.message + "\r\n";                      
                        break;
                    }
                case Constructor.UpdateShortChatMessage: {
                        var upd = update as UpdateShortChatMessageConstructor;
                        textBox1.Text = textBox1.Text + upd.message + "\r\n";
                        break; }
                case Constructor.UpdateShort: {
                        var upd = update as UpdateShortConstructor;
                        break; }
                case Constructor.UpdatesCombined: {
                        var upd = update as UpdatesCombinedConstructor;                        
                        break; }
                case Constructor.Updates:
                    {
                        var upd = update as UpdatesConstructor;
                        foreach (var updatePiece in upd.updates)
                        {
                            // handle update                            
                        }
                        break;
                    }
            }
        }

client.Connect() error

Thanks for the fix, after I used it with my phone numbers 4 or 5 times it started to produce, this error.

**An exception of type 'System.Exception' occurred in mscorlib.dll but was not handled in user code

Additional information: MessageSeqNoTooLow -**

Error when trying to send a message

Hello,

I am trying to send a message to a telegram bot using the following code:

   public async Task SendMessageByUserName(TelegramClient client, string command)
    {
        var user = await client.ResolveUsername(userName) as UserForeignConstructor;
        var peer = new InputPeerForeignConstructor() { userId = user.id };
        var message = await client.SendMessage(peer, command);
    }

I am getting the following error: {"BadRequest - PEER_ID_INVALID"}
Would you please clarify what I am doing wrong?

I also see that there is the second parameter in the InputPeerForeignConstructor class (accessHash) but I am not sure how to get it and whether I need it.

Thanks

HTTP Transport. Need help.

Now Telegram.Net supports one transport (TCP). I would try to write another transport (HTTP).

Someone tell me where best to start, and which way to go? =)


I tried, but it was stuck. Maybe someone will tell you where I'm confused.
I am trying to implement the http-transport. When you try to get the answer - Error 404.

    public class HttpTransport : ITransport, IDisposable
    {
        private readonly HttpWebRequest httpWebRequest;
        private int sendCounter = 0;

        public HttpTransport(string address, int port)
        {
            httpWebRequest = (HttpWebRequest)WebRequest.Create("http://" + address);
        }

        public async Task Send(byte[] packet)
        {
            var data = packet;

            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded ; charset=UTF-8";
            httpWebRequest.ContentLength = data.Length;

            using (var stream = httpWebRequest.GetRequestStream())
            {
                await stream.WriteAsync(data, 0, data.Length);
            }

            sendCounter++;
        }

        public async Task<TcpMessage> Receieve()
        {
            var response = (HttpWebResponse)httpWebRequest.GetResponse();
            var stream = response.GetResponseStream();

            var packetLengthBytes = new byte[4];
            if (await stream.ReadAsync(packetLengthBytes, 0, 4) != 4)
                throw new InvalidOperationException("Couldn't read the packet length");
            int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);

            var seqBytes = new byte[4];
            if (await stream.ReadAsync(seqBytes, 0, 4) != 4)
                throw new InvalidOperationException("Couldn't read the sequence");
            int seq = BitConverter.ToInt32(seqBytes, 0);

            int readBytes = 0;
            var body = new byte[packetLength - 12];
            int neededToRead = packetLength - 12;

            do
            {
                var bodyByte = new byte[packetLength - 12];
                var availableBytes = await stream.ReadAsync(bodyByte, 0, neededToRead);
                neededToRead -= availableBytes;
                Buffer.BlockCopy(bodyByte, 0, body, readBytes, availableBytes);
                readBytes += availableBytes;
            }
            while (readBytes != packetLength - 12);

            var crcBytes = new byte[4];
            if (await stream.ReadAsync(crcBytes, 0, 4) != 4)
                throw new InvalidOperationException("Couldn't read the crc");
            int checksum = BitConverter.ToInt32(crcBytes, 0);

            byte[] rv = new byte[packetLengthBytes.Length + seqBytes.Length + body.Length];

            Buffer.BlockCopy(packetLengthBytes, 0, rv, 0, packetLengthBytes.Length);
            Buffer.BlockCopy(seqBytes, 0, rv, packetLengthBytes.Length, seqBytes.Length);
            Buffer.BlockCopy(body, 0, rv, packetLengthBytes.Length + seqBytes.Length, body.Length);
            var crc32 = new Ionic.Crc.CRC32();
            crc32.SlurpBlock(rv, 0, rv.Length);
            var validChecksum = crc32.Crc32Result;

            if (checksum != validChecksum)
            {
                throw new InvalidOperationException("invalid checksum! skip");
            }

            return new TcpMessage(seq, body);
        }
    }

OnMessage not working after restart the Application

This is my Code. On first run everything worked correctly. But when the program is closed and reopened again than UpdateHandler not get called anymore. client.IsUserAuthorized() gives true. When i delete Session.dat i can reenter my code and it will work. After 5 runs of the programm i have to wait 24 hours because of flood error.

    public class Program
    {
        static void Main(string[] args)
        {
                Program program = new Program();
                Task.Run(async () => await program.Run()).Wait();
        }

        public async Task Run()
        {
                TelegramClient client = new TelegramClient(new FileSessionStore(), 129340, "...", new DeviceInfo("Telegram Test", "Telegram Test", "Telegram Test", "en"));
                client.UpdateMessage += UpdateHandler;
                await client.Start();
                if (!client.IsUserAuthorized())
                {
                    var codeRequest = await client.SendCode("+...", VerificationCodeDeliveryType.NumericCodeViaTelegram);
                    string input = "";
                    await client.SignIn("+...", codeRequest.phoneCodeHash, input);
                }
        }

        private void UpdateHandler(object sender, Updates updates)
        {
            if (updates.constructor == Constructor.UpdateShortMessage)
            {
                var updateShortMessageConstructor = updates as UpdateShortMessageConstructor;
            }
        }
    }

How to set message as read?

I added class "ReadMessageRequest" like this:

using System.Collections.Generic;
using System.IO;
using Telegram.Net.Core.MTProto;

namespace Telegram.Net.Core.Requests
{
    public class ReadMessagesRequest : MtProtoRequest
    {
        public readonly List<int> messageIdsToRead;
        public List<int> readMessageIds { get; private set; }

        public ReadMessagesRequest(List<int> messageIdsToRead)
        {
            this.messageIdsToRead = messageIdsToRead;
        }

        protected override uint requestCode => 0xc6649e31;

        public override void OnSend(BinaryWriter writer)
        {
            writer.Write(requestCode);
            TLObject.WriteVector(writer, messageIdsToRead, writer.Write);
        }

        public override void OnResponse(BinaryReader reader)
        {
            readMessageIds = TLObject.ReadVector(reader, reader.ReadInt32);
        }

        public override bool isContentMessage => true;
    }
}

Then i tried code like this to set message as read:

private async void btnSetMessageRead_Click(object sender, EventArgs e)
{
     List<int> fmsgid = new List<int>();
     fmsgid.Add(14);
     var setreadmessage = new ReadMessagesRequest(fmsgid);
     await client.SendRpcRequest(setreadmessage);
}

but i got Unhandled exception : "BadRequest - INPUT_METHOD_INVALID"
please how to resolve it?
thx...

Get all new Received Message

what method in Tests.cs from test unit give me all received message to handle that?
is there a way to config app as a bot?

Download Avatar

How can i download photoBig or PhotoSmall in UserProfilePhoto

Enabling session after publication in IIS

After generating the " core.dll " as should be created " session.data " when you published the application in IIS ?

Because at this point I will have to inform the received code.

remove messages in groups

у клиента не хватает метода для удаления сообщений в группе/супергруппе (при наличии статуса администратора).
добавьте, пожалуйста)

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.