using AuthorizeVK;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Xml.Serialization;
using VkUp.Targets;
using VkUp.Targets.Settings;
using VoiceBot;
namespace VkUp
{
public class Account
{
public List<AutoansTarget> autoansTargets;
public bool enabledAutoans { get; set; }
public bool SetActibityAuto { get; set; }
public int DelayAuto { get; set; }
public bool ReplyToMessage { get; set; }
public string AccInfo { get; set; }
public string Userid { get; set; }
public Account()
{
rnd = new Random();
}
public Account(string login, string password)
{
rnd = new Random();
this.login = login;
this.password = password;
targets = new List<string>();
names = new List<string>();
namePlace = new List<string>();
content = new List<string>();
autoansTargets = new List<AutoansTarget>();
}
public void SetTargetAutoans(DataGridViewRowCollection rows)
{
autoansTargets.Clear();
foreach (DataGridViewRow dataGrid in rows)
{
if (dataGrid.Cells[1].Value != null)
{
autoansTargets.Add(new AutoansTarget()
{
Name = (dataGrid.Cells[0].Value ?? "").ToString(),
Target = dataGrid.Cells[1].Value.ToString(),
Ids = dataGrid.Cells[2].Value.ToString(),
Content = dataGrid.Cells[3].Value.ToString()
});
}
}
}
public void SetTargets(DataGridViewRowCollection rows)
{
targets.Clear();
names.Clear();
namePlace.Clear();
content.Clear();
foreach (object obj in ((IEnumerable)rows))
{
DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
if (dataGridViewRow.Cells[1].Value != null)
{
names.Add(dataGridViewRow.Cells[0].Value.ToString());
targets.Add(dataGridViewRow.Cells[1].Value.ToString());
namePlace.Add(dataGridViewRow.Cells[2].Value.ToString());
content.Add(dataGridViewRow.Cells[3].Value.ToString());
}
}
}
public int CheckToken()
{
token_status = false;
if (token == null)
{
return -1;
}
int result;
try
{
VkParametes.APIRequest("friends.getRequests", "", token, "");
token_status = true;
result = 0;
}
catch (Exception ex)
{
if (ex.Message.Contains("could not get application"))
{
result = 1;
}
else
{
Log.Push("[Ошибка уровня API]: " + ex.Message);
result = 2;
}
}
return result;
}
public int GetToken()
{
if (CheckToken() == 0)
{
return 0;
}
try
{
var auth = new Auth(login, password);
token = auth.Authorize();
Userid = auth.UserId;
dynamic json = JsonConvert.DeserializeObject(VkParametes.APIRequest("users.get", $"user_ids={Userid}", token, ""));
AccInfo = $"{json["response"][0]["first_name"]} {json["response"][0]["last_name"]}";
token_status = true;
return 0;
}
catch (Exception ex)
{
Log.Push($"Неизвестная ошибка авторизации: {ex.Message}");
return -1;
}
}
public void SaveToDisk()
{
var xmlSerializer = new XmlSerializer(typeof(Account));
var textWriter = new StreamWriter($"Accounts\\{login}.xml");
xmlSerializer.Serialize(textWriter, this);
textWriter.Close();
}
public void TheAnswerToKeyword(int index)
{
var target = targets[index];
var fs = new FlooderSettings();
if (fs.GetHistory(target, token) != "Ок")
{
dynamic json = JsonConvert.DeserializeObject(fs.GetHistory(target, token));
var text = Convert.ToString(json["response"]["items"][0]["text"]);
dynamic url = JsonConvert.DeserializeObject(VkParametes.APIRequest("docs.getUploadServer", "type=audio_message", token));
dynamic file = JsonConvert.DeserializeObject(Helper.HttpUploadFile(Convert.ToString(url["response"]["upload_url"]), "Audio\\" + fs.RandomAudio(), "file", "audio/MP3"));
dynamic saveDocs = JsonConvert.DeserializeObject(VkParametes.APIRequest("docs.save", $"file={file["file"]}", token));
var id = saveDocs["response"]["audio_message"]["id"];
var owner_id = saveDocs["response"]["audio_message"]["owner_id"];
if (target.StartsWith("im?sel="))
{
var users = StrWrk.qSubstr(target, "im?sel=", false);
if (fs.Items.Contains(text))
{
VkParametes.APIRequest("messages.send", $"user_id={users}&attachment=doc{owner_id}_{id}", token, "");
}
}
else if (target.StartsWith("im?sel=c"))
{
var chat = StrWrk.qSubstr(target, "im?sel=c", false);
if (fs.Items.Contains(text))
{
VkParametes.APIRequest("messages.send", $"chat_id={chat}&attachment=doc{owner_id}_{id}", token, "");
}
}
}
}
public void FlooderSendMessage(string msg, int index)
{
string text = targets[index];
var name = names[index];
var contains = content[index];
var fs = new FlooderSettings();
if (names[index] != null)
{
if (namePlace[index] == "Начало")
msg = $"{name} {msg}";
else if (namePlace[index] == "Конец")
msg = $"{msg} {name}";
}
try
{
if (text.StartsWith("im?sel=c"))
{
var chat = StrWrk.qSubstr(text, "im?sel=c", false);
if (setActive)
VkParametes.SetActivity(text, token);
switch (contains)
{
case "Текст":
VkParametes.APIRequest("messages.send", $"chat_id={chat}&message={msg}", token, "");
break;
case "Текст+стикер":
VkParametes.APIRequest("messages.send", $"chat_id={chat}&message={msg}", token, "");
VkParametes.APIRequest("messages.send", $"chat_id={chat}&sticker_id={fs.RandomStickers()}", token);
break;
case "Рандом":
var r = rnd.Next(0, 7);
if (r == 1 || r == 3 || r == 0)
{
VkParametes.APIRequest("messages.send", $"chat_id={chat}&message={msg}", token, "");
}
else
{
VkParametes.APIRequest("messages.send", $"chat_id={chat}&message={msg}", token, "");
VkParametes.APIRequest("messages.send", $"chat_id={chat}&sticker_id={fs.RandomStickers()}", token);
}
break;
}
}
else if (text.StartsWith("im?sel="))
{
var user = StrWrk.qSubstr(text, "im?sel=", false);
if (setActive)
VkParametes.SetActivity(text, token);
switch (contains)
{
case "Текст":
VkParametes.APIRequest("messages.send", $"user_id={user}&message={msg}", token, "");
break;
case "Текст+стикер":
VkParametes.APIRequest("messages.send", $"user_id={user}&message={msg}", token, "");
VkParametes.APIRequest("messages.send", $"user_id={user}&sticker_id={fs.RandomStickers()}", token);
break;
case "Рандом":
var r = rnd.Next(0, 7);
if (r == 1 || r == 3 || r == 0)
{
VkParametes.APIRequest("messages.send", $"user_id={user}&message={msg}", token, "");
}
else
{
VkParametes.APIRequest("messages.send", $"user_id={user}&message={msg}", token, "");
VkParametes.APIRequest("messages.send", $"user_id={user}&sticker_id={fs.RandomStickers()}", token);
}
break;
}
}
else
Log.Push($"[{login}]: {text} — неверный формат ссылки");
}
catch (Exception ex)
{
Log.Push("[Ошибка уровня API]: " + ex.Message);
}
}
private void WorksFlooder()
{
var fs = new FlooderSettings();
int index = -1;
while (Working && enabled)
{
try
{
if (targets.Count == 0)
{
Log.Push($"Отсутствуют цели флудера...");
return;
}
else
{
index = (index + 1) % targets.Count;
TheAnswerToKeyword(index);
FlooderSendMessage(MainForm.phrases[rnd.Next(0, MainForm.phrases.Length)], index);
}
}
catch (Exception ex)
{
Log.Push($"[Поток {login}]: " + ex.Message);
}
fs.RandomDelay(TimeDelay, delay, DelayMax);
}
}
public void AutoansSendMessage(string message, int index)
{
var target = autoansTargets[index].Target;
var name = autoansTargets[index].Name;
var ids = autoansTargets[index].Ids;
var content = autoansTargets[index].Content;
var fs = new FlooderSettings();
if (!string.IsNullOrEmpty(name))
message = $"{name} {message}";
if (target.StartsWith("im?sel=c"))
{
var chat = StrWrk.qSubstr(target, "im?sel=c", false);
dynamic history = JsonConvert.DeserializeObject(
VkParametes.APIRequest("messages.getHistory", $"peer_id={2000000000 + int.Parse(chat)}&count=1", token, ""));
var fromId = history["response"]["items"][0]["from_id"];
var idMessage = history["response"]["items"][0]["id"];
foreach (var id in ids.Split(','))
{
if (fromId == id)
{
if (SetActibityAuto)
{
VkParametes.APIRequest("messages.setActivity", $"chat_id={chat}&type=typing", token, "");
Thread.Sleep(2000);
}
if (content == "Текст")
{
if (ReplyToMessage)
VkParametes.APIRequest("messages.send", $"chat_id={chat}&message={message}&reply_to={idMessage}", token, "");
else
VkParametes.APIRequest("messages.send", $"chat_id={chat}&message={message}", token, "");
}
else if (content == "Текст+стикер")
{
if (ReplyToMessage)
{
VkParametes.APIRequest("messages.send", $"chat_id={chat}&message={message}&reply_to={idMessage}", token, "");
VkParametes.APIRequest("messages.send", $"chat_id={chat}&sticker_id={fs.RandomStickers()}&reply_to={idMessage}", token, "");
}
else
{
VkParametes.APIRequest("messages.send", $"chat_id={chat}&message={message}", token, "");
VkParametes.APIRequest("messages.send", $"chat_id={chat}&sticker_id={fs.RandomStickers()}", token, "");
}
}
}
}
}
else if (target.StartsWith("im?sel="))
{
if (ids.Contains(","))
{
Log.Push("Невозможно указать несколько ID для личных сообщений.");
return;
}
var user = StrWrk.qSubstr(target, "im?sel=", false);
dynamic json = JsonConvert.DeserializeObject(
VkParametes.APIRequest("messages.getHistory", $"user_id={user}&count=1", token, ""));
var fromId = json["response"]["items"][0]["from_id"];
var id = json["response"]["items"][0]["id"];
if (fromId == ids)
{
if (SetActibityAuto)
{
VkParametes.APIRequest("messages.setActivity", $"user_id={user}&type=typing", token, "");
Thread.Sleep(2000);
}
if (content == "Текст")
{
if (ReplyToMessage)
VkParametes.APIRequest("messages.send", $"user_id={user}&message={message}&reply_to={id}", token, "");
else
VkParametes.APIRequest("messages.send", $"user_id={user}&message={message}", token, "");
}
else if (content == "Текст+стикер")
{
if (ReplyToMessage)
{
VkParametes.APIRequest("messages.send", $"user_id={user}&message={message}&reply_to={id}", token, "");
VkParametes.APIRequest("messages.send", $"user_id={user}&sticker_id={fs.RandomStickers()}&reply_to={id}", token, "");
}
else
{
VkParametes.APIRequest("messages.send", $"user_id={user}&message={message}", token, "");
VkParametes.APIRequest("messages.send", $"user_id={user}&sticker_id={fs.RandomStickers()}", token, "");
}
}
}
}
}
public void WorkAutoans()
{
int index = -1;
if (autoansTargets.Count == 0)
{
Log.Push("Отсутствуют цели автоответчика...");
return;
}
while (Working && enabledAutoans)
{
try
{
index = (index + 1) % autoansTargets.Count;
AutoansSendMessage(MainForm.phrases[rnd.Next(MainForm.phrases.Length)], index);
Thread.Sleep(DelayAuto);
}
catch (Exception ex)
{
Log.Push($"[Автоответчик]: {ex.Message}");
}
}
}
public void AsyncWorker()
{
if (enabled)
new Thread(() => WorksFlooder()) { IsBackground = true }.Start();
if (enabledAutoans)
new Thread(() => WorkAutoans()) { IsBackground = true }.Start();
}
[NonSerialized]
public static bool Working;
[NonSerialized]
private Random rnd;
[NonSerialized]
public bool token_status;
public string login;
public string password;
public string token;
public List<string> targets;
public List<string> names;
public List<string> namePlace;
public List<string> content;
public int delay;
public bool enabled;
public bool setActive;
public int DelayMax;
public string TimeDelay;
}
}
Ну так в ошибке же написано что не так: обращение к элементу с несуществующим номером в коллекции.
Надо разбираться почему так получается и решать что с этим делать, в зависимости от причин и задачи.
А в какой строке-то хоть?)