Skip to content
This repository was archived by the owner on Dec 5, 2021. It is now read-only.

Commit 3e0e53b

Browse files
merqlovemarkwest51
authored andcommitted
Reapply Events PR #679
pr updates amended pr review changes resolved merge conflicts updates from last night before rebase update on message test now passing removed nlog references and usage resolve conflicts from HEAD Reapply Events PR #679 update on message test now passing removed nlog references and usage
1 parent bca8bc5 commit 3e0e53b

11 files changed

Lines changed: 673 additions & 54 deletions

File tree

README.md

Lines changed: 251 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,257 @@ To download file you should call **GetFile** method
137137

138138
Full code you can see at [DownloadFileFromContactTest](https://github.com/sochix/TLSharp/blob/master/TLSharp.Tests/TLSharpTests.cs#L167)
139139

140+
# Events Sample code
141+
```csharp
142+
using System;
143+
using System.Threading.Tasks;
144+
using TeleSharp.TL;
145+
using TLSharp.Core;
146+
using System.Linq;
147+
using TeleSharp.TL.Messages;
148+
using System.Collections.Generic;
149+
150+
namespace TLSharpPOC
151+
{
152+
class MainClass
153+
{
154+
const int APIId = 0;
155+
const string APIHash = "???";
156+
const string phone = "???";
157+
public static void Main(string[] args)
158+
{
159+
new MainClass().MainAsync(args).Wait();
160+
}
161+
162+
private async Task MainAsync(string[] args)
163+
{
164+
TelegramClient client = null;
165+
try
166+
{
167+
// -- if necessary, IP can be changed so the client can connect to the test network.
168+
Session session = null;
169+
// new Session(new FileSessionStore(), "session")
170+
//{
171+
// ServerAddress = "149.154.175.10",
172+
// Port = 443
173+
//};
174+
//Console.WriteLine($"{session.ServerAddress}:{session.Port} {phone}");
175+
client = new TelegramClient(APIId, APIHash, session);
176+
// subscribe an event to receive live messages
177+
client.Updates += Client_Updates;
178+
await client.ConnectAsync();
179+
Console.WriteLine($"Authorised: {client.IsUserAuthorized()}");
180+
TLUser user = null;
181+
// -- If the user has already authenticated, this step will prevent account from being blocked as it
182+
// -- reuses the data from last authorisation.
183+
if (client.IsUserAuthorized())
184+
user = client.Session.TLUser;
185+
else
186+
{
187+
var registered = await client.IsPhoneRegisteredAsync(phone);
188+
var hash = await client.SendCodeRequestAsync(phone);
189+
Console.Write("Code: ");
190+
var code = Console.ReadLine();
191+
if (!registered)
192+
{
193+
Console.WriteLine($"Sign up {phone}");
194+
user = await client.SignUpAsync(phone, hash, code, "First", "Last");
195+
}
196+
Console.WriteLine($"Sign in {phone}");
197+
user = await client.MakeAuthAsync(phone, hash, code);
198+
}
199+
200+
var contacts = await client.GetContactsAsync();
201+
Console.WriteLine("Contacts:");
202+
foreach (var contact in contacts.Users.OfType<TLUser>())
203+
{
204+
var contactUser = contact as TLUser;
205+
Console.WriteLine($"\t{contact.Id} {contact.Phone} {contact.FirstName} {contact.LastName}");
206+
}
207+
208+
209+
var dialogs = (TLDialogs) await client.GetUserDialogsAsync();
210+
Console.WriteLine("Channels: ");
211+
foreach (var channelObj in dialogs.Chats.OfType<TLChannel>())
212+
{
213+
var channel = channelObj as TLChannel;
214+
Console.WriteLine($"\tChat: {channel.Title}");
215+
}
216+
217+
Console.WriteLine("Groups:");
218+
TLChat chat = null;
219+
foreach (var chatObj in dialogs.Chats.OfType<TLChat>())
220+
{
221+
chat = chatObj as TLChat;
222+
Console.WriteLine($"Chat name: {chat.Title}");
223+
var request = new TLRequestGetFullChat() { ChatId = chat.Id };
224+
var fullChat = await client.SendRequestAsync<TeleSharp.TL.Messages.TLChatFull>(request);
225+
226+
var participants = (fullChat.FullChat as TeleSharp.TL.TLChatFull).Participants as TLChatParticipants;
227+
foreach (var p in participants.Participants)
228+
{
229+
if (p is TLChatParticipant)
230+
{
231+
var participant = p as TLChatParticipant;
232+
Console.WriteLine($"\t{participant.UserId}");
233+
}
234+
else if (p is TLChatParticipantAdmin)
235+
{
236+
var participant = p as TLChatParticipantAdmin;
237+
Console.WriteLine($"\t{participant.UserId}**");
238+
}
239+
else if (p is TLChatParticipantCreator)
240+
{
241+
var participant = p as TLChatParticipantCreator;
242+
Console.WriteLine($"\t{participant.UserId}**");
243+
}
244+
}
245+
246+
var peer = new TLInputPeerChat() { ChatId = chat.Id };
247+
var m = await client.GetHistoryAsync(peer, 0, 0, 0);
248+
Console.WriteLine(m);
249+
if (m is TLMessages)
250+
{
251+
var messages = m as TLMessages;
252+
253+
254+
foreach (var message in messages.Messages)
255+
{
256+
if (message is TLMessage)
257+
{
258+
var m1 = message as TLMessage;
259+
Console.WriteLine($"\t\t{m1.Id} {m1.Message}");
260+
}
261+
else if (message is TLMessageService)
262+
{
263+
var m1 = message as TLMessageService;
264+
Console.WriteLine($"\t\t{m1.Id} {m1.Action}");
265+
}
266+
}
267+
}
268+
else if (m is TLMessagesSlice)
269+
{
270+
bool done = false;
271+
int total = 0;
272+
while (!done)
273+
{
274+
var messages = m as TLMessagesSlice;
275+
276+
foreach (var m1 in messages.Messages)
277+
{
278+
if (m1 is TLMessage)
279+
{
280+
var message = m1 as TLMessage;
281+
Console.WriteLine($"\t\t{message.Id} {message.Message}");
282+
++total;
283+
}
284+
else if (m1 is TLMessageService)
285+
{
286+
var message = m1 as TLMessageService;
287+
Console.WriteLine($"\t\t{message.Id} {message.Action}");
288+
++total;
289+
done = message.Action is TLMessageActionChatCreate;
290+
}
291+
}
292+
m = await client.GetHistoryAsync(peer, total, 0, 0);
293+
}
294+
}
295+
}
296+
297+
// -- Wait in a loop to handle incoming updates. No need to poll.
298+
for (;;)
299+
{
300+
await client.WaitEventAsync();
301+
}
302+
}
303+
catch (Exception e)
304+
{
305+
Console.WriteLine(e);
306+
}
307+
}
308+
309+
private void Client_Updates(TelegramClient client, TLAbsUpdates updates)
310+
{
311+
Console.WriteLine($"Got update: {updates}");
312+
if (updates is TLUpdateShort)
313+
{
314+
var updateShort = updates as TLUpdateShort;
315+
Console.WriteLine($"Short: {updateShort.Update}");
316+
if (updateShort.Update is TLUpdateUserStatus)
317+
{
318+
var status = updateShort.Update as TLUpdateUserStatus;
319+
Console.WriteLine($"User {status.UserId} is {status.Status}");
320+
if (status.Status is TLUserStatusOnline)
321+
{
322+
try
323+
{
324+
var peer = new TLInputPeerUser() { UserId = status.UserId };
325+
client.SendMessageAsync(peer, "Você está online.").Wait();
326+
} catch {}
327+
}
328+
}
329+
}
330+
else if (updates is TLUpdateShortMessage)
331+
{
332+
var message = updates as TLUpdateShortMessage;
333+
Console.WriteLine($"Message: {message.Message}");
334+
MarkMessageRead(client, new TLInputPeerUser() { UserId = message.UserId }, message.Id);
335+
}
336+
else if (updates is TLUpdateShortChatMessage)
337+
{
338+
var message = updates as TLUpdateShortChatMessage;
339+
Console.WriteLine($"Chat Message: {message.Message}");
340+
MarkMessageRead(client, new TLInputPeerChat() { ChatId = message.ChatId }, message.Id);
341+
}
342+
else if (updates is TLUpdates)
343+
{
344+
var allUpdates = updates as TLUpdates;
345+
foreach (var update in allUpdates.Updates)
346+
{
347+
Console.WriteLine($"\t{update}");
348+
if (update is TLUpdateNewChannelMessage)
349+
{
350+
var metaMessage = update as TLUpdateNewChannelMessage;
351+
var message = metaMessage.Message as TLMessage;
352+
Console.WriteLine($"Channel message: {message.Message}");
353+
var channel = allUpdates.Chats[0] as TLChannel;
354+
MarkMessageRead(client,
355+
new TLInputPeerChannel() { ChannelId = channel.Id, AccessHash = channel.AccessHash.Value },
356+
message.Id );
357+
}
358+
}
359+
360+
foreach(var user in allUpdates.Users)
361+
{
362+
Console.WriteLine($"{user}");
363+
}
364+
365+
foreach (var chat in allUpdates.Chats)
366+
{
367+
Console.WriteLine($"{chat}");
368+
}
369+
}
370+
}
371+
372+
private void MarkMessageRead(TelegramClient client, TLAbsInputPeer peer, int id)
373+
{
374+
// An exception happens here but it's not fatal.
375+
try
376+
{
377+
var request = new TLRequestReadHistory();
378+
request.MaxId = id;
379+
request.Peer = peer;
380+
client.SendRequestAsync<bool>(request).Wait();
381+
}
382+
catch (InvalidOperationException e){
383+
System.Console.WriteLine($"MarkMessageRead Error: {e.getMessage()}")
384+
}
385+
386+
}
387+
}
388+
}
389+
```
390+
140391
# Available Methods
141392

142393
For your convenience TLSharp have wrappers for several Telegram API methods. You could add your own, see details below.

TLSharp.Core/Network/Exceptions.cs

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
using System;
2+
namespace TLSharp.Core.Network
3+
{
4+
public class FloodException : Exception
5+
{
6+
public TimeSpan TimeToWait { get; private set; }
7+
8+
internal FloodException(TimeSpan timeToWait)
9+
: base($"Flood prevention. Telegram now requires your program to do requests again only after {timeToWait.TotalSeconds} seconds have passed ({nameof(TimeToWait)} property)." +
10+
" If you think the culprit of this problem may lie in TLSharp's implementation, open a Github issue please.")
11+
{
12+
TimeToWait = timeToWait;
13+
}
14+
}
15+
16+
public class BadMessageException : Exception
17+
{
18+
internal BadMessageException(string description) : base(description)
19+
{
20+
}
21+
}
22+
23+
internal abstract class DataCenterMigrationException : Exception
24+
{
25+
internal int DC { get; private set; }
26+
27+
private const string REPORT_MESSAGE =
28+
" See: https://github.com/sochix/TLSharp#i-get-a-xxxmigrationexception-or-a-migrate_x-error";
29+
30+
protected DataCenterMigrationException(string msg, int dc) : base(msg + REPORT_MESSAGE)
31+
{
32+
DC = dc;
33+
}
34+
}
35+
36+
internal class PhoneMigrationException : DataCenterMigrationException
37+
{
38+
internal PhoneMigrationException(int dc)
39+
: base($"Phone number registered to a different DC: {dc}.", dc)
40+
{
41+
}
42+
}
43+
44+
internal class FileMigrationException : DataCenterMigrationException
45+
{
46+
internal FileMigrationException(int dc)
47+
: base($"File located on a different DC: {dc}.", dc)
48+
{
49+
}
50+
}
51+
52+
internal class UserMigrationException : DataCenterMigrationException
53+
{
54+
internal UserMigrationException(int dc)
55+
: base($"User located on a different DC: {dc}.", dc)
56+
{
57+
}
58+
}
59+
60+
internal class NetworkMigrationException : DataCenterMigrationException
61+
{
62+
internal NetworkMigrationException(int dc)
63+
: base($"Network located on a different DC: {dc}.", dc)
64+
{
65+
}
66+
}
67+
68+
69+
}

0 commit comments

Comments
 (0)