Добавьте файлы проекта.

This commit is contained in:
Daria
2021-10-19 06:04:52 +03:00
parent 6ee25d0f59
commit eab3081ec2
187 changed files with 100839 additions and 0 deletions

View File

@@ -0,0 +1,84 @@
using SvetoforVKBot.Models.Updates;
using System;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class GetDRYearCommand
{
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
var chatId = update.@object.message.from_id;
MessagesSendParams @params = new MessagesSendParams();
var keyboardBuilder = new KeyboardBuilder().Clear();
int i = 0;
int year = 0;
Regex regex = new Regex("[^0-9]");
try
{
if (regex.Replace(update.@object.message.text, "").Length == 4)
year = Convert.ToInt32(regex.Replace(update.@object.message.text, ""));
if (year > 1920 && year < DateTime.Now.Year)
{
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Подписчик - Регистрация - ДР - Месяц";
db.SaveChanges();
for (i = 1; i <= 12; i++)
{
keyboardBuilder
.AddButton(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i), "selectDRMonth-" + year + "-" + i, KeyboardButtonColor.Primary);
if (i % 3 == 0)
keyboardBuilder.AddLine();
}
@params.Keyboard = keyboardBuilder
.Build();
@params.Message = "Выберите месяц своего рождения на клавиатуре. \n";
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
else
{
@params.Message = "Данные введены некорректно 😕 Введите, пожалуйста, текст в формате 1234 (4 цифры).";
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в GetDRYearCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
public int GetRandomId()
{
var intBytes = new byte[4];
Rng.GetBytes(intBytes);
return BitConverter.ToInt32(intBytes, 0);
}
}
}

View File

@@ -0,0 +1,51 @@
using System;
using System.Data.SqlClient;
using System.Linq;
using System.Text.RegularExpressions;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectDRMonthCommand : Command
{
public override string Name => "{\"button\":\"selectDRMonth-";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
Regex regex = new Regex("[^0-9]");
try
{
string[] payload = update.@object.message.payload.Split('-');
int curYear = Convert.ToInt32(regex.Replace(payload[1], ""));
int curMonth = Convert.ToInt32(regex.Replace(payload[2], ""));
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Подписчик - Регистрация - ДР - Число";
db.SaveChanges();
DateTime dt = new DateTime(curYear, curMonth, 1);
ShowCalendar showCalendar = new ShowCalendar();
showCalendar.Execute(update, client, db, dt);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectStudentDRMonthCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,86 @@
using System;
using System.Data.SqlClient;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using SvetoforVKBot.Models.Updates;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using VkNet;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using VkNet.Enums.SafetyEnums;
using SvetoforVKBot.Models.Commands.LK;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectDateCommand : Command
{
public override string Name => "{\"button\":\"selectDate-";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
Regex regex = new Regex("[^0-9]");
var keyboardBuilder = new KeyboardBuilder().Clear();
string tag = "";
try
{
string[] callBack = update.@object.message.payload.Split('-');
string[] date = callBack[1].Split('.');
DateTime selectedDateTime = new DateTime(Convert.ToInt32(regex.Replace(date[2], "")), Convert.ToInt32(regex.Replace(date[1], "")), Convert.ToInt32(regex.Replace(date[0], "")));
var user = db.Users.Single(usr => usr.chatId == chatId);
//SqlCommand getUser = new SqlCommand("SELECT reg FROM Users WHERE chatId = @chatId;", Con);
//getUser.Parameters.AddWithValue("@chatId", chatId);
//SqlDataReader rgetUser = getUser.ExecuteReader();
//rgetUser.Read();
//int reg = Convert.ToInt32(rgetUser["reg"]);
//rgetUser.Close();
if (user.reg == 1)
{
user.birthday = selectedDateTime;
user.tag = "Личный кабинет - Данные";
db.SaveChanges();
SelectEditDataCommand selectEditData = new SelectEditDataCommand();
selectEditData.Execute(update, client, db);
return;
}
else
{
user.birthday = selectedDateTime;
user.tag = "Подписчик - Регистрация - Телефон";
db.SaveChanges();
@params.Message = "Напишите номер телефона в формате 11 цифр через \"8\" или \"7\" \n";
keyboardBuilder
.AddButton("Отменить", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectDateCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,44 @@
using System;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectDateNavigationCommand : Command
{
public override string Name => "{\"button\":\"selectDateNavigation-";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
Regex regex = new Regex("[^0-9]");
try
{
string[] payload = update.@object.message.payload.Split('-');
payload[1] = payload[1].Replace("\"}", "");
DateTime curDateTime = DateTime.Parse(payload[1]);
ShowCalendar showCalendar = new ShowCalendar();
showCalendar.Execute(update, client, db, curDateTime);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectDateNavigationCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,309 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class ShowCalendar
{
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, DateTime curDateTime)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
string tag = "";
string str = "";
string month = "";
string plNext = "";
string plBack = "";
int i = 0, j = 0;
int weeks = 5, days = 1, dw = 1;
DateTime dt, dt1, dt2, dt3;
dt2 = new DateTime(curDateTime.Year, curDateTime.Month, 1);
dt3 = new DateTime(curDateTime.Year, curDateTime.Month, 1);
var row = new List<MessageKeyboardButton>();
var listRows = new List<List<MessageKeyboardButton>>();
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
try
{
for (i = 1; i <= 7; i++)
{
switch (i)
{
case 1:
str = "Пн";
break;
case 2:
str = "Вт";
break;
case 3:
str = "Ср";
break;
case 4:
str = "Чт";
break;
case 5:
str = "Пт";
break;
case 6:
str = "Сб";
break;
case 7:
str = "Вс";
break;
}
row = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){ Label = str,
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Default
},
};
listRows.Add(new List<MessageKeyboardButton>(row));
}
days = curDateTime.Day;
dt = new DateTime(curDateTime.Year, curDateTime.Month, 1);
if ((DateTime.DaysInMonth(curDateTime.Year, curDateTime.Month) == 28) && (dt.DayOfWeek == DayOfWeek.Monday))
weeks = 4;
if ((DateTime.DaysInMonth(curDateTime.Year, curDateTime.Month) >= 30) && (dt.DayOfWeek == DayOfWeek.Sunday))
weeks = 6;
for (i = 1; i <= weeks; i++)
{
row = new List<MessageKeyboardButton>();
if (days > DateTime.DaysInMonth(curDateTime.Year, curDateTime.Month)) break;
if (i == 4)
dt2 = new DateTime(curDateTime.Year, curDateTime.Month, days);
for (j = 0; j < 7; j++)
{
if (days <= DateTime.DaysInMonth(curDateTime.Year, curDateTime.Month))
{
dt = new DateTime(curDateTime.Year, curDateTime.Month, days);
dw = getDayOfWeek(dt.DayOfWeek);
if ((j + 1) == dw)
{
if (dt.Date < DateTime.Now.Date)
{
str = "·" + days.ToString() + "·";
if (listRows[j].Count < 4)
listRows[j].Add(new MessageKeyboardButton()
{
Action = new MessageKeyboardButtonAction()
{
Label = str,
Payload = "{\"button\":\"selectDate-" + dt.ToShortDateString() + "\"}",
Type = KeyboardButtonActionType.Text
},
Color = KeyboardButtonColor.Primary
});
}
else
if (listRows[j].Count < 4)
listRows[j].Add(
new MessageKeyboardButton()
{
Action = new MessageKeyboardButtonAction()
{
Label = "-" + days.ToString() + "-",
Type = KeyboardButtonActionType.Text
},
Color = KeyboardButtonColor.Default
});
days++;
}
else
if (listRows[j].Count < 4)
listRows[j].Add(
new MessageKeyboardButton()
{
Action = new MessageKeyboardButtonAction()
{
Label = "·",
Type = KeyboardButtonActionType.Text
},
Color = KeyboardButtonColor.Default
});
}
else
if (listRows[j].Count < 4)
listRows[j].Add(
new MessageKeyboardButton()
{
Action = new MessageKeyboardButtonAction()
{
Label = "·",
Type = KeyboardButtonActionType.Text
},
Color = KeyboardButtonColor.Default
});
}
}
foreach (var lr in listRows)
listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(lr));
month = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(curDateTime.Month);
dt1 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
if (dt2 == dt3) //генерируем вторую половину месяца
{
plBack = "{\"button\":\"selectDateNavigation-" + dt3.ToShortDateString() + "\"}";
plNext = "{\"button\":\"selectDateNavigation-" + dt3.AddMonths(1).ToShortDateString() + "\"}";
}
else //генерируем первую половину месяца
{
plBack = "{\"button\":\"selectDateNavigation-" + dt3.AddMonths(-1).AddDays(21 - getDayOfWeek(dt3.AddMonths(-1).DayOfWeek) + 1).ToShortDateString() + "\"}";
plNext = "{\"button\":\"selectDateNavigation-" + dt2.ToShortDateString() + "\"}";
}
if (dt1.Date > dt2.Date)
row = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){ Label = "<<", Payload = plBack,
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Default
},
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){ Label = month,
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Default
},
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){ Label = ">>", Payload = plNext,
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Default
},
};
else
row = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){ Label = "<<", Payload = plBack,
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Default
},
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){ Label = month,
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Default
},
};
listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row));
if (curDateTime.Year < DateTime.Now.Year)
row = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){ Label = "<<", Payload = "{\"button\":\"selectDateNavigation-" + curDateTime.AddYears(-1).ToShortDateString() + "\"}",
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Default
},
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){ Label = curDateTime.Year.ToString(),
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Default
},
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){ Label = ">>", Payload = "{\"button\":\"selectDateNavigation-" + curDateTime.AddYears(1).ToShortDateString() + "\"}",
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Default
},
};
else
row = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){ Label = "<<", Payload = "{\"button\":\"selectDateNavigation-" + curDateTime.AddYears(-1).ToShortDateString() + "\"}",
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Default
},
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){ Label = curDateTime.Year.ToString(),
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Default
},
};
listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row));
var user = db.Users.Single(usr => usr.chatId == chatId);
switch (user.tag)
{
case "Подписчик - Регистрация - ДР - Число":
@params.Message = "📅 Выберите дату своего рождения на календаре. \n";
break;
}
var buttons = new ReadOnlyCollection<ReadOnlyCollection<MessageKeyboardButton>>(listButtons);
var keyboard = new MessageKeyboard()
{
Buttons = buttons,
OneTime = false
};
@params.UserId = chatId;
@params.Keyboard = keyboard;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в ShowCalendarVK: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
private int GetRandomId()
{
var intBytes = new byte[4];
Rng.GetBytes(intBytes);
return BitConverter.ToInt32(intBytes, 0);
}
private int getDayOfWeek(DayOfWeek dw)
{
switch (dw)
{
case DayOfWeek.Monday:
return 1;
case DayOfWeek.Tuesday:
return 2;
case DayOfWeek.Wednesday:
return 3;
case DayOfWeek.Thursday:
return 4;
case DayOfWeek.Friday:
return 5;
case DayOfWeek.Saturday:
return 6;
case DayOfWeek.Sunday:
return 7;
}
return 1;
}
}
}

