Ejemplo n.º 1
0
        public async Task <bool> RemoveChannelUser(int channelId, long channelHash, int userId, long userHash, bool kicked)
        {
            await client.ConnectAsync();

            TLRequestKickFromChannel req = new TLRequestKickFromChannel
            {
                channel = new TLInputChannel
                {
                    access_hash = channelHash,
                    channel_id  = channelId
                },
                user_id = new TLInputUser
                {
                    access_hash = userHash,
                    user_id     = userId
                },
                kicked = kicked
            };

            try
            {
                TLUpdates result = await client.SendRequestAsync <TLUpdates>(req);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public static async Task <bool> JoinChannel(string channelusername)
        {
            //finding channel
            var update = await _client.SearchUserAsync(channelusername);

            var channel = update.Chats.Where(c => c.GetType() == typeof(TLChannel)).Cast <TLChannel>().FirstOrDefault();

            if (channel != null)
            {
                var request = new TLRequestJoinChannel()
                {
                    Channel = new TLInputChannel()
                    {
                        AccessHash = (long)channel.AccessHash, ChannelId = channel.Id
                    }
                };

                TLUpdates resJoinChannel = await _client.SendRequestAsync <TLUpdates>(request);

                if (resJoinChannel != null)
                {
                    Console.WriteLine($"------*successfully Joined to {channel.Title}.  ");
                    return(true);
                }

                return(false);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 3
0
        public async Task <bool> AddChannelUser(int channelId, long channelHash, int userId, long userHash)
        {
            await client.ConnectAsync();

            TLRequestInviteToChannel req = new TLRequestInviteToChannel
            {
                channel = new TLInputChannel
                {
                    access_hash = channelHash,
                    channel_id  = channelId
                },
                users = new TLVector <TLAbsInputUser>
                {
                    lists = new List <TLAbsInputUser>
                    {
                        new TLInputUser
                        {
                            access_hash = userHash,
                            user_id     = userId
                        }
                    }
                }
            };

            try
            {
                TLUpdates result = await client.SendRequestAsync <TLUpdates>(req);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 4
0
        private async void forward()
        {
            List <TLChannel> TargetChannel = new List <TLChannel>();

            TLChannel          targetchanel = TargetChannel[0];
            TLInputPeerChannel cha          = new TLInputPeerChannel();

            cha.ChannelId  = targetchanel.Id;
            cha.AccessHash = (long)targetchanel.AccessHash;


            Random rand = new Random();

            TLVector <long> a = new TLVector <long>();

            a.lists.Add(rand.Next());
            TLVector <int> b = new TLVector <int>();

            b.lists.Add(tlMessage.id);
            TLRequestForwardMessages aa = new TLRequestForwardMessages();

            aa.FromPeer    = peer;
            aa.ToPeer      = cha;
            aa.RandomId    = a;
            aa.MessageId   = tlMessage.id;
            aa.Id          = b;
            aa.Silent      = true;
            aa.WithMyScore = true;

            TLUpdates rr = await client.SendRequestAsync <TLUpdates>(aa);
        }
Ejemplo n.º 5
0
        public async Task <bool> JoinChannel(string channelname)
        {
            try
            {
                TLChannel channel = await FindChannel(channelname);

                var req = new TeleSharp.TL.Channels.TLRequestJoinChannel()
                {
                    Channel = new TLInputChannel
                    {
                        ChannelId  = channel.Id,
                        AccessHash = (long)channel.AccessHash
                    }
                };
                TLUpdates resJoinChannel = await client.SendRequestAsync <TLUpdates>(req);

                return(true);
            }
            catch (Exception ex)
            {
                if (ex.Message == "AUTH_KEY_UNREGISTERED")
                {
                    bool sessionRemoved = this.RemoveSession();
                    if (sessionRemoved)
                    {
                        await this.Reconnect();
                    }
                }
                return(false);
            }
        }
Ejemplo n.º 6
0
        public async Task <bool> AddChatUser(int chatId, int userId, long accessHash, int forwardMessageCount = 0)
        {
            await client.ConnectAsync();

            TLRequestAddChatUser req = new TLRequestAddChatUser
            {
                chat_id = chatId,
                user_id = new TLInputUser
                {
                    user_id     = userId,
                    access_hash = accessHash
                },
                fwd_limit = forwardMessageCount
            };

            try
            {
                TLUpdates result = await client.SendRequestAsync <TLUpdates>(req);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 7
0
        public async Task <bool> RemoveChatUser(int chatId, int userId, long accessHash)
        {
            await client.ConnectAsync();

            TLRequestDeleteChatUser req = new TLRequestDeleteChatUser
            {
                chat_id = chatId,
                user_id = new TLInputUser
                {
                    user_id     = userId,
                    access_hash = accessHash
                }
            };

            try
            {
                TLUpdates result = await client.SendRequestAsync <TLUpdates>(req);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 8
0
        public async Task <TLChat> CreateChat(int userId, long accessHash, string title)
        {
            await client.ConnectAsync();

            TLRequestCreateChat req = new TLRequestCreateChat
            {
                title = title,
                users = new TLVector <TLAbsInputUser>
                {
                    lists = new List <TLAbsInputUser>
                    {
                        new TLInputUser {
                            user_id     = userId,
                            access_hash = accessHash
                        }
                    }
                }
            };

            TLUpdates result = await client.SendRequestAsync <TLUpdates>(req);

            var chat = result.chats.lists
                       .Where(c => c.GetType() == typeof(TLChat))
                       .Cast <TLChat>()
                       .FirstOrDefault();

            if (chat == null)
            {
                throw new Exception("Error creating chat");
            }
            await this.ToggleChatAdmin(chat.id, false);

            return(chat);
        }
Ejemplo n.º 9
0
        public async Task <TLUpdates> GetPedningUpdate(int userId)
        {
            await Task.CompletedTask;

            if (userId == 2)
            {
            }
            var result = new TLUpdates();

            result.Updates = new TLVector <TLAbsUpdate>();
            result.Users   = new TLVector <TLAbsUser>();
            result.Chats   = new TLVector <TLAbsChat>();
            bool clear = false;

            foreach (var update in updates)
            {
                foreach (var u in update.Updates)
                {
                    if (u is TLUpdateNewMessage)
                    {
                        var m = (u as TLUpdateNewMessage).Message as MTProto.NET.Schema.Layer72.TLMessage;
                        if (m != null && m.ToId is TLPeerUser && ((TLPeerUser)m.ToId).UserId == userId)
                        {
                            result.Updates.Add(u);
                            clear = true;
                        }
                    }
                }
            }
            if (clear)
            {
                updates.Clear();
            }
            return(result);
        }
Ejemplo n.º 10
0
        public async Task AddUpdates(IStore store, TLUpdates updates)
        {
            var pts = data.Pts;

            //data.Seq++;
            foreach (var update in updates.Updates)
            {
                pts++;
                update.GetType().GetProperty("Pts").SetValue(update, pts);
                update.GetType().GetProperty("PtsCount").SetValue(update, 1);
            }
            data.Seq++;
            data.Pts     = pts;
            updates.Seq  = data.Seq;
            updates.Date = MTServer.Services.Utils().ToTelegramDate(DateTime.UtcNow);
            using (var update_store = store.GetUserUpdateStore())
            {
                var _data = MTServer.Services.Factory().CreateUserUpdate();
                _data.UserId   = this.data.Id;
                _data.Pts      = data.Pts;
                _data.PtsCount = updates.Updates.Count;
                _data.Content  = updates.ToByteArray();
                await update_store.AddUpdate(_data);

                using (var user_store = store.GetUserStore())
                {
                    await user_store.Update(this.data);
                }
            }
        }
Ejemplo n.º 11
0
        private async void button1_Click(object sender, EventArgs e)
        {
            string grhash = GHash.Text.Trim().Replace("https://t.me/joinchat/", "").Replace("/", "");
            TLRequestImportChatInvite RCHI = new TLRequestImportChatInvite();

            RCHI.hash = grhash;

            TLUpdates chat = await Client.SendRequestAsync <TLUpdates>(RCHI);
        }
Ejemplo n.º 12
0
        public async Task <TLUpdates> CreateChannel(string title, string about, bool megaGroup, bool broadcast)
        {
            await client.ConnectAsync();

            TLRequestCreateChannel req = new TLRequestCreateChannel
            {
                title     = title,
                about     = about,
                megagroup = megaGroup,
                broadcast = broadcast
            };

            TLUpdates result = await client.SendRequestAsync <TLUpdates>(req);

            return(result);
        }
Ejemplo n.º 13
0
        public async Task <bool> ChatMigrate(int chatId)
        {
            await client.ConnectAsync();

            TLRequestMigrateChat req = new TLRequestMigrateChat
            {
                chat_id = chatId
            };

            try
            {
                TLUpdates result = await client.SendRequestAsync <TLUpdates>(req);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        private static int?GetIdMessageAdded2(TLUpdates r2)
        {
            if (r2 == null)
            {
                return(null);
            }

            if (r2.Updates == null || r2.Updates.Count == 0)
            {
                return(null);
            }

            foreach (var r3 in r2.Updates)
            {
                if (r3 is TLUpdateMessageID r4)
                {
                    return(r4.Id);
                }
                else if (r3 is TLUpdateReadChannelInbox r5)
                {
                    return(r5.MaxId);
                }
                else if (r3 is TLUpdateNewChannelMessage r6)
                {
                    var r7 = r6.Message;
                    if (r7 is TLMessageService r8)
                    {
                        return(r8.Id);
                    }
                    ;
                }
                else
                {
                    ;
                }
            }

            return(null);
        }
Ejemplo n.º 15
0
        public async Task <bool> RenameChat(int chatId, string newName)
        {
            await client.ConnectAsync();

            TLRequestEditChatTitle req = new TLRequestEditChatTitle
            {
                chat_id = chatId,
                title   = newName
            };

            TLUpdates result = await client.SendRequestAsync <TLUpdates>(req);

            var chat = result.chats.lists
                       .Where(c => c.GetType() == typeof(TLChat))
                       .Cast <TLChat>()
                       .FirstOrDefault();

            if (chat == null)
            {
                throw new Exception("Error renaming chat");
            }
            return(true);
        }
Ejemplo n.º 16
0
        public async Task ForwardMessgae(TLMessage message, TLChannel from, TLUser to)
        {
            Random rand = new Random();

            TLInputPeerChannel cha = new TLInputPeerChannel
            {
                ChannelId  = from.Id,
                AccessHash = from.AccessHash.Value
            };


            TLInputPeerUser us = new TLInputPeerUser
            {
                AccessHash = to.AccessHash.Value,
                UserId     = to.Id
            };


            TLVector <long> a = new TLVector <long>();

            a.Add(rand.Next());
            TLVector <int> b = new TLVector <int>();

            b.Add(message.Id);
            TLRequestForwardMessages aa = new TLRequestForwardMessages();

            aa.FromPeer  = cha;
            aa.ToPeer    = us;
            aa.RandomId  = a;
            aa.MessageId = message.Id;
            aa.Id        = b;

            aa.Silent      = true;
            aa.WithMyScore = true;

            TLUpdates rr = await telegramClient.SendRequestAsync <TLUpdates>(aa);
        }
Ejemplo n.º 17
0
 public ReceiveUpdatesEventArgs(TLUpdates updates)
 {
     Updates = updates;
 }
 public UpdateProcesingContext(TLUpdates updates)
 {
     this.Updates = updates;
 }
Ejemplo n.º 19
0
        public async Task <MTObject> Handle(IMessageContext <NET.Schema.Layer72.TLSendMessage> context)
        {
            await Task.CompletedTask;
            TLUpdates result = null;

            try
            {
                result         = new TLUpdates();
                result.Updates = new TLVector <TLAbsUpdate>();
                result.Users   = new TLVector <TLAbsUser>();
                result.Chats   = new TLVector <TLAbsChat>();
                var session = this.manager.GetSession(context.AuthKey());
                if (session == null)
                {
                    throw new Exception("Session Not Found.");
                }
                var sendMessage = context.Body;
                if (sendMessage == null)
                {
                    throw new Exception(
                              "SendMessage is NULL!");
                }
                if (sendMessage.Peer == null)
                {
                    throw new ArgumentException(nameof(NET.Schema.Layer72.TLSendMessage.Peer));
                }
                if (sendMessage.Peer is TLInputPeerUser)
                {
                    //var sentMessage = await session.ChatManager.SendPrivateChatMessage(session.GetUserId(), (sendMessage.Peer as TLInputPeerUser).UserId, sendMessage);
                    var sentMessage = await this.messagingService.SendPrivateChatMessage(session.GetUserId(), (sendMessage.Peer as TLInputPeerUser).UserId, sendMessage);

                    //count++;
                    //result.Seq = count;
                    //result.Date = MTServer.Instance.Services.Utils().ToTelegramDate(DateTime.UtcNow);
                    //result.Updates.Add(new TLUpdateNewMessage
                    //{
                    //	Pts = count,
                    //	PtsCount = 1,

                    //	Message = new MTProto.NET.Schema.Layer72.TLMessage
                    //	{
                    //		FromId = session.GetUserId(),
                    //		Id = sentMessage.Data.Id,
                    //		Message = sentMessage.Data.Message,
                    //		ToId = new TLPeerUser
                    //		{
                    //			UserId = sentMessage.Data.ToPeerId
                    //		}
                    //	}
                    //});
                    //await session.UpdateManager.SendUpdate(result);
                    //result = new TLUpdates();
                    //result.Updates = new TLVector<TLAbsUpdate>();
                    //result.Users = new TLVector<TLAbsUser>();
                    //result.Chats = new TLVector<TLAbsChat>();
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
            catch (Exception err)
            {
                this.logger.LogError(
                    $"An error occured while trying to handle SendMessageRequest. Request:{context}, Error:\r\n{err.GetBaseException().Message}");
                throw;
            }

            //result.Updates.Add(new TLUpdateNewMessage
            //{

            //	Message = new MTProto.NET.Schema.Layer72.TLMessage
            //	{
            //		Message = "hi there",
            //		ToId = new TLPeerUser
            //		{
            //			UserId = 12,
            //		}
            //	}
            //});

            return(result);
        }
Ejemplo n.º 20
0
        public async Task SendUpdate(TLUpdates updates)
        {
            UpdateManager.updates.Add(updates);

            return;


            if (updates == null)
            {
                throw new ArgumentNullException(nameof(updates));
            }
            try
            {
                var context = new UpdateProcesingContext(updates);
                foreach (var update in updates.Updates)
                {
                    await UpdateNewMessage(context, update, (a, b, n) => Task.CompletedTask);
                }
                await Task.CompletedTask;
                foreach (var userId in context.GetDistictUsers())
                {
                    try
                    {
                        var userUpdates  = context.GetUserUpdates(userId);
                        var user_updates = new TLUpdates
                        {
                            Chats   = updates.Chats,
                            Users   = updates.Users,
                            Updates = new TLVector <TLAbsUpdate>()
                        };
                        userUpdates.ToList().ForEach(x => user_updates.Updates.Add(x));
                        user_updates.Seq = 0;
                        using (var store = this.serviceProvider.GetService <IStore>().GetUserStore())
                        {
                            var userData = await store.GetUserById(userId);

                            if (userData == null)
                            {
                                throw new Exception($"User Not Found {userId}");
                            }
                            var user = this.serviceProvider.Factory().CreateUser(userData);
                            await user.AddUpdates(this.serviceProvider.Store(), user_updates);

                            /// Send it to session
                            ///
                            //await this.serviceProvider.GetService<IMTSessionManager>()
                            //	.GetSessionByUserId(userId)
                            //	.PostUpdate(user_updates);
                            //MTHttpTransport.POSTED = 1;

                            UpdateManager.updates.Add(user_updates);
                        }
                    }
                    catch (Exception err)
                    {
                        this.logger.LogWarning(
                            "An error occured while trying to process user updates. Error:\r\n{0}", err.GetBaseException().Message);
                    }
                }
            }
            catch (Exception err)
            {
                this.logger.LogError(
                    "An error occured while trying to process updates: \r\n{0}", err.GetBaseException().Message);
            }
        }
Ejemplo n.º 21
0
        private async Task <object> ProduceUpdates(IMessageContext context)
        {
            await Task.CompletedTask;
            TLUpdates result = null;

            try
            {
                if (context.MessageType() == typeof(Contracts.Messages.NewMessageCreated))
                {
                    var new_message = context.Body as NewMessageCreated;
                    if (new_message != null && new_message.PeerIdType == 0)
                    {
                        using (var store = MTServer.Services.Store().GetUserStore())
                        {
                            var peer_user = await store.GetUserById(new_message.ToPeerId);

                            result         = new TLUpdates {
                            };
                            result.Updates = new TLVector <TLAbsUpdate>();
                            result.Users   = new TLVector <TLAbsUser>();
                            result.Chats   = new TLVector <TLAbsChat>();

                            var pts = peer_user.Pts + 1;
                            var seq = peer_user.Seq + 1;
                            result.Updates.Add(new TLUpdateNewMessage
                            {
                                Pts      = pts,
                                PtsCount = 1,
                                Message  = new MTProto.NET.Schema.Layer72.TLMessage
                                {
                                    Message = new_message.Text,
                                    ToId    = new TLPeerUser {
                                        UserId = new_message.ToPeerId
                                    },
                                    FromId = new_message.FromUserId,
                                    Date   = new_message.Date == 0 ? Extensions.ToTelegramDate(DateTime.UtcNow) : new_message.Date,
                                    Id     = new_message.Id
                                }
                            });
                            var from_user = await store.GetUserById(new_message.FromUserId);

                            result.Users.Add(new MTProto.NET.Schema.Layer72.TLUser {
                                Id        = from_user.Id,
                                FirstName = from_user.FirstName,
                                LastName  = from_user.LastName
                            });

                            peer_user.Pts = pts;
                            peer_user.Seq = seq;
                            result.Seq    = seq;
                            await store.Update(peer_user);

                            await MTServer.Bus.Publish(new UpdateCreated
                            {
                                Payload = result,
                                UserId  = new_message.ToPeerId,
                            });
                        }
                    }
                }
                if (context.Body as Contracts.Account.ProfileChanged != null)
                {
                    var profileChange = context.Body as Contracts.Account.ProfileChanged;
                    using (var store = MTServer.Services.Store().GetUserStore())
                    {
                        var userIds = new int[] { 1, 2 };
                        foreach (var userid in userIds)
                        {
                            var user_data = await store.GetUserById(userid);

                            result         = new TLUpdates {
                            };
                            result.Updates = new TLVector <TLAbsUpdate>();
                            result.Users   = new TLVector <TLAbsUser>();
                            result.Chats   = new TLVector <TLAbsChat>();
                            var pts      = user_data.Pts;
                            var seq      = user_data.Seq;
                            var ptscount = 0;

                            var user = new MTProto.NET.Schema.Layer72.TLUser
                            {
                                Id        = user_data.Id,
                                FirstName = user_data.FirstName,
                                LastName  = user_data.LastName,
                                Contact   = true
                            };
                            result.Users.Add(user);
                            result.Updates.Add(new TLUpdateUserName
                            {
                                FirstName = profileChange.FirstName,
                                LastName  = profileChange.LastName,
                                UserId    = profileChange.AccountId,
                                Username  = profileChange.UserName ?? ""
                            });

                            await MTServer.Bus.Publish(new UpdateCreated
                            {
                                Payload = result,
                                UserId  = userid
                            });
                        }
                    }
                }
                if (result != null)
                {
                }
            }
            catch (Exception err)
            {
                this.logger.LogError(
                    $"An error occured while trying to ManageUpdates: \r\n{0}", err.GetBaseException().Message);
            }

            return("ok");
        }