View File

@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Model.RequestParams;
using VkNet.Model.Keyboard;
using System.Collections.ObjectModel;
using System.Security.Cryptography;
using VkNet.Enums.SafetyEnums;
using SvetoforVKBot.Models.Dop;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class GetAgeCommand
{
public bool Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
int i = 0;
var keyboardBuilder = new KeyboardBuilder().Clear();
try
{
if (update.@object.message.text.Length > 0 && update.@object.message.text.Length <= 2)
{
// Согласовать по аттрибудам. Возможно привязан аттрибут к другому
var user = db.Users.Single(usr => usr.chatId == chatId);
Int32.TryParse(update.@object.message.text.Trim(), out int age);
user.birthday = DateTime.Today.AddYears(-1*age);
user.tag = "Регистрация - Деятельность";
db.SaveChanges();
//ТОчно так надо??
//ShowActivity showActivity = new ShowActivity();
//showActivity.Execute(update, client, db);
}
else
{
@params.UserId = chatId;
@params.Message = "Вы некорректно ввели возраст 🤔 Введите, пожалуйста, текст (до 2 символов).";
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в GetAgeCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return true;
}
return true;
}
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
public int GetRandomId()
{
var intBytes = new byte[4];
Rng.GetBytes(intBytes);
return BitConverter.ToInt32(intBytes, 0);
}
}
}

View File

@@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class GetFIOCommand
{
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
var chatId = update.@object.message.from_id;
MessagesSendParams @params = new MessagesSendParams();
var keyboardBuilder = new KeyboardBuilder().Clear();
int i = 0;
int btnCount = 0;
int btnLines = 0;
int startYear = DateTime.Now.Year - 18;
try
{
if (update.@object.message.text.Length > 0 && update.@object.message.text.Length <= 50)
{
var ids = new long[] { chatId };
var user = db.Users.Single(usr => usr.chatId == chatId);
user.fio = update.@object.message.text.Trim();
user.tag = "Подписчик - Регистрация - ДР - Год";
db.SaveChanges();
//editUser.Parameters.AddWithValue("@tag", "Подписчик - Регистрация - ДР - Год");
for (i = startYear; i > startYear - 20; i--)
{
keyboardBuilder
.AddButton(i.ToString(), i.ToString(), KeyboardButtonColor.Primary);
btnCount++;
if (btnCount % 4 == 0)
{
btnLines++;
keyboardBuilder.AddLine();
}
}
if (btnCount % 4 != 0)
{
keyboardBuilder.AddLine();
}
keyboardBuilder
.AddButton("Отменить", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder
.Build();
@params.Message = "Отлично! Теперь выберите на клавиатуре внизу или введите свой год рождения, например 1993. \n";
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
else
{
@params.Message = "Данные введены некорректно 😕 Напишите, пожалуйста, текст длиной до 50 символов.";
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в GetFIOCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
public int GetRandomId()
{
var intBytes = new byte[4];
Rng.GetBytes(intBytes);
return BitConverter.ToInt32(intBytes, 0);
}
}
}

View File

@@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class GetGenderCommand
{
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
var chatId = update.@object.message.from_id;
MessagesSendParams @params = new MessagesSendParams();
var keyboardBuilder = new KeyboardBuilder().Clear();
int i = 0;
int btnCount = 0;
int btnLines = 0;
int startYear = DateTime.Now.Year - 15;
int gender = 0;
try
{
if (update.@object.message.text.Trim().Length > 0 && update.@object.message.text.Trim().Length < 2)
{
var ids = new long[] { chatId };
string genderStr = update.@object.message.text.ToLower();
if (genderStr == "m" || genderStr == "м" || genderStr == "ж")
{
if (genderStr == "m" || genderStr == "м") gender = 1;
if (genderStr == "ж") gender = 2;
var user = db.Users.Single(usr => usr.chatId == chatId);
user.gender = gender;
user.tag = "Подписчик - Регистрация - ФИО";
db.SaveChanges();
//updTag.Parameters.AddWithValue("@tag", "Подписчик - Регистрация - ФИО");
keyboardBuilder
.AddButton("Отменить", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.Message = "Расскажите немного о себе 😉\n" + "Напишите ФИО.\n\nНапример: Иванов Иван Иванович";
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
else
{
@params.Message = "Данные введены некорректно 😕 Напишите, пожалуйста, \"М\" или \"Ж\" ";
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
else
{
@params.Message = "Данные введены некорректно 😕 Напишите, пожалуйста, \"М\" или \"Ж\" ";
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в GetFIOCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
public int GetRandomId()
{
var intBytes = new byte[4];
Rng.GetBytes(intBytes);
return BitConverter.ToInt32(intBytes, 0);
}
}
}

View File

@@ -0,0 +1,115 @@
using SvetoforVKBot.Models.Updates;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using VkNet;
using VkNet.Model.RequestParams;
using System.Security.Cryptography;
using VkNet.Model.Keyboard;
using VkNet.Model.Attachments;
using VkNet.Enums.SafetyEnums;
using System.Collections.ObjectModel;
using System.Threading;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using SvetoforVKBot.Models.Commands.LK;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class GetKorpusCommand
{
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
MessagesSendParams @params2 = new MessagesSendParams();
var chatId = update.@object.message.from_id;
Regex regex = new Regex("[^0-9]");
int i = 0;
var row = new List<MessageKeyboardButton>();
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
var keyboardBuilder = new KeyboardBuilder().Clear();
string korpus = "";
try
{
if (update.@object.message.text.Trim().ToLower().Contains("продолжить"))
korpus = "0";
else
{
if (update.@object.message.text.Trim().Length > 0)
//if (int.TryParse(update.@object.message.text.Trim(), out int korp))
{
korpus = update.@object.message.text.Trim();
//if (korp <= 24)
//else
//{
// @params.Message = "Вы некорректно ввели номер корпуса. Попробуйте, пожалуйста, ещё раз.";
// @params.UserId = chatId;
// @params.RandomId = GetRandomId();
// client.Messages.SendAsync(@params);
// return;
//}
}
else
{
@params.Message = "Вы некорректно ввели номер корпуса. Попробуйте, пожалуйста, ещё раз.";
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return;
}
}
var user = db.Users.Single(usr => usr.chatId == chatId);
user.korpus = korpus;
user.tag = "Регистрация - Активность - Вид";
db.SaveChanges();
//editUser.Parameters.AddWithValue("@tag", "Регистрация - Активность - Вид");
@params.Message = "Вы заниматесь спортом или физкультурой?\n" +
"Выберите на клавиатуре вариант, который наиболее точно описывает Ваш образ жизни.\n\n" +
"👉🏻 Если Вы профессионально занимаетесь спортом или Ваша работа связана с тяжёлым физическим трудом, выберите вариант \"Занимаюсь спортом\"\n" +
"👉🏻 Если Вы не занимаетесь спортом профессионально, но регулярно поддерживаете физическую активность (занятия физкультурой), выберите вариант \"Занимаюсь физкультурой\"\n" +
"👉🏻 Если у Вас сидячая работа или нерегулярная физическая активность (менее одного раза в неделю), выберите вариант \"Ничем не занимаюсь\".\n";
keyboardBuilder
.AddButton("Занимаюсь спортом", "selectActivityKind-1", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Занимаюсь физкультурой", "selectActivityKind-2", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Ничем не занимаюсь", "selectActivityKind-3", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Отменить", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в GetKorpusCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return;
}
return;
}
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
public int GetRandomId()
{
var intBytes = new byte[4];
Rng.GetBytes(intBytes);
return BitConverter.ToInt32(intBytes, 0);
}
}
}

View File

@@ -0,0 +1,124 @@
using SvetoforVKBot.Models.Updates;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using VkNet;
using VkNet.Model.RequestParams;
using System.Security.Cryptography;
using VkNet.Model.Keyboard;
using VkNet.Model.Attachments;
using VkNet.Enums.SafetyEnums;
using System.Collections.ObjectModel;
using System.Threading;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using SvetoforVKBot.Models.Commands.LK;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class GetPhoneCommand
{
public bool Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
MessagesSendParams @params2 = new MessagesSendParams();
var chatId = update.@object.message.from_id;
Regex regex = new Regex("[^0-9]");
int i = 0;
var row = new List<MessageKeyboardButton>();
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
var keyboardBuilder = new KeyboardBuilder().Clear();
try
{
string phone = regex.Replace(update.@object.message.text, "");
if (phone.Length == 11)
if (phone.StartsWith("8") || phone.StartsWith("7"))
{
var user = db.Users.Single(usr => usr.chatId == chatId);
var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);
if (jsPhones.Contains(phone))
{
jsPhones[jsPhones.FindIndex(p => p.Equals(phone))] = jsPhones[0];
jsPhones[0] = phone;
}
else
{
if (jsPhones.Count > 0)
{
for (i = jsPhones.Count; i > 0; i--)
{
if (i != 4)
{
if (i == jsPhones.Count)
jsPhones.Add("");
jsPhones[i] = jsPhones[i - 1];
}
}
}
else
jsPhones.Add("");
jsPhones[0] = phone;
}
user.tag = "Регистрация - Роль";
user.phone = JsonConvert.SerializeObject(jsPhones);
db.SaveChanges();
@params.Message = "Если вы обучаетесь или работаете в Вятском государственном университете, выберите подходящий вариант.\n" +
"Если Вы не из ВятГУ - выберите \"Другое\".";
keyboardBuilder
.AddButton("Студент", "selectVyatsuRole-1", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Сотрудник/Преподаватель", "selectVyatsuRole-2", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Другое", "selectVyatsuRole-3", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Отменить", "startPL", KeyboardButtonColor.Default);
}
else
@params.Message = "Контактный телефон в формате 89123456789 (11 цифр, без плюса и через \"8\" или \"7\" обязательно).";
else
@params.Message = "Контактный телефон в формате 89123456789 (11 цифр, без плюса и через \"8\" или \"7\" обязательно).";
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в GetPhoneCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return true;
}
return true;
}
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
public int GetRandomId()
{
var intBytes = new byte[4];
Rng.GetBytes(intBytes);
return BitConverter.ToInt32(intBytes, 0);
}
}
}

View File

@@ -0,0 +1,81 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using Newtonsoft.Json;
using VkNet.Enums.Filters;
using System.Text.RegularExpressions;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectAcceptPDCommand : Command
{
public override string Name => "{\"button\":\"selectAcceptPD-";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
var keyboardBuilder = new KeyboardBuilder().Clear();
Regex regex = new Regex("[^0-9]");
string voronka = "";
try
{
string[] payload = update.@object.message.payload.Split('-');
int curOption = Convert.ToInt32(regex.Replace(payload[1], ""));
switch (curOption)
{
case 0: // Согласен
var user = db.Users.Single(usr => usr.chatId == chatId);
user.agree = 1;
user.tag = "Подписчик - Регистрация - Пол";
if (user.voronka == "Старт")
{
user.voronka = "Регистрация";
}
db.SaveChanges();
keyboardBuilder
.AddButton("М", "selectGender-1", KeyboardButtonColor.Primary)
.AddButton("Ж", "selectGender-2", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Отменить", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.Message = //"1 шаг из 4. Расскажите немного о себе 😉\n" +
"Выберите на клавиатуре внизу или напишите пол в формате \"М\" или \"Ж\"";
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
break;
case 1: // Не согласен
StartCommand start = new StartCommand();
start.Execute(update, client, db);
break;
}
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectAcceptPDCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,82 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using Newtonsoft.Json;
using VkNet.Enums.Filters;
using System.Text.RegularExpressions;
using SvetoforVKBot.Models.Commands.LK;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectActivityCoefCommand : Command
{
public override string Name => "{\"button\":\"selectActivityCoef-";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
var keyboardBuilder = new KeyboardBuilder().Clear();
Regex regex = new Regex("[^0-9]");
string voronka = "";
double activityCoef = 0;
try
{
string[] payload = update.@object.message.payload.Split('-');
int activity = Convert.ToInt32(regex.Replace(payload[1], ""));
switch(activity)
{
case 1:
activityCoef = 1.2;
break;
case 2:
activityCoef = 1.375;
break;
case 3:
activityCoef = 1.55;
break;
case 4:
activityCoef = 1.725;
break;
case 5:
activityCoef = 1.9;
break;
}
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Подписчик - Регистрация - Готово";
user.voronka = "Зарегистрирован";
user.activityCoef = activityCoef;
user.reg = 1;
db.SaveChanges();
ShowLKCommand showLK = new ShowLKCommand();
showLK.Execute(update, client, db);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectActivityCoefCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,91 @@
using SvetoforVKBot.Models.Updates;
using System;
using System.Data.SqlClient;
using VkNet;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using VkNet.Enums.SafetyEnums;
using System.Text.RegularExpressions;
using System.Threading;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectActivityCommand : Command
{
public override string Name => "{\"button\":\"selectActivity-";
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
var keyboardBuilder = new KeyboardBuilder().Clear();
Regex regex = new Regex("[^0-9]");
SqlCommand editUser;
try
{
string[] payload = update.@object.message.payload.Split('-');
int stackId = Convert.ToInt32(regex.Replace(payload[1], ""));
// Тут надо дописать код, сейчас ссылка на несуществующий аттрибут в таблице
var user = db.Users.Single(usr => usr.chatId == chatId);
var userStack = new List<int>();// JsonConvert.DeserializeObject<List<int>>(rgetUserStack["activity"].ToString());
//SqlCommand getUserStack = new SqlCommand("SELECT activity FROM Users WHERE chatId = @chatId;", Con);
//getUserStack.Parameters.AddWithValue("@chatId", chatId);
//SqlDataReader rgetUserStack = getUserStack.ExecuteReader();
//rgetUserStack.Read();
//var userStack = JsonConvert.DeserializeObject<List<int>>(rgetUserStack["activity"].ToString());
//rgetUserStack.Close();
if (userStack.Contains(stackId))
{
userStack.Remove(stackId);
//SqlCommand editStack = new SqlCommand("UPDATE Users SET activity = @activity WHERE chatId = @chatId;", Con);
//editStack.Parameters.AddWithValue("@chatId", chatId);
//editStack.Parameters.AddWithValue("@activity", JsonConvert.SerializeObject(userStack));
//editStack.ExecuteNonQuery();
//ShowActivity showActivity = new ShowActivity();
//showActivity.Execute(update, client, Con);
}
else
{
userStack.Add(stackId);
//SqlCommand editStack = new SqlCommand("UPDATE Users SET activity = @activity WHERE chatId = @chatId;", Con);
//editStack.Parameters.AddWithValue("@chatId", chatId);
//editStack.Parameters.AddWithValue("@activity", JsonConvert.SerializeObject(userStack));
//editStack.ExecuteNonQuery();
//ShowActivity showActivity = new ShowActivity();
//showActivity.Execute(update, client, Con);
}
var activity = JsonConvert.SerializeObject(userStack);
//куда-то сохранить в user
db.SaveChanges();
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectActivity: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
}
}

View File

@@ -0,0 +1,103 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using Newtonsoft.Json;
using VkNet.Enums.Filters;
using System.Text.RegularExpressions;
using SvetoforVKBot.Models.Commands.LK;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectActivityKindCommand : Command
{
public override string Name => "{\"button\":\"selectActivityKind-";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
var keyboardBuilder = new KeyboardBuilder().Clear();
Regex regex = new Regex("[^0-9]");
string voronka = "";
double activityCoef = 0;
SqlCommand editUser;
try
{
string[] payload = update.@object.message.payload.Split('-');
int activityKind = Convert.ToInt32(regex.Replace(payload[1], ""));
var user = db.Users.Single(usr => usr.chatId == chatId);
switch (activityKind)
{
case 1:
case 2:
ShowSportKinds showSport = new ShowSportKinds();
showSport.Execute(update, client, db, activityKind);
return;
case 3:
activityCoef = 1.2;
if (user.reg == 0)
{
user.activityCoef = activityCoef;
user.activityKind = activityKind;
user.tag = "Регистрация - Напоминания";
db.SaveChanges();
keyboardBuilder
.AddButton("Раз в день", "selectNotifyCount-1", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Три раза в день", "selectNotifyCount-3", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Более 3х раз", "selectNotifyCount-4", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Никогда", "selectNotifyCount-0", KeyboardButtonColor.Default);
@params.Message = "Благодарим за регистрацию! Ваш личный кабинет сформирован.\n" +
"Последний вопрос: как часто Вы готовы получать напоминания от чат-бота?\n\n" +
"Вы будете получать уведомления о приёмах пищи и воды. Если Вы хотите сформировать привычку " +
"по режиму питания или употреблению достаточного количества воды, выберите вариант \"Более 3х раз\".\n" +
"Наш чат-бот не будет рассылать рекламу или спам. Только персональные уведомления и рекомендации по здоровому питанию.";
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
else
{
user.activityCoef = activityCoef;
user.activityKind = activityKind;
user.tag = "Личный кабинет - Данные";
db.SaveChanges();
SelectEditDataCommand selectEditData = new SelectEditDataCommand();
selectEditData.Execute(update, client, db);
}
return;
}
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectActivityCoefCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,124 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using Newtonsoft.Json;
using VkNet.Enums.Filters;
using VkNet.Model.Attachments;
using System.Collections.Generic;
using System.Threading;
using SvetoforVKBot.Models.Dop;
using SvetoforVKBot.Models.Commands;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectAgreementCommand : Command
{
public override string Name => "{\"button\":\"selectAgreement\"}";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
var chatId = update.@object.message.from_id;
MessagesSendParams @params = new MessagesSendParams();
var keyboardBuilder = new KeyboardBuilder().Clear();
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
List<MediaAttachment> listDoc = new List<MediaAttachment>()
{
new Document() { Id = 602601883, OwnerId = 59111081 } //59111081_600676073
};
if (user.agree == 0)
{
switch (user.child)
{
case 0:
@params.Message = "Вам уже исполнилось 18 лет? Исходя из возраста, мы сформируем для Вас подходящий документ " +
"согласия на обработку персональных данных.\n\n" +
"Нажмите кнопку на специальной клавиатуре👇";
keyboardBuilder
.AddButton("Да", "selectChildAge-2", KeyboardButtonColor.Positive)
.AddButton("Нет", "selectChildAge-1", KeyboardButtonColor.Negative)
.AddLine()
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return;
case 1:
listDoc = new List<MediaAttachment>()
{
new Document() { Id = 602601888, OwnerId = 59111081 } //59111081_600676073
};
break;
case 2:
listDoc = new List<MediaAttachment>()
{
new Document() { Id = 602601883, OwnerId = 59111081 } //59111081_600676073
};
break;
}
@params.Message = "Для продолжения, подтвердите, пожалуйста, Ваше согласие на обработку персональных данных. \n" +
"Нажмите зелёную кнопку \"Согласен\" на специальной клавиатуре👇";
keyboardBuilder
.AddButton("Согласен", "selectAcceptPD-0", KeyboardButtonColor.Positive)
.AddButton("Не согласен", "selectAcceptPD-1", KeyboardButtonColor.Negative)
.AddLine()
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.Attachments = listDoc;
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
else
{
user.tag = "Подписчик - Регистрация - Пол";
db.SaveChanges();
keyboardBuilder
.AddButton("М", "selectGender-1", KeyboardButtonColor.Primary)
.AddButton("Ж", "selectGender-2", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Отменить", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.Message = //1 шаг из 4.
"Выберите на клавиатуре внизу или напишите пол в формате \"М\" или \"Ж\"";
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectAgreementCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,60 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using Newtonsoft.Json;
using VkNet.Enums.Filters;
using VkNet.Model.Attachments;
using System.Collections.Generic;
using System.Threading;
using SvetoforVKBot.Models.Dop;
using SvetoforVKBot.Models.Commands;
using System.Text.RegularExpressions;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectChildAgeCommand : Command
{
public override string Name => "{\"button\":\"selectChildAge-";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
var chatId = update.@object.message.from_id;
MessagesSendParams @params = new MessagesSendParams();
var keyboardBuilder = new KeyboardBuilder().Clear();
Regex regex = new Regex("[^0-9]");
try
{
string[] payload = update.@object.message.payload.Split('-');
int child = Convert.ToInt32(regex.Replace(payload[1], ""));
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Подписчик - Регистрация";
user.child = child;
db.SaveChanges();
SelectAgreementCommand selectAgreement = new SelectAgreementCommand();
selectAgreement.ExecutePL(update, client, db);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectChildAgeCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,111 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using Newtonsoft.Json;
using VkNet.Enums.Filters;
using System.Text.RegularExpressions;
using SvetoforVKBot.Models.Commands.LK;
using System.Collections.Generic;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectDayCommand : Command
{
public override string Name => "{\"button\":\"selectDay-";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
var keyboardBuilder = new KeyboardBuilder().Clear();
Regex regex = new Regex("[^0-9]");
ShowSportDays showSportDays = new ShowSportDays();
//int i = 1;
try
{
string[] payload = update.@object.message.payload.Split('-');
int day = Convert.ToInt32(regex.Replace(payload[1], ""));
//int sportId = Convert.ToInt32(regex.Replace(payload[2], ""));
var user = db.Users.Single(usr => usr.chatId == chatId);
List<int> sportDays = JsonConvert.DeserializeObject<List<int>>(user.sportDays);
if (day == 0)
{
if (sportDays.Count > 0)
{
if (user.reg == 0)
{
keyboardBuilder
.AddButton("Раз в день", "selectNotifyCount-1", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Три раза в день", "selectNotifyCount-3", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Более 3х раз", "selectNotifyCount-4", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Никогда", "selectNotifyCount-0", KeyboardButtonColor.Default);
@params.Message = "Благодарим за регистрацию! Ваш личный кабинет сформирован.\n" +
"Последний вопрос: как часто Вы готовы получать напоминания от чат-бота?\n\n" +
"Вы будете получать уведомления о приёмах пищи и воды. Если Вы хотите сформировать привычку " +
"по режиму питания или употреблению достаточного количества воды, выберите вариант \"Более 3х раз\".\n" +
"Наш чат-бот не будет рассылать рекламу или спам. Только персональные уведомления и рекомендации по здоровому питанию.";
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return;
}
else
{
keyboardBuilder
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Positive);
@params.Message = "Супер! Продуктивной недели💪🏻";
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return;
}
}
else
{
showSportDays.Execute(update, client, db);
return;
}
}
if (sportDays.Contains(day))
sportDays.Remove(day);
else
sportDays.Add(day);
user.sportDays = JsonConvert.SerializeObject(sportDays);
db.SaveChanges();
showSportDays.Execute(update, client, db);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectActivityCoefCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,90 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using Newtonsoft.Json;
using VkNet.Enums.Filters;
using System.Text.RegularExpressions;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectGenderCommand : Command
{
public override string Name => "{\"button\":\"selectGender-";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
var keyboardBuilder = new KeyboardBuilder().Clear();
Regex regex = new Regex("[^0-9]");
string voronka = "";
int i = 0;
int btnCount = 0;
int btnLines = 0;
int startYear = DateTime.Now.Year - 18;
try
{
string[] payload = update.@object.message.payload.Split('-');
int gender = Convert.ToInt32(regex.Replace(payload[1], ""));
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Подписчик - Регистрация - ДР - Год";
user.gender = gender;
db.SaveChanges();
keyboardBuilder
.AddButton("Отменить", "startPL", KeyboardButtonColor.Default);
for (i = startYear; i > startYear - 20; i--)
{
keyboardBuilder
.AddButton(i.ToString(), i.ToString(), KeyboardButtonColor.Primary);
btnCount++;
if (btnCount % 4 == 0)
{
btnLines++;
keyboardBuilder.AddLine();
}
}
if (btnCount % 4 != 0)
{
keyboardBuilder.AddLine();
}
keyboardBuilder
.AddButton("Отменить", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder
.Build();
@params.Message = "Отлично! Теперь выберите на клавиатуре внизу или введите свой год рождения, например 1993. \n";
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectGenderCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,103 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using Newtonsoft.Json;
using VkNet.Enums.Filters;
using System.Text.RegularExpressions;
using SvetoforVKBot.Models.Commands.LK;
using System.Collections.Generic;
using SvetoforVKBot.Models.Commands.LK.SportsLK;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectNotifyCountCommand : Command
{
public override string Name => "{\"button\":\"selectNotifyCount-";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
var keyboardBuilder = new KeyboardBuilder().Clear();
Regex regex = new Regex("[^0-9]");
double activityCoef = 0;
try
{
string[] payload = update.@object.message.payload.Split('-');
int notifyCount = Convert.ToInt32(regex.Replace(payload[1], ""));
var user = db.Users.Single(usr => usr.chatId == chatId);
List<int> sportDays = JsonConvert.DeserializeObject<List<int>>(user.sportDays);
if (user.activityKind == 3)
activityCoef = 1.2;
else
{
if (user.activityKind == 1) //СПОРТ
{
if (sportDays.Count <= 3)
activityCoef = 1.375;
else if (sportDays.Count > 3 && sportDays.Count <= 5)
activityCoef = 1.55;
else if (sportDays.Count == 6)
activityCoef = 1.725;
else
activityCoef = 1.9;
}
else
{
if (sportDays.Count <= 3)
activityCoef = 1.375;
else if (sportDays.Count > 3 && sportDays.Count <= 5)
activityCoef = 1.55;
else if (sportDays.Count == 6)
activityCoef = 1.725;
else
activityCoef = 1.9;
}
}
user.activityCoef = activityCoef;
user.notifyCount = notifyCount;
user.reg = 1;
user.tag = "Регистрация - Готово";
user.voronka = "Зарегистрирован";
db.SaveChanges();
ShowLKCommand showLK = new ShowLKCommand();
showLK.Execute(update, client, db);
//if (activityKind == 1)
//{
// ShowSportsLKCommand showSportsLK = new ShowSportsLKCommand();
// showSportsLK.Execute(update, client, Con);
//}
//else
//{
// ShowLKCommand showLK = new ShowLKCommand();
// showLK.Execute(update, client, Con);
//}
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectNotifyCountCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,100 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using Newtonsoft.Json;
using VkNet.Enums.Filters;
using VkNet.Model.Attachments;
using System.Collections.Generic;
using System.Threading;
using SvetoforVKBot.Models.Dop;
using SvetoforVKBot.Models.Commands;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectParticipateCommand : Command
{
public override string Name => "{\"button\":\"selectParticipate\"}";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
var chatId = update.@object.message.from_id;
MessagesSendParams @params = new MessagesSendParams();
var keyboardBuilder = new KeyboardBuilder().Clear();
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
List<MediaAttachment> listDoc = new List<MediaAttachment>()
{
new Document() { Id = 602601883, OwnerId = 59111081 } //59111081_600676073
};
if (user.agree == 0)
{
switch (user.child)
{
case 0:
@params.Message = "Вам уже исполнилось 18 лет? Исходя из возраста, мы сформируем для Вас подходящий документ " +
"согласия на обработку персональных данных.\n\n" +
"Нажмите кнопку на специальной клавиатуре👇";
keyboardBuilder
.AddButton("Да", "selectChildAge-2", KeyboardButtonColor.Positive)
.AddButton("Нет", "selectChildAge-1", KeyboardButtonColor.Negative)
.AddLine()
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return;
default:
SelectAgreementCommand selectAgreement = new SelectAgreementCommand();
selectAgreement.ExecutePL(update, client, db);
return;
}
}
else
{
user.tag = "Подписчик - Регистрация - Пол";
db.SaveChanges();
keyboardBuilder
.AddButton("М", "selectGender-1", KeyboardButtonColor.Primary)
.AddButton("Ж", "selectGender-2", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Отменить", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.Message = //1 шаг из 4.
"Выберите на клавиатуре внизу или напишите пол в формате \"М\" или \"Ж\"";
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectParticipateCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Linq;
using Newtonsoft.Json;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectRegVkNameCommand : Command
{
public override string Name => "{\"button\":\"selectRegVkName\"}";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
var chatId = update.@object.message.from_id;
MessagesSendParams @params = new MessagesSendParams();
var keyboardBuilder = new KeyboardBuilder().Clear();
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Регистрация - Возраст";
user.fio = user.firstName + " " + user.lastName;
db.SaveChanges();
@params.Message = "2 шаг из 4. Напиши возраст одним числом, например, 19. \n";
keyboardBuilder
.AddButton("Отменить", "selectRegistration", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в ContinueRegCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,70 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using Newtonsoft.Json;
using VkNet.Enums.Filters;
using System.Text.RegularExpressions;
using SvetoforVKBot.Models.Commands.LK;
using System.Collections.Generic;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectSportsCommand : Command
{
public override string Name => "{\"button\":\"selectSports-";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
var keyboardBuilder = new KeyboardBuilder().Clear();
Regex regex = new Regex("[^0-9]");
//int i = 1;
try
{
string[] payload = update.@object.message.payload.Split('-');
int sportId = Convert.ToInt32(regex.Replace(payload[1], ""));
//int sportId = Convert.ToInt32(regex.Replace(payload[2], ""));
var user = db.Users.Single(usr => usr.chatId == chatId);
if (user.reg == 0)
{
user.tag = "Регистрация - Дни";
user.sportId = sportId;
db.SaveChanges();
ShowSportDays showSportDays = new ShowSportDays();
showSportDays.Execute(update, client, db);
}
else
{
user.tag = "Личный кабинет - Данные";
user.sportId = sportId;
db.SaveChanges();
SelectEditDataCommand selectEditData = new SelectEditDataCommand();
selectEditData.Execute(update, client, db);
}
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectActivityCoefCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,112 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class SelectVyatsuRoleCommand : Command
{
public override string Name => "{\"button\":\"selectVyatsuRole-";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
var chatId = update.@object.message.from_id;
MessagesSendParams @params = new MessagesSendParams();
Regex regex = new Regex("[^0-9]");
string msg = "";
var keyboardBuilder = new KeyboardBuilder().Clear();
int age = 0;
int genderCoef = 0;
double kkalResult = 0;
double kkalResultLow = 0;
double kkalResultHigh = 0;
double colorPercent = 0;
double dayCoef = 0;
double curDayKkal = 0;
SqlCommand editUser;
try
{
string[] payload = update.@object.message.payload.Split('-');
int vyatsuRole = Convert.ToInt32(regex.Replace(payload[1], ""));
var userEdit = db.Users.Single(usr => usr.chatId == chatId);
switch (vyatsuRole)
{
case 1:
@params.Message = "Перечислите корпуса, в которых проходите обучение. Например: 1, 4.";
break;
case 2:
@params.Message = "Перечислите корпуса, в которых Вы работаете. Например: 1, 4.";
break;
case 3:
userEdit.korpus = "0";
userEdit.statusId = vyatsuRole;
userEdit.tag = "Регистрация - Активность - Вид";
db.SaveChanges();
@params.Message = "Вы заниматесь спортом или физкультурой?\n" +
"Выберите на клавиатуре вариант, который наиболее точно описывает Ваш образ жизни.\n\n" +
"👉🏻 Если Вы профессионально занимаетесь спортом или Ваша работа связана с тяжёлым физическим трудом, выберите вариант \"Занимаюсь спортом\"\n" +
"👉🏻 Если Вы не занимаетесь спортом профессионально, но регулярно поддерживаете физическую активность (занятия физкультурой), выберите вариант \"Занимаюсь физкультурой\"\n" +
"👉🏻 Если у Вас сидячая работа или нерегулярная физическая активность (менее одного раза в неделю), выберите вариант \"Ничем не занимаюсь\".\n";
keyboardBuilder
.AddButton("Занимаюсь спортом", "selectActivityKind-1", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Занимаюсь физкультурой", "selectActivityKind-2", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Ничем не занимаюсь", "selectActivityKind-3", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Отменить", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return;
}
userEdit.statusId = vyatsuRole;
userEdit.tag = "Регистрация - Корпус";
db.SaveChanges();
//@params.Message = "Напишите номер корпуса, в котором проходите обучение/работаете. Например: 1.";
keyboardBuilder
.AddButton("Отменить", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectCalcCcalResultCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,111 @@
using Newtonsoft.Json;
using SvetoforVKBot.Models.Updates;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Attachments;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class ShowActivity
{
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, int expert)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
int i = 0;
int index = 0;
Regex regex = new Regex("[^0-9]");
string backPL = "startPL";
var keyboardBuilder = new KeyboardBuilder().Clear();
List<StackObject> techStack = new List<StackObject>();
string msg = "";
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
if (expert == 0)
{
msg = "На какое направление ты хочешь подать свой проект?\n\n";
user.tag = "Проектный офис - Направление";
}
else
{
msg = "В какой области/направлении ты готов выступить экспертом?\n\n";
user.tag = "Проектный офис - Эксепрт - Направление";
}
db.SaveChanges();
//SqlCommand getTechStack = new SqlCommand("SELECT * FROM Activity;", Con);
//SqlDataReader rgetTechStack = getTechStack.ExecuteReader();
//while (rgetTechStack.Read())
//{
// techStack.Add(new StackObject()
// {
// id = Convert.ToInt32(rgetTechStack["id"]),
// name = rgetTechStack["name"].ToString(),
// description = rgetTechStack["description"].ToString(),
// });
//}
//rgetTechStack.Close();
int btnCount = 0;
foreach (var s in techStack)
{
keyboardBuilder
.AddButton(s.name, "selectPOTheme-" + s.id + "-" + expert, KeyboardButtonColor.Primary);
btnCount++;
msg += btnCount + ". " + s.description + "\n";
if (btnCount % 2 == 0)
keyboardBuilder.AddLine();
if (btnCount == 14) break;
}
if (btnCount % 2 != 0)
keyboardBuilder.AddLine();
msg += "\nВыбери на клавиатуре👇";
keyboardBuilder
.AddButton("⬅Назад", "startPL", KeyboardButtonColor.Default);
@params.Message = msg;
@params.UserId = chatId;
@params.Keyboard = keyboardBuilder.Build();
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в ShowActivity: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
private int GetRandomId()
{
var intBytes = new byte[4];
Rng.GetBytes(intBytes);
return BitConverter.ToInt32(intBytes, 0);
}
}
}

View File

@@ -0,0 +1,100 @@
using Newtonsoft.Json;
using SvetoforVKBot.Models.Updates;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Attachments;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class ShowSportDays
{
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
var keyboardBuilder = new KeyboardBuilder().Clear();
List<SportObject> sports = new List<SportObject>();
var kbColor = KeyboardButtonColor.Primary;
try
{
Dictionary<int, string> days = new Dictionary<int, string>(7);
days.Add(1, "Пн");
days.Add(2, "Вт");
days.Add(3, "Ср");
days.Add(4, "Чт");
days.Add(5, "Пт");
days.Add(6, "Сб");
days.Add(7, "Вс");
var user = db.Users.Single(usr => usr.chatId == chatId);
List<int> sportDays = JsonConvert.DeserializeObject<List<int>>(user.sportDays);
if (user.activityKind == 1)
@params.Message = "Отметьте все дни, в которые Вы занимаетесь спортом на текущей неделе👇\n";
else
@params.Message = "Отметьте все дни, в которые Вы занимаетесь физкультурой на текущей неделе👇\n";
for (int i = 1; i <= 7; i++)
{
if (sportDays.Contains(i))
kbColor = KeyboardButtonColor.Positive;
else
kbColor = KeyboardButtonColor.Primary;
keyboardBuilder
.AddButton(days[i], "selectDay-" + i, kbColor);
if (i % 2 == 0)
keyboardBuilder.AddLine();
}
if (sportDays.Count > 0)
keyboardBuilder
.AddButton("Готово", "selectDay-0", KeyboardButtonColor.Positive);
else
keyboardBuilder
.AddButton("Готово", "selectDay-0", KeyboardButtonColor.Negative);
keyboardBuilder
.AddLine()
.AddButton("В начало", "startPL", KeyboardButtonColor.Default);
@params.UserId = chatId;
@params.Keyboard = keyboardBuilder.Build();
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в ShowSportDays: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
private int GetRandomId()
{
var intBytes = new byte[4];
Rng.GetBytes(intBytes);
return BitConverter.ToInt32(intBytes, 0);
}
}
}

View File

@@ -0,0 +1,113 @@
using Newtonsoft.Json;
using SvetoforVKBot.Models.Updates;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Attachments;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.Registration
{
public class ShowSportKinds
{
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, int kind)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
int i = 0;
int index = 0;
Regex regex = new Regex("[^0-9]");
string backPL = "startPL";
var keyboardBuilder = new KeyboardBuilder().Clear();
List<SportObject> sports = new List<SportObject>();
string msg = "";
try
{
switch (kind)
{
case 1:
msg = "Выберите основной вид спорта. Нажмите кнопку👇\n";
break;
case 2:
msg = "Выберите основной вид активности. Нажмите кнопку👇\n";
break;
default:
return;
}
var user = db.Users.Single(usr => usr.chatId == chatId);
user.activityKind = kind;
user.tag = "Регистрация - Вид спорта";
db.SaveChanges();
sports = db.SportKinds.Where(s => s.kind == kind).ToList().
ConvertAll<SportObject>(s => new SportObject()
{
id = s.id,
name = s.name,
btnName = s.btnName,
kind = s.kind
}) ;
int btnCount = 0;
foreach (var s in sports)
{
keyboardBuilder
.AddButton(s.btnName, "selectSports-" + s.id + "-" + kind, KeyboardButtonColor.Primary);
btnCount++;
//msg += btnCount + ". " + s.description + "\n";
if (btnCount % 2 == 0)
keyboardBuilder.AddLine();
if (btnCount == 14) break;
}
if (btnCount % 2 != 0)
keyboardBuilder.AddLine();
//msg += "\nВыбери на клавиатуре👇";
keyboardBuilder
.AddButton("Отменить", "startPL", KeyboardButtonColor.Default);
@params.Message = msg;
@params.UserId = chatId;
@params.Keyboard = keyboardBuilder.Build();
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в ShowSportKinds: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
private int GetRandomId()
{
var intBytes = new byte[4];
Rng.GetBytes(intBytes);
return BitConverter.ToInt32(intBytes, 0);
}
}
}