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

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,189 @@
using SvetoforVKBot.Models.Updates;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using VkNet.Model;
using System.Collections.ObjectModel;
using VkNet.Model.Attachments;
namespace SvetoforVKBot.Models.Commands.Admin
{
public class SelectAdminCommand : Command
{
private const int ADMIN1 = 59111081;
private const int ADMIN2 = 369217524;
private const int ADMIN3 = 10160301;
public override string Name => "{\"button\":\"selectAdminMenu\"}";
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;
SalesFunnel salesFunnel = new SalesFunnel();
//var keyboardBuilder = new KeyboardBuilder().Clear();
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
try
{
if (update.@object.message.from_id == ADMIN1 || update.@object.message.from_id == ADMIN2 || update.@object.message.from_id == ADMIN3 || update.@object.message.from_id == 178385801)
{
//List<MediaAttachment> listVideo = new List<MediaAttachment>()
//{
// new VkNet.Model.Attachments.Video() { Id = 456239343, OwnerId = 59111081, AccessKey = "5530abb97b1da2077b" }
//};
//@params.Attachments = listVideo;
Uri URL = new Uri("https://docs.google.com/spreadsheets/d/1nWHvWufxDy6g2ZJtqd4K8MDM6Gh8OHWasRGXIyqbT2k/");
Uri URLSHEET_ALL = new Uri("https://docs.google.com/spreadsheets/d/1jr68NfIrlz2bVsN-HZg0Kv2sSJ82J5G-EbtXl-YMK44/");
Uri URLDOC = new Uri("https://docs.google.com/document/d/1DQcBuS9g6KYphJZRdcc-tdqgQ_oSvV2PsZt3U-pO_oo/");
Uri URLDIALOGS = new Uri("https://vk.com/gim194717824");
/*
if (admin == 1)
{
keyboardBuilder
.AddButton("📅Каталог мероприятий", "selectEvents-0-1", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("➕Добавить мероприятие", "Добавить мероприятие", KeyboardButtonColor.Default)
.AddLine()
.AddButton("Создать рассылку", "Создать рассылку", KeyboardButtonColor.Default)
.AddLine()
.AddButton("Статистика", "Статистика", KeyboardButtonColor.Default)
.AddButton("Обращения", "Обращения", KeyboardButtonColor.Default);
@params.Message = "Режим администратора. Выберите интересующее действие👇🏻";
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return;
}
*/
//keyboardBuilder.AddButton("Открыть таблицу", URL, "open_link");
var row = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){
Type = KeyboardButtonActionType.OpenLink,
Link = URL,
Label = "Заявки на консультацию",
Payload = "{\"button\":\"selectOpenSheet\"}"
},
}
};
listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row));
var row1 = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){
Type = KeyboardButtonActionType.OpenLink,
Link = URLSHEET_ALL,
Label = "Все участники",
Payload = "{\"button\":\"selectOpenSheet\"}"
},
}
};
listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row1));
row1 = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){
Type = KeyboardButtonActionType.OpenLink,
Link = URLDIALOGS,
Label = "Перейти в диалоги",
Payload = "{\"button\":\"selectOpenSheet\"}"
},
}
};
listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row1));
row1 = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){
Type = KeyboardButtonActionType.OpenLink,
Link = URLDOC,
Label = "Инструкция",
Payload = "{\"button\":\"selectOpenSheet\"}"
},
}
};
listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row1));
var row2 = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){
Label = "Статистика",
Payload = "{\"button\":\"selectStatistic\"}",
Type = KeyboardButtonActionType.Text},
Color = KeyboardButtonColor.Primary
}
};
listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row2));
//var row3 = new List<MessageKeyboardButton>()
//{
// new MessageKeyboardButton() {
// Action = new MessageKeyboardButtonAction(){
// Label = "Личный кабинет специалиста",
// Payload = "{\"button\":\"selectExpertLK\"}",
// Type = KeyboardButtonActionType.Text},
// Color = KeyboardButtonColor.Primary
// }
//};
//listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row3));
var row4 = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){
Label = "В начало",
Payload = "{\"button\":\"startPL\"}",
Type = KeyboardButtonActionType.Text},
Color = KeyboardButtonColor.Default
}
};
listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row4));
var buttons = new ReadOnlyCollection<ReadOnlyCollection<MessageKeyboardButton>>(listButtons);
var keyboard = new MessageKeyboard()
{
Buttons = buttons,
OneTime = false
};
//@params.Attachments = listVideo;
@params.Keyboard = keyboard;
@params.UserId = chatId;
@params.Message = "✅ Вы перешли в панель администратора. Выберите интересующее действие";
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectAdminCommand: " + 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.Collections.Generic;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Threading;
using Newtonsoft.Json;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.Admin
{
public class SelectGetPhotoCommand : Command
{
public override string Name => "/getphoto";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
string str = "";
try
{
//string[] payload = update.@object.message.text.Split('-');
string response = "";
if (chatId != 59111081) return;
foreach (var att in update.@object.message.attachments)
{
switch (att.type)
{
case "photo":
var usPhoto = client.Photo.GetMessagesUploadServer(peerId: 0);
var strArray = att.photo.sizes[att.photo.sizes.Count - 1].url.Split('.');
response = UploadFile(
serverUrl: usPhoto.UploadUrl,
file: att.photo.sizes[att.photo.sizes.Count - 1].url,
fileExtension: strArray[strArray.Length - 1]).Result;
foreach (var a in client.Photo.SaveMessagesPhoto(response))
{
str = "{\"id\": " + a.Id +
", \"owner_id\": " + a.OwnerId +
", \"access_key\": \"" + a.AccessKey + "\"}";
}
break;
case "video":
str = "{\"id\": " + att.video.id +
", \"owner_id\": " + att.video.owner_id +
", \"access_key\": \"" + att.video.access_key + "\"}";
break;
}
}
@params.Message = str;
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectGetPhotoCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
}
}

View File

@@ -0,0 +1,114 @@
using SvetoforVKBot.Models.Updates;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.Admin
{
public class SelectStatisticCommand : Command
{
private const int ADMIN1 = 59111081;
private const int ADMIN2 = 10160301;
private const int ADMIN3 = 369217524;
private const int ADMIN4 = 178385801;
//chatId == 59111081 || chatId == 10160301 || chatId == 369217524 || chatId == 178385801
public override string Name => "{\"button\":\"selectStatistic\"}";
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;
string msg = "";
double sumOrders = 0;
DateTime dt;
DateTime dt1;
DateTime dt2;
List<UserStats> userStats = new List<UserStats>();
List<UserStats> userStats1 = new List<UserStats>();
SalesFunnel salesFunnel = new SalesFunnel();
try
{
if (update.@object.message.from_id == ADMIN1 || update.@object.message.from_id == ADMIN2 || update.@object.message.from_id == ADMIN3 || update.@object.message.from_id == ADMIN4)
{
userStats = db.Users.ToList().ConvertAll<UserStats>(x => new UserStats {
chatId = x.chatId,
sourses = JsonConvert.DeserializeObject<Sourses>(x.sourse),
voronka = x.voronka,
});
/*SqlCommand getUsers = new SqlCommand("SELECT chatId, sourse, voronka FROM Users;", Con);
SqlDataReader rgetUsers = getUsers.ExecuteReader();
while (rgetUsers.Read())
userStats.Add(new UserStats()
{
chatId = Convert.ToInt32(rgetUsers["chatId"]),
sourses = JsonConvert.DeserializeObject<Sourses>(rgetUsers["sourse"].ToString()),
voronka = rgetUsers["voronka"].ToString(),
});
rgetUsers.Close();*/
msg += "📊 Статистика \n" +
"ВСЕГО: сег вч нед мес all\n";
foreach (var st in salesFunnel.stages)
{
dt = DateTime.Now;
dt2 = DateTime.Now;
msg += st + ": " + userStats.FindAll(u => u.voronka.Equals(st) && u.sourses.sourses.Count > 0 &&
u.sourses.sourses[0].dateTime.Date.Equals(dt.Date)).Count;
dt = dt.AddDays(-1);
msg += "__" + userStats.FindAll(u => u.voronka.Equals(st) && u.sourses.sourses.Count > 0 &&
u.sourses.sourses[0].dateTime.Date.Equals(dt.Date)).Count;
dt2 = dt2.AddDays(-7);
msg += "__" + userStats.FindAll(u => u.voronka.Equals(st) && u.sourses.sourses.Count > 0 &&
u.sourses.sourses[0].dateTime.Date.Equals(dt2.Date)).Count;
dt2 = dt2.AddDays(7);
dt2 = dt2.AddMonths(-1);
msg += "__" + userStats.FindAll(u => u.voronka.Equals(st) && u.sourses.sourses.Count > 0 &&
u.sourses.sourses[0].dateTime.Date.Equals(dt2.Date)).Count;
dt2 = dt2.AddMonths(1);
msg += "__" + userStats.FindAll(u => u.voronka.Equals(st)).Count;
msg += "\n";
}
msg += "Всего пользователей: " + userStats.Count + "\n";
msg += "\n";
@params.UserId = chatId;
@params.Message = msg;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectStatisticCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,220 @@
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.Admin
{
public class SelectTestNotifyCommand : Command
{
public override string Name => "/test";
public override 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();
List<UserObject> users = new List<UserObject>();
List<int> chatIds = new List<int>();
string name = "";
int age = 0;
int genderCoef = 0;
double kkalResult = 0;
double colorPercent = 0;
double dayCoef = 0;
double curDayKkal = 0;
double kkalResultLow = 0;
double kkalResultHigh = 0;
try
{
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
tracks.Add(1, "Оптимизация питания");
tracks.Add(2, "Снижение жировой массы");
tracks.Add(3, "Увеличение мышечной массы");
tracks.Add(4, "Персональный режим");
//-- Вот этот запрос лучше сработает на стороне
db.Database.ExecuteSqlCommand("UPDATE Users SET choosenProducts = @choosenProducts, cart = @cart;",
new object[] {
new SqlParameter("@choosenProducts", "[]"),
new SqlParameter("@cart", "{\"orders\":[]}")
});
//--
var user = db.Users.Single(usr => usr.chatId == 59111081);
int id = user.id;
string fio = user.fio;
var birthday = user.birthday;
var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);
int choosenTrack = user.track;
int height = user.height;
int weight = user.weight;
int gender = user.gender; // 1 - М / 2 - Ж
var activityCoef = user.activityCoef;
//--
if ((DateTime.Now.Month >= birthday.Month) && (DateTime.Now.Day >= birthday.Day))
age = DateTime.Now.Year - birthday.Year;
else
age = DateTime.Now.Year - birthday.Year - 1;
#region ccalCalculator
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, "Воскресенье");
Dictionary<int, string> gend = new Dictionary<int, string>(3);
gend.Add(0, "Мужской");
gend.Add(1, "Мужской");
gend.Add(2, "Женский");
int curDay = (int)DateTime.Now.DayOfWeek;
if (curDay == 0) curDay = 7;
int nextDay = curDay + 1;
if (nextDay == 8)
nextDay = 1;
//if (weight == 0 || height == 0)
//{
// keyboardBuilder
// .AddButton("📝Редактировать данные", "selectEditData-0", KeyboardButtonColor.Primary)
// .AddLine()
// .AddButton("Назад", "startPL", KeyboardButtonColor.Default);
// @params.Message = "Не хватает данных о росте/весе.\n" +
// "Нажмите \"📝Редактировать данные\" и заполните показатели.";
// @params.Keyboard = keyboardBuilder.Build();
// @params.UserId = chatId;
// @params.RandomId = GetRandomId();
// client.Messages.SendAsync(@params);
// return;
//}
if (gender == 1)
{
genderCoef = 5;
}
else
{
genderCoef = -161;
}
switch (choosenTrack)
{
case 1: //не изменяя веса
colorPercent = 1;
break;
case 2:
colorPercent = 0.75; //1 - 15%
break;
case 3:
colorPercent = 1.2; //1 - 15%
break;
default:
colorPercent = 1;
break;
}
for (int i = 1; i <= 7; i++)
{
switch (i)
{
case 2:
dayCoef = 0.8;
break;
case 3:
dayCoef = 1.2;
break;
case 5:
dayCoef = 0.9;
break;
case 6:
dayCoef = 1.1;
break;
default:
dayCoef = 1;
break;
}
kkalResult = Math.Round((((10 * weight) + (6.25 * height) - (5 * age) + genderCoef) * activityCoef) * colorPercent * dayCoef);
kkalResultHigh = Math.Round(kkalResult * 1.2);
kkalResultLow = Math.Round(kkalResult * 0.9);
//if (i == nextDay)
if (i == curDay)
{
curDayKkal = kkalResult;
}
}
#endregion ccalCalculator
//-- неожиданно пришлось преобразовывать типы данных к инту от double)
var curChatIdUser = db.Users.Single(usr => usr.chatId == chatId);
curChatIdUser.kkal = Convert.ToInt32(curDayKkal);
db.SaveChanges();
//@params.Message = "🌙Добрый вечер!\n" +
// $"Ваша норма калорий на завтра: {Math.Round(curDayKkal * 0.9)} - {Math.Round(curDayKkal * 1.2)}\n" +
// "Мы подготовили для Вас блюда👇🏻";
@params.Message = "☀Доброе утро!\n" +
$"Ваша норма калорий на сегодня: {Math.Round(curDayKkal * 0.9)} - {Math.Round(curDayKkal * 1.2)}\n" +
"Мы подготовили для Вас блюда👇🏻\n\n" +
"Меню также доступно в Личном кабинете в разделе \"Дневной рацион\"";
keyboardBuilder
.AddButton($"Завтрак (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-1-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
.AddLine()
.AddButton($"Обед (до {Math.Round(curDayKkal * 1.2 * 0.4)} ккал)", "selectPersonalMenu-2-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
.AddLine()
.AddButton($"Перекус (до {Math.Round(curDayKkal * 1.2 * 0.1)} ккал)", "selectPersonalMenu-3-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
.AddLine()
.AddButton($"Ужин (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-4-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default)
.SetInline();
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = 59111081; //10160301;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectTestNotifyCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
}
}

View File

@@ -0,0 +1,69 @@
using SvetoforVKBot.Models.Updates;
using System;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using VkNet;
namespace SvetoforVKBot.Models.Commands
{
public abstract class Command
{
public abstract string Name { get; }
public abstract void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db);
public abstract void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db);
public bool StartsWith(string command)
{
return command.StartsWith(this.Name);
}
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
public int GetRandomId()
{
var intBytes = new byte[4];
Rng.GetBytes(intBytes);
return BitConverter.ToInt32(intBytes, 0);
}
public async Task<string> UploadFile(string serverUrl, string file, string fileExtension)
{
// Получение массива байтов из файла
var data = GetBytesNet(file);
// Создание запроса на загрузку файла на сервер
using (var client = new HttpClient())
{
var requestContent = new MultipartFormDataContent();
var content = new ByteArrayContent(data);
content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
requestContent.Add(content, "file", $"file.{fileExtension}");
var response = client.PostAsync(serverUrl, requestContent).Result;
return Encoding.Default.GetString(await response.Content.ReadAsByteArrayAsync());
}
}
private byte[] GetBytesNet(string fileUrl)
{
using (var webClient = new WebClient())
{
return webClient.DownloadData(fileUrl);
}
}
private byte[] GetBytesLocal(string filePath)
{
return File.ReadAllBytes(filePath);
}
}
}

View File

@@ -0,0 +1,90 @@
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.ExpertLK
{
public class SelectExpertLKCommand : Command
{
public override string Name => "{\"button\":\"selectExpertLK\"}";
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();
List<UserObject> users = new List<UserObject>();
List<int> chatIds = new List<int>();
try
{
@params.Message = "Личный кабинет специалиста.\n";
//вот это
chatIds = db.PersonalConsultations.Where(c => c.chatId == chatId && c.state == 1)?
.ToList().ConvertAll<int>(el => el.chatId);
//вместо этого
//SqlCommand getCons = new SqlCommand("SELECT * FROM PersonalConsultation WHERE chatId = @chatId AND state = 1;", Con);
//getCons.Parameters.AddWithValue("@chatId", chatId);
//SqlDataReader rgetCons = getCons.ExecuteReader();
//if (rgetCons.HasRows)
//{
// while (rgetCons.Read())
// chatIds.Add(Convert.ToInt32(rgetCons["chatId"]));
// rgetCons.Close();
//}
//else
// rgetCons.Close();
if (chatIds.Count > 0)
{
keyboardBuilder
.AddButton("Участники: " + chatIds.Count.ToString(), "selectParticipants", KeyboardButtonColor.Positive)
.AddButton("Вопросы", "selectExQuestions", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Назад", "selectAdminMenu", KeyboardButtonColor.Default);
}
else
{
keyboardBuilder
.AddButton("Участники", "selectExpertLK", KeyboardButtonColor.Primary)
.AddButton("Вопросы", "selectExQuestions", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Назад", "selectAdminMenu", KeyboardButtonColor.Default);
}
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectExpertLKCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,72 @@
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.ExpertLK
{
public class SelectParticipantInfoCommand : Command
{
public override string Name => "{\"button\":\"selectParticipantInfo-";
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();
List<UserObject> users = new List<UserObject>();
List<int> chatIds = new List<int>();
string name = "";
Regex regex = new Regex("[^0-9]");
try
{
string[] payload = update.@object.message.payload.Split('-');
int userId = Convert.ToInt32(regex.Replace(payload[1], ""));
//@params.Message = "Выберите участника.\n";
var user = db.Users.Single(usr => usr.id == userId);
int uChatId = Convert.ToInt32(user.chatId);
string fio = user.fio;
var birthday = user.birthday;
var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);
@params.Message = "Участник:\n\n" +
fio + "\n" +
"Дата рождения: " + birthday.ToShortDateString() + "\n" +
"Телефон: " + jsPhones[0];
keyboardBuilder
.AddButton("Вкл. персональный режим", "selectPersonalPlan-" + userId, KeyboardButtonColor.Positive)
.AddLine()
.AddButton("Назад", "selectExpertLK", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectParticipantInfoCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,116 @@
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.ExpertLK
{
public class SelectParticipantsCommand : Command
{
public override string Name => "{\"button\":\"selectParticipants\"}";
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();
List<UserObject> users = new List<UserObject>();
List<int> chatIds = new List<int>();
string name = "";
try
{
@params.Message = "Выберите участника.\n";
//SqlCommand getCons = new SqlCommand("SELECT * FROM PersonalConsultation WHERE chatId = @chatId;", Con);
//getCons.Parameters.AddWithValue("@chatId", chatId);
//SqlDataReader rgetCons = getCons.ExecuteReader();
//if (rgetCons.HasRows)
//{
// while (rgetCons.Read())
// chatIds.Add(Convert.ToInt32(rgetCons["chatId"]));
// rgetCons.Close();
//}
//else
// rgetCons.Close();
//if (chatIds.Count > 0)
//{
// foreach (var c in chatIds)
// {
// SqlCommand getUser = new SqlCommand("SELECT * FROM Users WHERE chatId = @chatId;", Con);
// getUser.Parameters.AddWithValue("@chatId", c);
// SqlDataReader rgetUser = getUser.ExecuteReader();
// while (rgetUser.Read())
// users.Add(new UserObject()
// {
// id = Convert.ToInt32(rgetUser["id"]),
// chatId = Convert.ToInt32(rgetUser["chatId"]),
// fio = rgetUser["fio"].ToString(),
// birthday = DateTime.Parse(rgetUser["birthday"].ToString()),
// });
// rgetUser.Close();
// }
// int btnRow = 0;
// foreach (var u in users)
// {
// if (u.fio.Length >= 36)
// name = u.fio.Substring(0, 35) + "...";
// else
// name = u.fio;
// keyboardBuilder
// .AddButton(name, "selectParticipantInfo-"+ u.id, KeyboardButtonColor.Primary)
// .AddLine();
// btnRow++;
// if (btnRow == 8)
// break;
// }
// keyboardBuilder
// .AddButton("Назад", "selectExpertLK", KeyboardButtonColor.Default);
//}
//else
//{
// keyboardBuilder
// .AddButton("Назад", "selectExpertLK", KeyboardButtonColor.Default);
//}
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectParticipantsCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,84 @@
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.ExpertLK
{
public class SelectUpPersonalPlanCommand : Command
{
public override string Name => "{\"button\":\"selectPersonalPlan-";
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();
List<UserObject> users = new List<UserObject>();
List<int> chatIds = new List<int>();
string name = "";
Regex regex = new Regex("[^0-9]");
try
{
string[] payload = update.@object.message.payload.Split('-');
int userId = Convert.ToInt32(regex.Replace(payload[1], ""));
//@params.Message = "Выберите участника.\n";
var user = db.Users.Single(usr => usr.id == userId);
int uChatId = user.chatId;
string fio = user.fio;
user.personal = 1;
db.Entry(db.PersonalConsultations.Where(el => el.chatId == uChatId)).Property("state").CurrentValue = 2;
db.SaveChanges();
//SqlCommand updTag = new SqlCommand("UPDATE Users SET personal = @personal WHERE chatId = @chatId;", Con);
//updTag.Parameters.AddWithValue("@chatId", uChatId);
//updTag.Parameters.AddWithValue("@personal", 1);
//updTag.ExecuteNonQuery();
//SqlCommand updState = new SqlCommand("UPDATE PersonalConsultation SET state = @state WHERE chatId = @chatId;", Con);
//updState.Parameters.AddWithValue("@chatId", uChatId);
//updState.Parameters.AddWithValue("@state", 2);
//updState.ExecuteNonQuery();
@params.Message = "✅Персональный режим для участника " + fio + " включен";
keyboardBuilder
//.AddButton("Вкл. персональный режим", "selectPersonalPlan-", KeyboardButtonColor.Positive)
//.AddLine()
.AddButton("Назад", "selectExpertLK", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectUpPersonalPlanCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,78 @@
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.Linq;
using SvetoforVKBot.App_Start;
using System.Configuration;
namespace SvetoforVKBot.Models.Dop
{
public class GetAskQuestionsCommand
{
private const int MODER = 59111081; //35688505; //59111081
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;
var keyboardBuilder = new KeyboardBuilder().Clear();
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Задал вопрос";
db.SaveChanges();
keyboardBuilder
.AddButton("В начало", "startPL", KeyboardButtonColor.Positive);
@params.Keyboard = keyboardBuilder.Build();
@params.Message = "Вопрос отправлен 📩 \n" +
"✅Ответим в течение часа";
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.Send(@params);
Thread.Sleep(1000);
@params2.Message = "❓Вопрос. \nСсылка на диалог: " + ((WebConfiguration)ConfigurationManager.GetSection("VKApi")).GroupDialogsLink + chatId;
List<long> listFrwMsg = new List<long>() { update.@object.message.id };
@params2.UserId = MODER;
@params2.ForwardMessages = listFrwMsg;
@params2.RandomId = GetRandomId();
client.Messages.Send(@params2);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в GetAskQuestionsCommand: " + 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,118 @@
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.Enums.SafetyEnums;
using System.Threading;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using System.Linq;
namespace SvetoforVKBot.Models.Dop
{
public class GetPhoneRecallMeCommand
{
private const int MODER = 59111081;
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 keyboardBuilder = new KeyboardBuilder().Clear();
try
{
string phone = regex.Replace(update.@object.message.text, "");
if (phone.Length == 11)
if (phone.StartsWith("8"))
{
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.phone = JsonConvert.SerializeObject(jsPhones);
user.tag = "Заказ обратного звонка";
db.SaveChanges();
keyboardBuilder
.AddButton("🏠 В начало", "startPL", KeyboardButtonColor.Positive);
@params.Keyboard = keyboardBuilder.Build();
@params.Message = "✅Спасибо за заявку! \n" +
"\n" +
"Менеджер перезвонит Вам в ближайшее время и ответит на Ваши вопросы.";
Thread.Sleep(1000);
@params2.Message = "🎉Заказ обратного звонка. \n";
List<long> listFrwMsg = new List<long>() { update.@object.message.id };
@params2.UserId = MODER;
@params2.ForwardMessages = listFrwMsg;
@params2.RandomId = GetRandomId();
client.Messages.Send(@params2);
}
else
@params.Message = "Контактный телефон в формате 89123456789 (11 цифр, без плюса и через \"8\" обязательно).";
else
@params.Message = "Контактный телефон в формате 89123456789 (11 цифр, без плюса и через \"8\" обязательно).";
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в GetPhoneRecallMeCommand: " + 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,171 @@
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.LK.Calculators
{
public class SelectCalcCcalResultCommand : Command
{
public override string Name => "{\"button\":\"selectCalcCcalResult-";
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;
try
{
string[] payload = update.@object.message.payload.Split('-');
int curColor = Convert.ToInt32(regex.Replace(payload[1], ""));
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, "Воскресенье");
int curDay = (int)DateTime.Now.DayOfWeek;
if (curDay == 0) curDay = 7;
var user = db.Users.Single(usr => usr.chatId == chatId);
List<int> sportDays = JsonConvert.DeserializeObject<List<int>>(user.sportDays);
string cons = "✅Прошёл консультацию";
if ((DateTime.Now.Month >= user.birthday.Month) && (DateTime.Now.Day >= user.birthday.Day))
age = DateTime.Now.Year - user.birthday.Year;
else
age = DateTime.Now.Year - user.birthday.Year - 1;
if (user.weight == 0 || user.height == 0)
{
keyboardBuilder
.AddButton("📝Редактировать данные", "selectEditData-0", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
@params.Message = "Для подсчёта калорий не хватает данных о росте/весе.\n" +
"Нажмите \"📝Редактировать данные\" и заполните показатели.";
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return;
}
if (user.gender == 1)
{
genderCoef = 5;
//cons = "✅Прошёл консультацию";
}
else
{
genderCoef = -161;
//cons = "✅Прошла консультацию";
}
switch (user.track)
{
case 1: //не изменяя веса
colorPercent = 1;
break;
case 2:
colorPercent = 0.75; //1 - 15%
break;
case 3:
colorPercent = 1.2; //1 - 15%
break;
default:
colorPercent = 1;
break;
}
@params.Message = "Ваш результат:\n\n";
for (int i = 1; i <= 7; i++)
{
switch (i)
{
case 2:
dayCoef = 0.8;
break;
case 3:
dayCoef = 1.2;
break;
case 5:
dayCoef = 0.9;
break;
case 6:
dayCoef = 1.1;
break;
default:
dayCoef = 1;
break;
}
kkalResult = Math.Round((((10 * user.weight) + (6.25 * user.height) - (5 * age) + genderCoef) * user.activityCoef) * colorPercent * dayCoef);
kkalResultHigh = Math.Round(kkalResult * 1.2);
kkalResultLow = Math.Round(kkalResult * 0.9);
if (i == curDay)
{
@params.Message += $"⭐ {days[i]}: {kkalResultLow}-{kkalResultHigh} ккал\n";
curDayKkal = kkalResult;
}
else
@params.Message += $"{days[i]}: {kkalResultLow}-{kkalResultHigh} ккал\n";
}
//kkalResult = Math.Round((((10 * weight) + (6.25 * height) - (5 * age) + genderCoef) * activityCoef) * colorPercent);
keyboardBuilder.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
user.kkal = Convert.ToInt32(curDayKkal);
db.SaveChanges();
@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,55 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.LK.Calculators
{
public class SelectCalculatorCcalCommand : Command
{
public override string Name => "{\"button\":\"selectCalculatorCcal\"}";
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
{
@params.Message = "🚦Выберите на клавиатуре комфортный для Вас режим сохранения/потери веса.\n";
keyboardBuilder
.AddButton("🟥Не изменяя вес", "selectCalcCcalResult-1", KeyboardButtonColor.Primary) //К
.AddLine()
.AddButton("🟨Снижение веса", "selectCalcCcalResult-2", KeyboardButtonColor.Primary) //Ж
.AddLine()
.AddButton("🟩Быстрое снижение веса", "selectCalcCcalResult-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 = "Ошибка в SelectCalculatorCcalCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,67 @@
using System;
using System.Data.SqlClient;
using System.Linq;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.LK.Calculators
{
public class SelectIdealWeightCommand : Command
{
public override string Name => "{\"button\":\"selectIdealWeight\"}";
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();
double indexMT = 23;
double indexMTLow = 18.5;
double indexMTHigh = 25;
string IMT = "";
double idealWeight = 0;
double normWeightLow = 0;
double normWeightHigh = 0;
int age = 0;
try
{
Data.Users user = db.Users.Single(usr => usr.chatId == chatId);
age = DateTime.Today.Year - user.birthday.Year;
idealWeight = Math.Round(indexMT * user.height / 100.0 * user.height / 100.0, 1);
normWeightLow = Math.Round(indexMTLow * user.height / 100.0 * user.height / 100.0, 1);
normWeightHigh = Math.Round(indexMTHigh * user.height / 100.0 * user.height / 100.0, 1);
//indexMT = Math.Round(weight / (double)(height / 100.0 * height / 100.0), 1);
@params.Message = "⭐Ваш идеальный вес: " + idealWeight + " кг.\n" +
"✅Диапазон нормального веса: " + normWeightLow + " - " + normWeightHigh + " кг.\n\n" +
"Идеальный для здоровья вес рассчитывается, исходя из ИМТ равного 23.";
keyboardBuilder
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectIdealWeightCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,163 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Threading;
using Newtonsoft.Json;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Model.RequestParams;
using VkNet.Model.Keyboard;
using VkNet.Enums.SafetyEnums;
using SvetoforVKBot.Models.Commands.LK.Menu;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.LK.Cart
{
public class SelectAddToCartCommand : Command
{
public override string Name => "{\"button\":\"selectAddToCart-";
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;
string msg = "";
double sum = 0;
string backPL = "startPL";
Regex regex = new Regex("[^0-9]");
List<ProductsDostavka> products = new List<ProductsDostavka>();
List<ProductsDostavka> souses = new List<ProductsDostavka>();
ShowPersonalMenuCarusel showProductCaruselMain = new ShowPersonalMenuCarusel();
var keyboardBuilder = new KeyboardBuilder().Clear();
int kkals = 0;
try
{
string[] payload = update.@object.message.payload.Split('-');
int curCategory = Convert.ToInt32(regex.Replace(payload[1], ""));
int curProduct = Convert.ToInt32(regex.Replace(payload[2], ""));
int curDayKkal = Convert.ToInt32(regex.Replace(payload[3], ""));
int curDay = (int)DateTime.Now.DayOfWeek;
if (curDay == 0) curDay = 7;
var user = db.Users.Single(usr => usr.chatId == chatId);
var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);
var prodDb = db.ProductsDostavkas.Where(p =>
p.id == curProduct &&
JsonConvert.DeserializeObject<List<int>>(p.weekDays).Exists(e => e == curDay));
products = prodDb.ToList().ConvertAll<ProductsDostavka>(el => new ProductsDostavka()
{
id = el.id,
idIiko = el.idIiko,
article = el.article,
categoryId = el.categoryId,
name = el.name,
fullName = el.fullName,
description = el.description,
price = Convert.ToDouble( el.price),
photo = el.photo,
additions = JsonConvert.DeserializeObject<List<string>>(el.additions),
recommends = JsonConvert.DeserializeObject<List<string>>(el.recommends),
kkal = el.kkal,
});
var orderPizza = new Order();
var orderSous = new Order();
if (cartObject.orders.Exists(o => o.id.Equals(curCategory + "-" + curProduct)))
cartObject.orders.Find(o => o.id.Equals(curCategory + "-" + curProduct)).number++;
else
{
var order = new Order()
{
id = curCategory + "-" + curProduct,
idIiko = products[0].idIiko,
fullname = products[0].fullName,
name = products[0].name,
price = products[0].price,
number = 1,
article = products[0].article,
kkal = products[0].kkal,
};
cartObject.orders.Add(order);
}
user.cart = JsonConvert.SerializeObject(cartObject);
db.SaveChanges();
foreach (var o in cartObject.orders)
{
sum += o.price * o.number;
kkals += o.kkal * o.number;
}
keyboardBuilder
.AddButton($"Завтрак (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-1-" + curDayKkal, KeyboardButtonColor.Primary)
.AddLine()
.AddButton($"Обед (до {Math.Round(curDayKkal * 1.2 * 0.4)} ккал)", "selectPersonalMenu-2-" + curDayKkal, KeyboardButtonColor.Primary)
.AddLine()
.AddButton($"Перекус (до {Math.Round(curDayKkal * 1.2 * 0.1)} ккал)", "selectPersonalMenu-3-" + curDayKkal, KeyboardButtonColor.Primary)
.AddLine()
.AddButton($"Ужин (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-4-" + curDayKkal, KeyboardButtonColor.Primary)
.AddLine();
if (cartObject.orders.Count > 0)
{
keyboardBuilder
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default)
.AddButton("Корзина: " + sum + " р", "selectCart-0", KeyboardButtonColor.Negative);
}
else
{
keyboardBuilder
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
}
if (update.@object.client_info.carousel == true)
{
msg = "✅ " + products.Find(p => p.id == curProduct).fullName + " добавлен в корзину.";
}
//@params.Template = templateBuilder.Build();
@params.Keyboard = keyboardBuilder.Build();
@params.Message = msg;
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
//else
//{
// switch (curCategory)
// {
// case 1:
// if (update.@object.client_info.carousel == true)
// showProductCaruselDouble.Execute(update, client, Con, curCategory, curProduct);
// else
// showProductDouble.Execute(update, client, Con, curCategory, curProduct, 2);
// break;
// default:
// if (update.@object.client_info.carousel == true)
// showProductCaruselMain.Execute(update, client, Con, curCategory, curProduct, 1);
// else
// showProductMain.Execute(update, client, Con, curCategory, curProduct, 0, 2);
// break;
// }
//}
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectAddToCartCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using SvetoforVKBot.Models.Commands.LK.Cart;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Model;
using VkNet.Model.RequestParams;
using Newtonsoft.Json;
using VkNet.Model.Keyboard;
namespace SvetoforVKBot.Models.Commands.LK.Cart
{
public class SelectCartCommand : Command
{
public override string Name => "{\"button\":\"selectCart-";
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]");
List<ProductsDostavka> products = new List<ProductsDostavka>();
List<Button> buttons = new List<Button>();
try
{
string[] payload = update.@object.message.payload.Split('-');
int curCart = Convert.ToInt32(regex.Replace(payload[1], ""));
ShowCart showCart = new ShowCart();
showCart.Execute(update, client, db, curCart);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectCartCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,54 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Commands.LK.Menu.Products;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Model.RequestParams;
using VkNet.Model.Keyboard;
using VkNet.Enums.SafetyEnums;
using Newtonsoft.Json;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.LK.Cart
{
public class SelectConfirmClearCartCommand : Command
{
public override string Name => "{\"button\":\"selectConfirmClearCart\"}";
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;
string msg = "";
var keyboardBuilder = new KeyboardBuilder().Clear();
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
var jsCart = JsonConvert.DeserializeObject<CartObject>(user.cart);
jsCart.orders.RemoveAll(o => o.id.StartsWith("0-") == false);
user.cart = JsonConvert.SerializeObject(jsCart);
db.SaveChanges();
msg = "✅Корзина очищена.\nВозвращаю в Личный кабинет.\n";
ShowLKCommand showLK = new ShowLKCommand();
showLK.Execute(update, client, db);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectConfirmClearCartCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,97 @@
using System;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using SvetoforVKBot.Models.Commands.LK.Cart;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Model.RequestParams;
using SvetoforVKBot.Models.Commands.LK.Menu.Products;
using VkNet.Model.Keyboard;
using VkNet.Enums.SafetyEnums;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.LK.Cart
{
public class SelectEditCartCommand : Command
{
public override string Name => "{\"button\":\"selectEditCart-";
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 msg = "";
try
{
string[] payload = update.@object.message.payload.Split('-');
int action = Convert.ToInt32(regex.Replace(payload[1], ""));
int curCart = Convert.ToInt32(regex.Replace(payload[2], ""));
var user = db.Users.Single(usr => usr.chatId == chatId);
var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);
if (cartObject.orders[curCart].id.StartsWith("0-")) return;
switch (action)
{
case 1: // -
if (cartObject.orders[curCart].number == 1)
cartObject.orders.RemoveAt(curCart);
else
cartObject.orders[curCart].number--;
break;
case 2: // +
cartObject.orders[curCart].number++;
break;
};
if (action > 2)
{
int count = action - 3;
if (count == 0)
cartObject.orders.RemoveAt(curCart);
else
cartObject.orders[curCart].number = count;
}
user.cart = JsonConvert.SerializeObject(cartObject);
db.SaveChanges();
if (cartObject.orders.Count > 0)
{
if (curCart >= cartObject.orders.Count)
curCart = cartObject.orders.Count - 1;
ShowCart showCart = new ShowCart();
showCart.Execute(update, client, db, curCart);
}
else
{
msg = "Корзина оказалась пустой. \n" +
"\n" +
"Возвращаю в Личный кабинет";
ShowLKCommand showLK = new ShowLKCommand();
showLK.Execute(update, client, db);
}
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectEditCartCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,192 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
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.LK.Cart
{
public class ShowCart
{
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, int curCart) //curCart - порядковый номер в массиве корзины
{
MessagesSendParams @params = new MessagesSendParams();
int cartCount = 0;
var chatId = update.@object.message.from_id;
string msg = "";
//string voronka = "";
List<CategoriesDostavka> categories = new List<CategoriesDostavka>();
List<ProductsDostavka> products = new List<ProductsDostavka>();
int i = 0;
int j = 0;
int prevCart = 0, nextCart = 0;
double sum = 0;
double fullSum = 0;
string label = "";
var keyboardBuilder = new KeyboardBuilder().Clear();
int kkals = 0;
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);
//SqlCommand getCart = new SqlCommand("SELECT cart, voronka FROM Users WHERE chatId = @chatId;", Con);
//getCart.Parameters.AddWithValue("@chatId", chatId);
//SqlDataReader rgetCart = getCart.ExecuteReader();
//rgetCart.Read();
//var cartObject = JsonConvert.DeserializeObject<CartObject>(rgetCart["cart"].ToString());
//voronka = rgetCart["voronka"].ToString();
//rgetCart.Close();
//cartObject.orders.RemoveAll(o => o.article.StartsWith("00-"));
cartObject.dostavkaCost = 100;
//if (cartObject.orders.Count == 0)
//{
// msg = "Корзина пуста.\n📋Возвращаю в основное меню";
// ShowMenuDostavka showMenuDostavka = new ShowMenuDostavka();
// showMenuDostavka.Execute(update, client, Con, msg, 1, 0);
// return;
//}
if (curCart >= cartObject.orders.Count)
{
curCart = cartObject.orders.Count - 1;
prevCart = curCart - 1;
nextCart = 0;
}
else
{
prevCart = curCart - 1;
nextCart = curCart + 1;
}
if ((curCart + 1) == cartObject.orders.Count)
{
prevCart = curCart - 1;
nextCart = 0;
}
if (curCart == 0)
{
prevCart = cartObject.orders.Count - 1;
nextCart = curCart + 1;
}
string promo = "";
msg = "Ваша корзина: \n";
double sumCheck = 0;
foreach (var o in cartObject.orders)
{
sumCheck += o.price * o.number;
}
for (i = 0; i < cartObject.orders.Count; i++)
{
cartCount++;
switch (cartObject.orders[i].id)
{
default:
msg += (i + 1).ToString() + ". " +
cartObject.orders[i].fullname + " - " + cartObject.orders[i].kkal + " ккал. " +
cartObject.orders[i].number + " шт. " +
(cartObject.orders[i].price * cartObject.orders[i].number).ToString() + " ₽ \n";
sum += cartObject.orders[i].price * cartObject.orders[i].number;
kkals += cartObject.orders[i].kkal * cartObject.orders[i].number;
break;
}
//msg += (i + 1).ToString() + ". " +
// cartObject.orders[i].fullname + " - " +
// cartObject.orders[i].number + " шт. " +
// (cartObject.orders[i].price * cartObject.orders[i].number).ToString() + " ₽ \n";
/*cartCount++;
for (j = 0; j < cartObject.orders.Count; j++)
{
msg += " " + cartCount.ToString() + "." + (j + 1).ToString() + " Доп - " +
cartObject.orders[i].addition[j].fullname + " - " +
cartObject.orders[i].addition[j].number + " шт. " +
(cartObject.orders[i].addition[j].price * cartObject.orders[i].addition[j].number).ToString() + " ₽ \n";
}
*/
}
fullSum = sum;
user.cart = JsonConvert.SerializeObject(cartObject);
db.SaveChanges();
//SqlCommand updCart = new SqlCommand("UPDATE Users SET cart = @cart WHERE chatId = @chatId;", Con);
//updCart.Parameters.AddWithValue("@chatId", chatId);
//updCart.Parameters.AddWithValue("@cart", JsonConvert.SerializeObject(cartObject));
//updCart.ExecuteNonQuery();
msg += "\n" +
"Итого: " + fullSum + " ₽ | " + kkals + " ккал.";
label = cartObject.orders[curCart].name + " " +
cartObject.orders[curCart].price + " ₽ * " +
cartObject.orders[curCart].number + " = " +
(cartObject.orders[curCart].price * cartObject.orders[curCart].number).ToString() + " ₽";
if (label.Length > 40)
label = cartObject.orders[curCart].name + " " +
(cartObject.orders[curCart].price * cartObject.orders[curCart].number).ToString() + " ₽";
keyboardBuilder
.AddButton(label, "selectCart-" + curCart, KeyboardButtonColor.Default)
.AddLine()
.AddButton("-", "selectEditCart-1-" + curCart, KeyboardButtonColor.Default)
.AddButton(cartObject.orders[curCart].number + " шт", "selectCartCount-" + curCart, KeyboardButtonColor.Default)
.AddButton("+", "selectEditCart-2-" + curCart, KeyboardButtonColor.Default)
.AddButton("🗑Очистить", "selectConfirmClearCart", KeyboardButtonColor.Default)
.AddLine()
.AddButton("<<", "selectCart-" + prevCart, KeyboardButtonColor.Primary)
.AddButton((curCart + 1).ToString() + "/" + cartObject.orders.Count, "selectCart-" + curCart, KeyboardButtonColor.Default)
.AddButton(">>", "selectCart-" + nextCart, KeyboardButtonColor.Primary);
keyboardBuilder
.AddLine()
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
@params.Message = msg;
@params.UserId = chatId;
@params.Keyboard = keyboardBuilder.Build();
@params.DontParseLinks = true;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в ShowCart: " + 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,85 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using SvetoforVKBot.App_Start;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.LK.Consultation
{
public class GetConsultationCommand
{
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
var chatId = update.@object.message.from_id;
MessagesSendParams @params = new MessagesSendParams();
MessagesSendParams @params2 = new MessagesSendParams();
var keyboardBuilder = new KeyboardBuilder().Clear();
try
{
if (update.@object.message.text.Length > 0)
{
var ids = new long[] { chatId };
var user = db.Users.Single(usr => usr.chatId == chatId);
user.question = update.@object.message.text.Trim();
user.tag = "Личный кабинет";
db.SaveChanges();
keyboardBuilder
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.Message = "✅Вопрос принят. Менеджер ответит Вам в ближайшее время!\n";
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
@params2.Message = "❓Вопрос. \nСсылка на диалог: " + ((WebConfiguration)ConfigurationManager.GetSection("VKApi")).GroupDialogsLink + chatId;
List<long> listFrwMsg = new List<long>() { update.@object.message.id };
@params2.PeerId = 2000000002;
//@params2.UserId = 59111081;
@params2.ForwardMessages = listFrwMsg;
@params2.RandomId = GetRandomId();
client.Messages.Send(@params2);
}
else
{
@params.Message = "Не распознал сообщение 😕 Попробуйте, пожалуйста, ещё раз";
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в GetReportCommentCommand: " + 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,62 @@
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.LK.Consultation
{
public class SelectConsultationCommand : Command
{
public override string Name => "{\"button\":\"selectConsultation\"}";
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 = "Консультация - Вопрос";
db.SaveChanges();
@params.Message = //"Вы можете записаться на онлайн-консультацию к специалисту.\n" +
"Напишите свой вопрос сюда одним сообщением. " + //Это будет служить Вашей заявкой.\n" +
"Менеджер свяжется с Вами для ответа и уточнения информации."; //"Мы оповестим Вас о ближайшей консультации, к которой Вы сможете присоединиться.\n\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 = "Ошибка в SelectExpertLKCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,53 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.LK.Consultation
{
public class SelectLiveConsultationCommand : Command
{
public override string Name => "{\"button\":\"selectLiveConsultation\"}";
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
{
@params.Message = "-----Информация о приёме на консультации.-----\n\n" +
"Вы можете оформить заявку на запись. Для этого нажмите кнопку \"Оставить заявку\".\n" +
"Ваши данные будут отправлены менеджеру, с Вами свяжутся для уточнения даты и времени консультации.";
keyboardBuilder
.AddButton("Оставить заявку", "selectSubmitConsultation", KeyboardButtonColor.Positive) //К
.AddLine()
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в selectLiveConsultation: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Threading;
using Newtonsoft.Json;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Attachments;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.LK.Consultation
{
public class SelectMoreAboutSpecCommand : Command
{
public override string Name => "{\"button\":\"selectMoreAboutSpec\"}";
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
{
//{"id": 457239276, "owner_id": -194717824, "access_key": "3f83861845f644622f"}
List<MediaAttachment> listPhoto = new List<MediaAttachment>()
{
new VkNet.Model.Attachments.Photo() { Id = 457239276, OwnerId = -194717824, AccessKey = "3f83861845f644622f"}
};
@params.Message =
"📌Кадочникова Наталья Ивановна\n" +
"Кандидат биологических наук, доцент кафедры медико-биологических дисциплин факультета физической культуры и спорта ВятГУ." +
"\n\n" +
"⭐Стаж работы более 20 лет, автор более 100 научных публикаций в области физиологии." +
"\n\n" +
"⭐Участник Международных и Всероссийских научно-практических конференций по спортивной науке." +
"\n\n" +
"🎓Прошла обучение по программам:" +
"\n" +
"✅По использованию анализатора состава тела АВС-01 «Медасс» в практике спортивной медицины " +
"и реабилитологии (г. Москва АО НТЦ «Медасс», март 2016)" +
"\n\n" +
"✅«Оптимальное питание» (г. Москва, ФНМО РУДН, март 2019)" +
"\n\n" +
"✅«Питание в фитнесе» (г. Москва, ФНМО РУДН, апрель 2019)" +
"\n\n" +
"✅ «Современное диетическое и персонализированное питание» (г. Москва, МГУТУ им. К.Г. Разумовского, март 2021)." +
"\n\n";
@params.Message += "📍Консультации проводятся по субботам по адресу: г. Киров, ул. Молодой Гвардии, д.13.\n" +
"☎Тел. 70-81-22.\n" +
"Стоимость и условия по телефону.";
keyboardBuilder
.AddButton("Оставить заявку", "selectSubmitConsultation", KeyboardButtonColor.Positive) //К
.AddLine()
.AddButton("Назад", "selectTrack-4", KeyboardButtonColor.Default);
@params.Attachments = listPhoto;
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectMoreAboutSpecCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,154 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Threading;
using Newtonsoft.Json;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Attachments;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using System.Linq;
using System.Configuration;
using SvetoforVKBot.App_Start;
namespace SvetoforVKBot.Models.Commands.LK.Consultation
{
public class SelectSubmitConsultationCommand : Command
{
public const int MODER = 59111081;
public override string Name => "{\"button\":\"selectSubmitConsultation\"}";
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();
MessagesSendParams @params2 = new MessagesSendParams();
var keyboardBuilder = new KeyboardBuilder().Clear();
string msg = "";
DateTime dt = DateTime.Now;
string msgManager = "";
List<int> ids = new List<int>();
try
{
if (db.PersonalConsultations.Where(c => c.chatId == chatId).Count() > 0)
{
@params.Message = "Ваша заявка уже на рассмотрении. Чтобы вернуться назад, нажмите кнопку \"Личный кабинет\".";
keyboardBuilder
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Positive);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return;
}
//https://vk.com/doc59111081_594730049
List<MediaAttachment> listDoc = new List<MediaAttachment>()
{
new Document() { Id = 594730049, OwnerId = 59111081 }
};
db.PersonalConsultations.Add(new Data.PersonalConsultation()
{
chatId = chatId,
datetime = dt,
state = 1,
});
db.SaveChanges();
var user = db.Users.Single(usr => usr.chatId == chatId);
var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);
@params.Message = "📌Ваша заявка:\n\n";
msg = "ФИО: " + user.fio +
"\n" +
"Телефон: " + jsPhones[0] +
"\n" +
"Дата рождения: " + user.birthday.ToShortDateString() +
"\n\n" +
"Дата заявки: " + dt.ToString("dd.MM.yyyy HH:mm");
@params.Message += msg +
"\n\n" +
"Заявка отправлена! Менеджер свяжется с Вами в ближайшее время. Чтобы вернуться назад, нажмите кнопку \"Личный кабинет\".\n\n" +
"Квитанция на оплату 👇🏻";
keyboardBuilder
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Positive);
@params.Attachments = listDoc;
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
Thread.Sleep(1000);
@params2.Message = "✅Новая заявка на консультацию:\n\n" +
"ФИО: " + user.fio +
"\n" +
"Телефон: " + jsPhones[0] +
"\n" +
"Дата рождения: " + user.birthday.ToShortDateString() +
"\n" +
"Рост: " + user.height +
"\n" +
"Вес: " + user.weight +
"\n\n" +
"Дата заявки: " + dt.ToString("dd.MM.yyyy HH:mm") +
"\n" +
"Диалог с пользователем: " + ((WebConfiguration)ConfigurationManager.GetSection("VKApi")).GroupDialogsLink + chatId;
//https://vk.com/gim194717824?sel=
@params2.PeerId = 2000000002;
@params2.RandomId = GetRandomId();
client.Messages.SendAsync(@params2);
Thread.Sleep(1500);
ids = db.PersonalConsultations.Where(c => c.state == 2).ToList().ConvertAll<int>(el => el.chatId);
string strIds = "Участники, записавшиеся на консультацию:\n";
if (ids.Count >= 6)
{
foreach (var id in ids)
{
strIds += ((WebConfiguration)ConfigurationManager.GetSection("VKApi")).GroupDialogsLink + id + " \n";
//Проверить как записывает
var con = db.PersonalConsultations.Where(el => el.chatId == chatId);
db.Entry(con).Property("state").CurrentValue = 3;
db.SaveChanges();
Thread.Sleep(10);
}
@params2.Message = "🔔 Набралась группа на консультацию! Оповестите их о подробностях." +
"\n\n" +
strIds;
@params2.PeerId = 2000000002;
@params2.RandomId = GetRandomId();
client.Messages.SendAsync(@params2);
}
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectSubmitConsultationCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
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;
namespace SvetoforVKBot.Models.Commands.LK.EditData
{
public class GetEditFIOCommand
{
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
var chatId = update.@object.message.from_id;
MessagesSendParams @params = new MessagesSendParams();
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();
SelectEditDataCommand selectEditData = new SelectEditDataCommand();
selectEditData.Execute(update, client, db);
}
else
{
@params.Message = "Данные введены некорректно 😕 Напишите, пожалуйста, текст длиной до 50 символов.";
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в GetEditFIOCommand: " + 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,111 @@
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.LK.EditData
{
public class GetEditPhoneCommand
{
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);
SelectEditDataCommand selectEditData = new SelectEditDataCommand();
selectEditData.Execute(update, client, db);
}
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 = "‼Ошибка в GetEditPhoneCommand: " + 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,58 @@
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.LK.EditData
{
public class SelectEditNotifyCount : Command
{
public override string Name => "{\"button\":\"selectEditNotifyCount-";
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);
user.notifyCount = notifyCount;
user.tag = "Личный кабинет - Данные";
db.SaveChanges();
SelectEditDataCommand selectEditData = new SelectEditDataCommand();
selectEditData.Execute(update, client, db);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectEditNotifyCountCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using Newtonsoft.Json;
using SvetoforVKBot.Models.Commands.Registration;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Attachments;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.LK.EditData
{
public class SelectUpdateSportDaysCommand : Command
{
public override string Name => "{\"button\":\"selectUpdateSportDays\"}";
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();
MessagesSendParams @params2 = new MessagesSendParams();
var keyboardBuilder = new KeyboardBuilder().Clear();
string msg = "";
DateTime dt = DateTime.Now;
string msgManager = "";
List<int> ids = new List<int>();
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
user.sportDays = "[]";
db.SaveChanges();
ShowSportDays showSportDays = new ShowSportDays();
showSportDays.Execute(update, client, db);
return;
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectUpdateSportDaysCommand: " + 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.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.LK
{
public class GetHeightCommand
{
public void 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 (int.TryParse(update.@object.message.text.Trim(), out int height))
{
var user = db.Users.Single(usr => usr.chatId == chatId);
user.height = height;
user.tag = "Личный кабинет - Данные";
db.SaveChanges();
SelectEditDataCommand selectEditData = new SelectEditDataCommand();
selectEditData.Execute(update, client, db);
}
else
{
@params.UserId = chatId;
@params.Message = "Вы некорректно ввели рост 🤔 Введите, пожалуйста, число (до 3 символов).";
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в GetHeightCommand: " + 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,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.LK
{
public class GetWeightCommand
{
public void 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 (int.TryParse(update.@object.message.text.Trim(), out int weight))
{
var user = db.Users.Single(usr => usr.chatId == chatId);
user.weight = weight;
user.tag = "Личный кабинет - Данные";
db.SaveChanges();
/*SqlCommand editUser = new SqlCommand("UPDATE Users SET tag = @tag, weight = @weight WHERE chatId = @chatId;", Con);
editUser.Parameters.AddWithValue("@chatId", chatId);
editUser.Parameters.AddWithValue("@tag", "Личный кабинет - Данные");
editUser.Parameters.AddWithValue("@weight", weight);
editUser.ExecuteNonQuery();*/
SelectEditDataCommand selectEditData = new SelectEditDataCommand();
selectEditData.Execute(update, client, db);
}
else
{
@params.UserId = chatId;
@params.Message = "Вы некорректно ввели вес 🤔 Введите, пожалуйста, число (до 3 символов).";
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в GetWeightCommand: " + 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,76 @@
using System;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using SvetoforVKBot.Models.Commands.LK.Menu.Products;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Model.RequestParams;
using Newtonsoft.Json;
using VkNet.Model.Keyboard;
using VkNet.Enums.SafetyEnums;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.LK.Menu.Products
{
public class SelectProductCommand : Command
{
public override string Name => "{\"button\":\"selectProduct-";
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;
string msg = "";
string voronka = "";
double sum = 0;
string backPL = "startPL";
Regex regex = new Regex("[^0-9]");
ShowProductCaruselMain showProductCaruselMain = new ShowProductCaruselMain();
ShowProductMain showProductMain = new ShowProductMain();
CategoriesDostavka categories = new CategoriesDostavka();
var keyboardBuilder = new KeyboardBuilder().Clear();
try
{
string[] payload = update.@object.message.payload.Split('-');
int curCategory = Convert.ToInt32(regex.Replace(payload[1], ""));
int curProduct = Convert.ToInt32(regex.Replace(payload[2], ""));
int curWay = Convert.ToInt32(regex.Replace(payload[3], "")); //для ShowProductCaruselMain направление навигации, 1 по умолчанию
var cats = db.CategoriesDostavkas.Where(e => e.subMenu == curCategory);
if(cats.Count() > 0)
{
ShowMenuDostavka showMenuDostavka = new ShowMenuDostavka();
showMenuDostavka.Execute(update, client, db, msg, 2, categories.subMenu); //1
}
else
{
switch (curCategory)
{
default:
if (update.@object.client_info.carousel == true)
showProductCaruselMain.Execute(update, client, db, curCategory, curProduct, curWay);
else
showProductMain.Execute(update, client, db, curCategory, curProduct, 0, 1);
break;
}
}
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectProductCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,269 @@
using Newtonsoft.Json;
using SvetoforVKBot.Models.Updates;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Security.Cryptography;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using VkNet.Utils;
using VkNet.Model.Template;
using VkNet.Model.Template.Carousel;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.LK.Menu.Products
{
public class ShowProductCaruselMain
{
private const string PHOTOIDNEXT = "-194717824_457239273_446146426236760985";
//{"id": 457239273, "owner_id": -194717824, "access_key": "446146426236760985"}
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, int curCategory, int curProduct, int curWay)
//curCategory - id Categories, curProduct - порядковый номер в массиве продуктов, curWay - для showProductCarusel направление навигации
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
int i = 0;
int prevCatalog = 0, nextCatalog = 0;
int naviState = 0;
double sum = 0;
string desc = "";
//int curDay = (int)DateTime.Now.DayOfWeek;
//if (curDay == 0) curDay = 7;
List<CategoriesDostavka> categories = new List<CategoriesDostavka>();
List<ProductsDostavka> products = new List<ProductsDostavka>();
var row = new List<MessageKeyboardButton>();
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
TemplateBuilder templateBuilder = new TemplateBuilder();
CarouselElementAction carouselElementAction = new CarouselElementAction();
carouselElementAction.Type = CarouselElementActionType.OpenPhoto;
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);
int curDay = user.day;
//SqlCommand getCart = new SqlCommand("SELECT cart, day, colorId FROM Users WHERE chatId = @chatId;", Con);
//getCart.Parameters.AddWithValue("@chatId", chatId);
//SqlDataReader rgetCart = getCart.ExecuteReader();
//rgetCart.Read();
//var cartObject = JsonConvert.DeserializeObject<CartObject>(rgetCart["cart"].ToString());
//int curDay = Convert.ToInt32(rgetCart["day"]);
//int colorId = Convert.ToInt32(rgetCart["colorId"]);
//rgetCart.Close();
if (curDay == 8) curDay = (int)DateTime.Now.DayOfWeek;
foreach (var o in cartObject.orders)
{
sum += o.price * o.number;
}
categories = db.CategoriesDostavkas.ToList().ConvertAll<CategoriesDostavka>(c =>
new CategoriesDostavka()
{
categoryId = c.categoryId,
name = c.name,
btnName = c.btnName,
kbColor = c.kbColor,
});
//SqlCommand getCategories = new SqlCommand("SELECT * FROM CategoriesDostavka;", Con);
//getCategories.Parameters.AddWithValue("@chatId", chatId);
//SqlDataReader rgetCategories = getCategories.ExecuteReader();
//while (rgetCategories.Read())
// categories.Add(new CategoriesDostavka()
// {
// categoryId = Convert.ToInt32(rgetCategories["categoryId"]),
// name = rgetCategories["name"].ToString(),
// btnName = rgetCategories["btnName"].ToString(),
// kbColor = rgetCategories["kbColor"].ToString(),
// });
//rgetCategories.Close();
products = db.ProductsDostavkas.Where(p => p.categoryId == curCategory &&
JsonConvert.DeserializeObject<List<int>>(p.weekDays).Exists(day => day == curDay)).
ToList().ConvertAll<ProductsDostavka>(e => new ProductsDostavka()
{
id = e.id,
article = e.article,
colorId = e.colorId,
categoryId = e.categoryId,
name = e.name,
fullName = e.fullName,
description = e.description,
descriptionCarousel = e.descriptionCarousel,
price = Convert.ToDouble(e.price),
photo = e.photo,
photoCarousel = e.photoCarousel,
additions = JsonConvert.DeserializeObject<List<string>>(e.additions),
recommends = JsonConvert.DeserializeObject<List<string>>(e.recommends),
});
//SqlCommand getProducts = new SqlCommand("SELECT * FROM ProductsDostavka WHERE categoryId = @categoryId;", Con);
//getProducts.Parameters.AddWithValue("@categoryId", curCategory);
////getProducts.Parameters.AddWithValue("@colorId", colorId);
//SqlDataReader rgetProducts = getProducts.ExecuteReader();
//while (rgetProducts.Read())
//{
// var weekDays = JsonConvert.DeserializeObject<List<int>>(rgetProducts["weekDays"].ToString());
// foreach (int weekDay in weekDays)
// {
// if (weekDay == curDay)
// {
// products.Add(new ProductsDostavka()
// {
// id = Convert.ToInt32(rgetProducts["id"]),
// article = rgetProducts["article"].ToString(),
// colorId = Convert.ToInt32(rgetProducts["colorId"]),
// categoryId = Convert.ToInt32(rgetProducts["categoryId"]),
// name = rgetProducts["name"].ToString(),
// fullName = rgetProducts["fullName"].ToString(),
// descriptionCarousel = rgetProducts["descriptionCarousel"].ToString(),
// price = Convert.ToInt32(rgetProducts["price"]),
// photo = rgetProducts["photo"].ToString(),
// photoCarousel = rgetProducts["photoCarousel"].ToString(),
// //weight = rgetProducts["weight"].ToString(),
// });
// }
// }
//}
//rgetProducts.Close();
nextCatalog = curProduct + 9;
prevCatalog = curProduct - 9;
if (curProduct > 0 && products.Count > 6)
{
if (nextCatalog > products.Count) nextCatalog = products.Count - (products.Count - curProduct);
if (prevCatalog < 0) prevCatalog = 0;
}
for (i = curProduct; i < products.Count; i++)
{
var jsPhoto = JsonConvert.DeserializeObject<CatalogPhotoObject>(products[i].photoCarousel);
desc = products[i].descriptionCarousel; //+ " " + products[i].weight;
if (desc.Length > 80) desc = desc.Substring(0, 77) + "..."; //desc.Substring(0, 77)
templateBuilder.AddTemplateElement(new CarouselElement()
{
Title = products[i].fullName,
Description = desc,
PhotoId = jsPhoto.owner_id + "_" + jsPhoto.id + "_" + jsPhoto.access_key,
Buttons = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton(){
Action = new MessageKeyboardButtonAction(){ Label = "Подробнее",
Payload = "{\"button\":\"selectAddToCart-" + curCategory + "-" + i + "\"}",
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Default
},
},
Action = carouselElementAction,
});
if (templateBuilder.Elements.Count == 9 && products.Count > 10)
break;
}
if (products.Count > 10)
{
switch (curWay)
{
case 1:
if (curProduct < (products.Count - 9))
naviState = 1;
else
naviState = 2;
break;
case 2:
if (curProduct == 0)
naviState = 1;
else
naviState = 2;
break;
default:
naviState = 2;
break;
}
switch (naviState)
{
case 1:
templateBuilder.AddTemplateElement(new CarouselElement()
{
Title = ".",
Description = ".",
PhotoId = PHOTOIDNEXT,
Buttons = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){ Label = ">> Следующие " + (products.Count - nextCatalog).ToString(),
Payload = "{\"button\":\"selectProduct-" + products[nextCatalog].categoryId + "-" + nextCatalog + "-1\"}",
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Primary
},
},
Action = carouselElementAction,
});
break;
case 2:
templateBuilder.AddTemplateElement(new CarouselElement()
{
Title = ".",
Description = ".",
PhotoId = PHOTOIDNEXT,
Buttons = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){ Label = "<< Предыдущие " + curProduct,
Payload = "{\"button\":\"selectProduct-" + products[prevCatalog].categoryId + "-" + prevCatalog + "-2\"}",
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Primary
},
},
Action = carouselElementAction,
});
break;
}
}
@params.Template = templateBuilder.Build();
@params.Message = "😍";
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в ShowProductCaruselMain: " + 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,232 @@
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.LK.Menu.Products
{
public class ShowProductMain
{
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, int curCategory, int curProduct, int curAddition, int plAction)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
int i = 0;
int index = 0;
Regex regex = new Regex("[^0-9]");
int prevCatalog = 0, nextCatalog = 0;
//double sumCart = 0;
double sum = 0;
Additions addition = new Additions();
//DateTime startDate = new DateTime(2020, 09, 14);
//DateTime currentDate = DateTime.Now;
//TimeSpan offset = currentDate - startDate;
//int curDay = offset.Days % 14 + 1;
string backPL = "selectMenu-0";
List<CategoriesDostavka> categories = new List<CategoriesDostavka>();
List<ProductsDostavka> products = new List<ProductsDostavka>();
var keyboardBuilder = new KeyboardBuilder().Clear();
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);
int curDay = user.day;
//int curDay = (int)DateTime.Now.DayOfWeek;
//if (curDay == 0) curDay = 7;
if (curDay == 8) curDay = (int)DateTime.Now.DayOfWeek;
/*
* foreach (var o in cartObject.orders)
sum += o.price * o.number;
*/
categories = db.CategoriesDostavkas.ToList().ConvertAll<CategoriesDostavka>(c =>
new CategoriesDostavka()
{
categoryId = c.categoryId,
name = c.name,
btnName = c.btnName,
kbColor = c.kbColor,
});
products = db.ProductsDostavkas.Where(p => p.categoryId == curCategory &&
JsonConvert.DeserializeObject<List<int>>(p.weekDays).Exists(day => day == curDay)).
ToList().ConvertAll<ProductsDostavka>(e => new ProductsDostavka()
{
id = e.id,
article = e.article,
colorId = e.colorId,
categoryId = e.categoryId,
name = e.name,
fullName = e.fullName,
description = e.description,
descriptionCarousel = e.descriptionCarousel,
price = Convert.ToDouble(e.price),
photo = e.photo,
photoCarousel = e.photoCarousel,
additions = JsonConvert.DeserializeObject<List<string>>(e.additions),
recommends = JsonConvert.DeserializeObject<List<string>>(e.recommends),
});
switch (plAction)
{
case 1:
var jsPhoto = JsonConvert.DeserializeObject<CatalogPhotoObject>(products[curProduct].photo);
List<MediaAttachment> listPhoto = new List<MediaAttachment>()
{
new VkNet.Model.Attachments.Photo() { Id = jsPhoto.id, OwnerId = jsPhoto.owner_id, AccessKey = jsPhoto.access_key}
};
@params.Attachments = listPhoto;
@params.Message = products[curProduct].fullName + "\n" +
products[curProduct].description + "\n"; // + " " + products[curProduct].weight
break;
case 2:
if (curAddition == 0)
@params.Message = "✅ " + products[curProduct].fullName + " добавлен в корзину.";
else
{
// Нет таблицы с модификаторами
//SqlCommand getAddition = new SqlCommand("SELECT * FROM Modifiers WHERE article = @article;", Con);
//getAddition.Parameters.AddWithValue("@article", curAddition);
//SqlDataReader rgetAddition = getAddition.ExecuteReader();
//if (rgetAddition.HasRows)
//{
// rgetAddition.Read();
// addition = new Additions()
// {
// name = rgetAddition["name"].ToString(),
// price = Convert.ToInt32(rgetAddition["price"]),
// fullName = rgetAddition["fullName"].ToString(),
// article = rgetAddition["article"].ToString(),
// };
//}
//rgetAddition.Close();
@params.Message = "✅ " + products[curProduct].fullName + " с " + addition.fullName + " добавлен в корзину.";
}
break;
}
if (curProduct >= products.Count)
{
curProduct = products.Count - 1;
prevCatalog = curProduct - 1;
nextCatalog = 0;
}
else
{
prevCatalog = curProduct - 1;
nextCatalog = curProduct + 1;
}
if ((curProduct + 1) == products.Count)
{
prevCatalog = curProduct - 1;
nextCatalog = 0;
}
if (curProduct == 0)
{
prevCatalog = products.Count - 1;
nextCatalog = curProduct + 1;
}
if (products.Count == 1)
{
prevCatalog = 0;
nextCatalog = 0;
}
#region keyboard
//keyboardBuilder
// .AddButton("Подробнее", "selectAddToCart-" + curCategory + "-" + curProduct, KeyboardButtonColor.Primary)
// .AddLine();
keyboardBuilder
.AddButton("<<", "selectProduct-" + curCategory + "-" + prevCatalog + "-1", KeyboardButtonColor.Primary)
.AddButton((curProduct + 1) + "/" + products.Count, "selectProduct-" + curCategory + "-" + curProduct + "-1", KeyboardButtonColor.Default)
.AddButton(">>", "selectProduct-" + curCategory + "-" + nextCatalog + "-1", KeyboardButtonColor.Primary)
.AddLine();
keyboardBuilder
.AddButton("Вернуться в меню", "selectDayMenu-" + curDay, KeyboardButtonColor.Default)
//.AddButton("Корзина: " + sum + " р", "selectCart-0", KeyboardButtonColor.Negative)
.AddLine()
.AddButton("День недели", "selectMenu-0", KeyboardButtonColor.Default);
//.AddLine();
#endregion keyboard
/*
if (products.Count > 10) //14
{
if (curProduct < (products.Count - 10)) index = curProduct + 1;
else index = products.Count - 10;
}
else index = 0;
int rowCount = 3;
for (i = index; i < products.Count; i += 2)
{
if (i + 1 < products.Count)
keyboardBuilder
.AddButton(products[i].name, "selectProduct-" + curCategory + "-" + i.ToString() + "-1", KeyboardButtonColor.Default)
.AddButton(products[i + 1].name, "selectProduct-" + curCategory + "-" + (i + 1).ToString() + "-1", KeyboardButtonColor.Default)
.AddLine();
else
keyboardBuilder
.AddButton(products[i].name, "selectProduct-" + curCategory + "-" + i.ToString() + "-1", KeyboardButtonColor.Default)
.AddLine();
rowCount += 1;
if (rowCount == 8) break;
}
*/
@params.UserId = chatId;
@params.Keyboard = keyboardBuilder.Build();
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в ShowProductMain: " + 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,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 System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.LK.Menu
{
public class SelectColorCommand : Command
{
public override string Name => "{\"button\":\"selectColor-";
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();
List<Data.Svetofor> categories = new List<Data.Svetofor>();
var row = new List<MessageKeyboardButton>();
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
var kbColor = KeyboardButtonColor.Positive;
try
{
string[] payload = update.@object.message.payload.Split('-');
int colorId = Convert.ToInt32(regex.Replace(payload[1], ""));
var user = db.Users.Single(usr => usr.chatId == chatId);
user.colorId = colorId;
db.SaveChanges();
msg = "📋Основное меню\n";
ShowMenuDostavka showMenuDostavka = new ShowMenuDostavka();
showMenuDostavka.Execute(update, client, db, msg, 2, 0);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectColorCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,64 @@
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 System.Linq;
namespace SvetoforVKBot.Models.Commands.LK.Menu
{
public class SelectDayMenuCommand : Command
{
public override string Name => "{\"button\":\"selectDayMenu-";
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();
List<Data.Svetofor> categories = new List<Data.Svetofor>();
var row = new List<MessageKeyboardButton>();
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
var kbColor = KeyboardButtonColor.Positive;
try
{
string[] payload = update.@object.message.payload.Split('-');
int curDay = Convert.ToInt32(regex.Replace(payload[1], ""));
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Меню";
user.day = curDay;
db.SaveChanges();
keyboardBuilder.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
msg = "📋Основное меню\n";
ShowMenuDostavka showMenuDostavka = new ShowMenuDostavka();
showMenuDostavka.Execute(update, client, db, msg, 2, 0);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectDayMenuCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,65 @@
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;
namespace SvetoforVKBot.Models.Commands.LK.Menu
{
public class SelectMenuCommand : Command
{
public override string Name => "{\"button\":\"selectMenu-";
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();
try
{
string[] payload = update.@object.message.payload.Split('-');
int curSubMenu = Convert.ToInt32(regex.Replace(payload[1], ""));
@params.Message = "📅На какой день показать меню? Выберите на клавиатуре\n";
keyboardBuilder
.AddButton("Сегодня", "selectDayMenu-8", KeyboardButtonColor.Positive)
.AddLine()
.AddButton("Пн", "selectDayMenu-1", KeyboardButtonColor.Primary)
.AddButton("Вт", "selectDayMenu-2", KeyboardButtonColor.Primary)
.AddButton("Ср", "selectDayMenu-3", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Чт", "selectDayMenu-4", KeyboardButtonColor.Primary)
.AddButton("Пт", "selectDayMenu-5", KeyboardButtonColor.Primary)
.AddButton("Сб", "selectDayMenu-6", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
//ShowMenuDostavka showMenuDostavka = new ShowMenuDostavka();
//showMenuDostavka.Execute(update, client, Con, msg, 2, curSubMenu);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectMenuCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,107 @@
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 Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.LK.Menu
{
public class SelectPersonalMenuCommand : Command
{
public override string Name => "{\"button\":\"selectPersonalMenu-";
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();
double sum = 0;
string backPL = "startPL";
int kkals = 0;
try
{
switch (DateTime.Now.DayOfWeek)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
keyboardBuilder
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
@params.Message = "Рекомендации по дневному меню доступны с понедельника по пятницу.\n" +
"Чтобы вернуться в Личный кабинет, нажмите кнопку \"Назад\"";
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return;
}
string[] payload = update.@object.message.payload.Split('-');
int foodType = Convert.ToInt32(regex.Replace(payload[1], ""));
int curDayKkal = Convert.ToInt32(regex.Replace(payload[2], ""));
var user = db.Users.Single(usr => usr.chatId == chatId);
var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);
foreach (var o in cartObject.orders)
{
sum += o.price * o.number;
kkals += o.kkal * o.number;
}
//keyboardBuilder
// .AddButton($"Завтрак (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-1-" + curDayKkal, KeyboardButtonColor.Primary)
// .AddLine()
// .AddButton($"Обед (до {Math.Round(curDayKkal * 1.2 * 0.4)} ккал)", "selectPersonalMenu-2-" + curDayKkal, KeyboardButtonColor.Primary)
// .AddLine()
// .AddButton($"Перекус (до {Math.Round(curDayKkal * 1.2 * 0.1)} ккал)", "selectPersonalMenu-3-" + curDayKkal, KeyboardButtonColor.Primary)
// .AddLine()
// .AddButton($"Ужин (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-4-" + curDayKkal, KeyboardButtonColor.Primary)
// .AddLine();
//if (cartObject.orders.Count > 0)
//{
// keyboardBuilder
// .AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default)
// .AddButton("Корзина: " + sum + " р", "selectCart-0", KeyboardButtonColor.Negative);
//}
//else
//{
// keyboardBuilder
// .AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
//}
////@params.Template = templateBuilder.Build();
//@params.Keyboard = keyboardBuilder.Build();
//@params.Message = "Если хотите подобрать блюда ещё раз, нажмите кнопку повторно😉";
//@params.UserId = chatId;
//@params.RandomId = GetRandomId();
//client.Messages.SendAsync(@params);
ShowPersonalMenuCarusel showPersonalMenu = new ShowPersonalMenuCarusel();
showPersonalMenu.Execute(update, client, db, foodType, 0, 1, curDayKkal);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectMenuCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,139 @@
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 VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Attachments;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.LK.Menu
{
public class ShowMenuDostavka
{
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, string msg, int plAction, int subMenu)
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
var ids = new long[] { chatId };
var user = client.Users.Get(ids);
string voronka = "";
double sum = 0;
string backPL = "";
List<CategoriesDostavka> categories = new List<CategoriesDostavka>();
var row = new List<MessageKeyboardButton>();
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
var kbColor = KeyboardButtonColor.Positive;
var keyboardBuilder = new KeyboardBuilder().Clear();
try
{
categories = db.CategoriesDostavkas.Where(c=>c.subMenu == subMenu).ToList().ConvertAll<CategoriesDostavka>(c =>
new CategoriesDostavka()
{
categoryId = c.categoryId,
inTheOrder = c.inTheOrder,
name = c.name,
btnName = c.btnName,
kbColor = c.kbColor,
});
//SqlCommand getCategories = new SqlCommand("SELECT * FROM CategoriesDostavka WHERE subMenu = @subMenu;", Con);
//getCategories.Parameters.AddWithValue("@subMenu", subMenu);
//SqlDataReader rgetCategories = getCategories.ExecuteReader();
//while (rgetCategories.Read())
// categories.Add(new CategoriesDostavka()
// {
// categoryId = Convert.ToInt32(rgetCategories["categoryId"]),
// inTheOrder = Convert.ToInt32(rgetCategories["inTheOrder"]),
// name = rgetCategories["name"].ToString(),
// btnName = rgetCategories["btnName"].ToString(),
// kbColor = rgetCategories["kbColor"].ToString(),
// });
//rgetCategories.Close();
categories.RemoveAll(c => c.inTheOrder.Equals(0));
categories.Sort((x, y) => x.inTheOrder.CompareTo(y.inTheOrder));
int btnCount = 0;
foreach (var c in categories)
{
switch (c.kbColor)
{
case "Default":
kbColor = KeyboardButtonColor.Default;
break;
case "Positive":
kbColor = KeyboardButtonColor.Positive;
break;
case "Negative":
kbColor = KeyboardButtonColor.Negative;
break;
case "Primary":
kbColor = KeyboardButtonColor.Primary;
break;
}
keyboardBuilder
.AddButton(c.btnName, "selectProduct-" + c.categoryId + "-0-1", kbColor);
btnCount += 1;
if (btnCount % 2 == 0)
{
keyboardBuilder.AddLine();
}
}
if (btnCount % 2 != 0)
{
keyboardBuilder.AddLine();
}
if (subMenu == 0)
{
backPL = "startPL";
}
else
backPL = "selectMenu-0";
keyboardBuilder
.AddButton("Назад", "selectMenu-0", KeyboardButtonColor.Default)
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
@params.UserId = chatId;
@params.Keyboard = keyboardBuilder.Build();
@params.Message = msg;
@params.DontParseLinks = true;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в ShowMenuDostavka: " + 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,430 @@
using Newtonsoft.Json;
using SvetoforVKBot.Models.Updates;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Security.Cryptography;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using VkNet.Utils;
using VkNet.Model.Template;
using VkNet.Model.Template.Carousel;
using System.Linq;
namespace SvetoforVKBot.Models.Commands.LK.Menu
{
public class ShowPersonalMenuCarusel
{
private const string PHOTOIDNEXT = "-194717824_457239273_446146426236760985";
//{"id": 457239273, "owner_id": -194717824, "access_key": "446146426236760985"}
public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, int curCategory, int curProduct, int curWay, double curDayKkal)
//curCategory - id Categories, curProduct - порядковый номер в массиве продуктов, curWay - для showProductCarusel направление навигации
{
MessagesSendParams @params = new MessagesSendParams();
var chatId = update.@object.message.from_id;
int i = 0;
int prevCatalog = 0, nextCatalog = 0;
int naviState = 0;
double sum = 0;
string desc = "";
int curDay = (int)DateTime.Now.DayOfWeek;
if (curDay == 0) curDay = 7;
List<CategoriesDostavka> categories = new List<CategoriesDostavka>();
List<ProductsDostavka> products = new List<ProductsDostavka>();
List<ProductsDostavka> allProducts = new List<ProductsDostavka>();
List<ProductsDostavka> randomFood = new List<ProductsDostavka>();
//List<ProductsDostavka> personalProducts = new List<ProductsDostavka>();
var row = new List<MessageKeyboardButton>();
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
TemplateBuilder templateBuilder = new TemplateBuilder();
CarouselElementAction carouselElementAction = new CarouselElementAction();
carouselElementAction.Type = CarouselElementActionType.OpenPhoto;
double belkiLow = 0, zhiryLow = 0, uglevodyLow = 0, belkiHigh = 0, zhiryHigh = 0, uglevodyHigh = 0;
double curBelki = 0, curZhiry = 0, curUglevody = 0;
double foodPercent = 0;
double belkiPercent = 0, zhiryPercent = 0, uglevodyPercent = 0;
double dayKkal = 0;
string foodTime = "";
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);
var choosenProducts = JsonConvert.DeserializeObject<List<int>>(user.choosenProducts);
List<int> sportDays = JsonConvert.DeserializeObject<List<int>>(user.sportDays);
//if (curDay == 8) curDay = (int)DateTime.Now.DayOfWeek;
int nextDay = curDay + 1;
if (nextDay == 8)
nextDay = 1;
foreach (var o in cartObject.orders)
{
sum += o.price * o.number;
}
categories = db.CategoriesDostavkas.ToList().ConvertAll<CategoriesDostavka>(c =>
new CategoriesDostavka()
{
categoryId = c.categoryId,
name = c.name,
btnName = c.btnName,
kbColor = c.kbColor,
});
allProducts = db.ProductsDostavkas.Where(p => p.categoryId != 0 &&
JsonConvert.DeserializeObject<List<int>>(p.weekDays).Exists(day => day == curDay)).
ToList().ConvertAll<ProductsDostavka>(e=>new ProductsDostavka()
{
id = e.id,
article = e.article,
colorId = e.colorId,
categoryId = e.categoryId,
name = e.name,
fullName = e.fullName,
descriptionCarousel = e.descriptionCarousel,
price = Convert.ToDouble(e.price),
photo = e.photo,
photoCarousel = e.photoCarousel,
kkal = e.kkal,
foodType = JsonConvert.DeserializeObject<List<int>>(e.foodType),
belki = Convert.ToDouble(e.belki),
zhiry = Convert.ToDouble(e.zhiry),
uglevody = Convert.ToDouble(e.uglevody),
});
ProductsDostavka water = new ProductsDostavka();
water = allProducts.Find(p => p.article.Equals("55"));
allProducts.Remove(water);
//allProducts.RemoveAll(p => !p.foodType.Contains(curCategory));
if (choosenProducts.Count > 0)
allProducts.RemoveAll(p => choosenProducts.Contains(p.id));
switch (user.track)
{
case 1:
belkiLow = 1.4;
belkiHigh = 2;
zhiryLow = 1;
zhiryHigh = 1.1;
uglevodyLow = 2.4;
uglevodyHigh = 3;
break;
case 2:
belkiLow = 1.2;
belkiHigh = 1.7;
zhiryLow = 0.9;
zhiryHigh = 1;
uglevodyLow = 2;
uglevodyHigh = 2.6;
break;
case 3:
belkiLow = 1.6;
belkiHigh = 2.2;
zhiryLow = 1.1;
zhiryHigh = 1.2;
uglevodyLow = 2.8;
uglevodyHigh = 3.4;
break;
}
switch (curCategory)
{
case 1:
allProducts.RemoveAll(p => p.categoryId == 1);
foodPercent = 0.3;
belkiPercent = 0.3;
uglevodyPercent = 0.4;
zhiryPercent = 0.2;
foodTime = "🥐Завтрак";
randomFood = allProducts.FindAll(ap => (ap.categoryId != 1) && ap.zhiry <= zhiryLow * user.weight * zhiryPercent && ap.uglevody <= uglevodyLow * user.weight * uglevodyPercent);
//Углеводы - 0.4
//Белки - 0.3
//Жиры - 0.2
//Кнопка ещё один вариант
//web
break;
case 2:
foodPercent = 0.4;
belkiPercent = 0.3;
uglevodyPercent = 0.3;
zhiryPercent = 0.4;
foodTime = "🍲Обед";
randomFood = allProducts.FindAll(ap => ap.categoryId == 1 && ap.zhiry <= zhiryLow * user.weight * zhiryPercent && ap.uglevody <= uglevodyLow * user.weight * uglevodyPercent);
break;
case 3:
allProducts.RemoveAll(p => p.categoryId == 1);
foodPercent = 0.1;
belkiPercent = 0.2;
uglevodyPercent = 0.2;
zhiryPercent = 0.2;
foodTime = "🥪Перекус";
//ap.categoryId == 5 || ap.categoryId == 4
randomFood = allProducts.FindAll(ap => (ap.categoryId != 1) && ap.zhiry <= zhiryLow * user.weight * zhiryPercent && ap.uglevody <= uglevodyLow * user.weight * uglevodyPercent);
break;
case 4:
allProducts.RemoveAll(p => p.categoryId == 1);
foodPercent = 0.3;
belkiPercent = 0.2;
uglevodyPercent = 0.2;
zhiryPercent = 0.2;
randomFood = allProducts.FindAll(ap => (ap.categoryId != 1) && ap.zhiry <= zhiryLow * user.weight * zhiryPercent && ap.uglevody <= uglevodyLow * user.weight * uglevodyPercent);
foodTime = "🥗Ужин";
break;
}
double maxKkal = Math.Round(curDayKkal * 1.2 * foodPercent);
double minKkal = Math.Round(curDayKkal * 0.9 * foodPercent);
Random rand = new Random();
if (choosenProducts.Count > 0)
randomFood.RemoveAll(p => choosenProducts.Contains(p.id));
int randomBludo = rand.Next(0, randomFood.Count);
if (curCategory == 3)
{
products.Add(randomFood.Find(rf => rf.kkal <= maxKkal));
}
else
{
products.Add(randomFood[randomBludo]);
}
curBelki = products[0].belki;
curZhiry = products[0].zhiry;
curUglevody = products[0].uglevody;
dayKkal = products[0].kkal;
choosenProducts.Add(products[0].id);
ProductsDostavka tmp = new ProductsDostavka();
for (i = 0; i < allProducts.Count; i++)
{
tmp = allProducts[i];
allProducts.RemoveAt(i);
allProducts.Insert(rand.Next(allProducts.Count), tmp);
}
foreach (var ap in allProducts)
{
//if (dayKkal + ap.kkal <= maxKkal) //curBelki <= belkiLow * weight * foodPercent && curUglevody + ap.uglevody < uglevodyHigh * weight * foodPercent)
if (curBelki + ap.belki <= belkiHigh * user.weight * belkiPercent &&
curUglevody + ap.uglevody <= uglevodyHigh * user.weight * uglevodyPercent)// &&
//curZhiry + ap.zhiry <= zhiryHigh * weight * zhiryPercent)
{
if (!products.Exists(p => p.categoryId == ap.categoryId))
{
if (true)//curUglevody + ap.uglevody < uglevodyHigh * weight * foodPercent curBelki < belkiHigh * weight * foodPercent && curZhiry < zhiryHigh * weight * foodPercent && curUglevody < uglevodyHigh * weight * foodPercent)
{
curBelki += ap.belki;
curZhiry += ap.zhiry;
curUglevody += ap.uglevody;
dayKkal += ap.kkal;
products.Add(ap);
choosenProducts.Add(ap.id);
}
}
}
//else break;
}
//if (dayKkal < minKkal)
//{
// if (curCategory != 3)
// {
// products.Add(allProducts.Find(ap => !choosenProducts.Contains(ap.id) && ap.zhiry <= zhiryLow * weight * zhiryPercent && ap.uglevody <= uglevodyLow * weight * uglevodyPercent && ap.categoryId != 7));
// curBelki += products[products.Count - 1].belki;
// curZhiry += products[products.Count - 1].zhiry;
// curUglevody += products[products.Count - 1].uglevody;
// dayKkal += products[products.Count - 1].kkal;
// choosenProducts.Add(products[products.Count - 1].id);
// }
// //else
// // products.Add(allProducts.Find(ap => !choosenProducts.Contains(ap.id) && ap.kkal <= maxKkal - minKkal));
// //choosenProducts.Add(products[products.Count - 1].id);
//}
if (!products.Exists(p => p.categoryId == 7))
products.Add(water);
//(p => p.article.Equals("55")))
//if (curCategory != 4)
//{
// SqlCommand updCart = new SqlCommand("UPDATE Users SET choosenProducts = @choosenProducts WHERE chatId = @chatId;", Con);
// updCart.Parameters.AddWithValue("@chatId", chatId);
// updCart.Parameters.AddWithValue("@choosenProducts", JsonConvert.SerializeObject(choosenProducts));
// updCart.ExecuteNonQuery();
//}
//else
//{
// SqlCommand updCart = new SqlCommand("UPDATE Users SET choosenProducts = @choosenProducts WHERE chatId = @chatId;", Con);
// updCart.Parameters.AddWithValue("@chatId", chatId);
// updCart.Parameters.AddWithValue("@choosenProducts", "[]");
// updCart.ExecuteNonQuery();
//}
nextCatalog = curProduct + 9;
prevCatalog = curProduct - 9;
if (curProduct > 0 && products.Count > 6)
{
if (nextCatalog > products.Count) nextCatalog = products.Count - (products.Count - curProduct);
if (prevCatalog < 0) prevCatalog = 0;
}
for (i = curProduct; i < products.Count; i++)
{
var jsPhoto = JsonConvert.DeserializeObject<CatalogPhotoObject>(products[i].photoCarousel);
desc = products[i].descriptionCarousel; //+ " " + products[i].weight;
if (desc.Length > 80) desc = desc.Substring(0, 77) + "..."; //desc.Substring(0, 77)
templateBuilder.AddTemplateElement(new CarouselElement()
{
Title = products[i].fullName,
Description = desc + " | " + products[i].kkal + " ккал\n" +
$"Б\\Ж\\У: {products[i].belki}г\\{products[i].zhiry}г\\{products[i].uglevody}г",
PhotoId = jsPhoto.owner_id + "_" + jsPhoto.id + "_" + jsPhoto.access_key,
Buttons = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton(){
Action = new MessageKeyboardButtonAction(){ Label = "Добавить в корзину " + products[i].price + "р",
Payload = "{\"button\":\"selectAddToCart-" + products[i].categoryId + "-" + products[i].id + "-" + curDayKkal + "\"}",
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Positive
},
//new MessageKeyboardButton(){
// Action = new MessageKeyboardButtonAction(){ Label = "Подробнее",
// Payload = "{\"button\":\"selectAddToCart-" + curCategory + "-" + i + "\"}",
// Type = KeyboardButtonActionType.Text },
// Color = KeyboardButtonColor.Default
//},
},
Action = carouselElementAction,
});
if (templateBuilder.Elements.Count == 9 && products.Count > 10)
break;
}
if (products.Count > 10)
{
switch (curWay)
{
case 1:
if (curProduct < (products.Count - 9))
naviState = 1;
else
naviState = 2;
break;
case 2:
if (curProduct == 0)
naviState = 1;
else
naviState = 2;
break;
default:
naviState = 2;
break;
}
switch (naviState)
{
case 1:
templateBuilder.AddTemplateElement(new CarouselElement()
{
Title = ".",
Description = ".",
PhotoId = PHOTOIDNEXT,
Buttons = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){ Label = ">> Следующие " + (products.Count - nextCatalog).ToString(),
Payload = "{\"button\":\"selectProduct-" + products[nextCatalog].categoryId + "-" + nextCatalog + "-1\"}",
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Primary
},
},
Action = carouselElementAction,
});
break;
case 2:
templateBuilder.AddTemplateElement(new CarouselElement()
{
Title = ".",
Description = ".",
PhotoId = PHOTOIDNEXT,
Buttons = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){ Label = "<< Предыдущие " + curProduct,
Payload = "{\"button\":\"selectProduct-" + products[prevCatalog].categoryId + "-" + prevCatalog + "-2\"}",
Type = KeyboardButtonActionType.Text },
Color = KeyboardButtonColor.Primary
},
},
Action = carouselElementAction,
});
break;
}
}
@params.Message = foodTime + "\n" +
"Калории: " + dayKkal + " ккал \n" +
$"Б\\Ж\\У: {curBelki}г\\{curZhiry}г\\{curUglevody}г \n\n" +
$"Если хотите подобрать блюда ещё раз, нажмите кнопку повторно😉";
@params.Template = templateBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в ShowProductCaruselMain: " + 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,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SvetoforVKBot.Data
{
public partial class Reports : IComparable<Reports>
{
public int CompareTo(Reports other) // Сделаем сравнение по максимальному id
{
return (id < other.id) ? -1 : (id > other.id) ? 1 : 0;
}
}
}

View File

@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
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;
namespace SvetoforVKBot.Models.Commands.LK.Reports
{
public class GetReportCommentCommand
{
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();
try
{
if (update.@object.message.text.Length > 0)
{
var ids = new long[] { chatId };
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Личный кабинет";
db.SaveChanges();
var report = db.Reports.Where(r=>r.chatId == chatId).Max();
report.comment = update.@object.message.text.Trim();
report.datetime = DateTime.Now;
report.state = 1;
keyboardBuilder
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.Message = "✅Отчет сохранён. Увидимся завтра!\n";
@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 = "‼Ошибка в GetReportCommentCommand: " + 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,58 @@
using System;
using System.Data.SqlClient;
using System.Linq;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.LK.Reports
{
public class SelectCreateReportCommand : Command
{
public override string Name => "{\"button\":\"selectCreateReport\"}";
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);
@params.Message = "✏Отчёт за " + DateTime.Now.ToShortDateString() + "\n\n" +
user.firstName + ", как Вы себя чувствуете?";
keyboardBuilder
.AddButton("😀", "selectReportRate-10", KeyboardButtonColor.Primary)
.AddButton("😐", "selectReportRate-5", KeyboardButtonColor.Primary)
.AddButton("🙁", "selectReportRate-1", 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 = "Ошибка в SelectCreateReportCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,68 @@
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 System.Linq;
namespace SvetoforVKBot.Models.Commands.LK.Reports
{
public class SelectReportCcalCommand : Command
{
public override string Name => "{\"button\":\"selectReportCcal-";
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();
try
{
string[] payload = update.@object.message.payload.Split('-');
int result = Convert.ToInt32(regex.Replace(payload[1], ""));
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Отчет - Комменнт";
db.SaveChanges();
var report = db.Reports.Where(r => r.chatId == chatId).Max();
report.result = result;
db.SaveChanges();
@params.Message = "Оставьте несколько слов о прошедшем дне😌";
keyboardBuilder
.AddButton("Пропустить", "Пропустить", 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 = "‼Ошибка в SelectReportCcalCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,73 @@
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 System.Linq;
namespace SvetoforVKBot.Models.Commands.LK.Reports
{
public class SelectReportRateCommand : Command
{
public override string Name => "{\"button\":\"selectReportRate-";
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();
try
{
string[] payload = update.@object.message.payload.Split('-');
int rate = Convert.ToInt32(regex.Replace(payload[1], ""));
var user = db.Users.Single(usr => usr.chatId == chatId);
db.Reports.Add(new Data.Reports()
{
chatId = chatId,
rate = rate,
datetime = DateTime.Now
});
db.SaveChanges();
@params.Message = "Ваша дневная норма: " + user.kkal + " ккал.\n" +
"Справились?";
keyboardBuilder
.AddButton("Меньше", "selectReportCcal-2", KeyboardButtonColor.Primary)
.AddButton("Норма", "selectReportCcal-1", KeyboardButtonColor.Positive)
.AddButton("Больше", "selectReportCcal-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 = "‼Ошибка в SelectReportRateCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,229 @@
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.LK
{
public class SelectDayFoodCommand : Command
{
public override string Name => "{\"button\":\"selectDayFood\"}";
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();
var keyboardBuilder2 = new KeyboardBuilder().Clear();
DateTime dt = DateTime.Now.AddHours(0);
List<OrderLog> orders = new List<OrderLog>();
string highWorkload = "0";
List<int> ids = new List<int>();
List<int> ids2 = new List<int>();
List<int> idsFood = new List<int>();
List<UserObject> waterNotifiesList = new List<UserObject>();
string msg = "";
string name = "";
int age = 0;
int genderCoef = 0;
double kkalResult = 0;
double colorPercent = 0;
double dayCoef = 0;
double curDayKkal = 0;
double kkalResultLow = 0;
double kkalResultHigh = 0;
try
{
switch (DateTime.Now.DayOfWeek)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
keyboardBuilder
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
@params.Message = "Рекомендации по дневному меню доступны с понедельника по пятницу.\n" +
"Чтобы вернуться в Личный кабинет, нажмите кнопку \"Назад\"";
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return;
}
var user = db.Users.Single(usr => usr.chatId == chatId);
user.choosenProducts = "[]";
user.cart = "{\"orders\":[]}";
db.SaveChanges();
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
tracks.Add(1, "Оптимизация питания");
tracks.Add(2, "Снижение жировой массы");
tracks.Add(3, "Увеличение мышечной массы");
tracks.Add(4, "Персональный режим");
keyboardBuilder.Clear();
var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);
if ((DateTime.Now.Month >= user.birthday.Month) && (DateTime.Now.Day >= user.birthday.Day))
age = DateTime.Now.Year - user.birthday.Year;
else
age = DateTime.Now.Year - user.birthday.Year - 1;
#region ccalCalculator
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, "Воскресенье");
Dictionary<int, string> gend = new Dictionary<int, string>(3);
gend.Add(0, "Мужской");
gend.Add(1, "Мужской");
gend.Add(2, "Женский");
int curDay = (int)DateTime.Now.DayOfWeek;
if (curDay == 0) curDay = 7;
int nextDay = curDay + 1;
if (nextDay == 8)
nextDay = 1;
//if (weight == 0 || height == 0)
//{
// keyboardBuilder
// .AddButton("📝Редактировать данные", "selectEditData-0", KeyboardButtonColor.Primary)
// .AddLine()
// .AddButton("Назад", "startPL", KeyboardButtonColor.Default);
// @params.Message = "Не хватает данных о росте/весе.\n" +
// "Нажмите \"📝Редактировать данные\" и заполните показатели.";
// @params.Keyboard = keyboardBuilder.Build();
// @params.UserId = chatId;
// @params.RandomId = GetRandomId();
// client.Messages.SendAsync(@params);
// return;
//}
if (user.gender == 1)
{
genderCoef = 5;
}
else
{
genderCoef = -161;
}
switch (user.track)
{
case 1: //не изменяя веса
colorPercent = 1;
break;
case 2:
colorPercent = 0.75; //1 - 15%
break;
case 3:
colorPercent = 1.2; //1 - 15%
break;
default:
colorPercent = 1;
break;
}
for (int i = 1; i <= 7; i++)
{
switch (i)
{
case 2:
dayCoef = 0.8;
break;
case 3:
dayCoef = 1.2;
break;
case 5:
dayCoef = 0.9;
break;
case 6:
dayCoef = 1.1;
break;
default:
dayCoef = 1;
break;
}
kkalResult = Math.Round((((10 * user.weight) + (6.25 * user.height) - (5 * age) + genderCoef) * user.activityCoef) * colorPercent * dayCoef);
kkalResultHigh = Math.Round(kkalResult * 1.2);
kkalResultLow = Math.Round(kkalResult * 0.9);
if (i == curDay)
//if (i == curDay)
{
curDayKkal = kkalResult;
}
}
#endregion ccalCalculator
//@params.Message = "🌙Добрый вечер!\n" +
// $"Ваша норма калорий на завтра: {Math.Round(curDayKkal * 0.9)} - {Math.Round(curDayKkal * 1.2)}\n" +
// "Мы подготовили для Вас блюда👇🏻";
@params.Message = //"☀Доброе утро!\n" +
$"Ваша норма калорий на сегодня: {Math.Round(curDayKkal * 0.9)} - {Math.Round(curDayKkal * 1.2)}\n" +
$"Мы подготовили для Вас блюда👇🏻\n\n";
keyboardBuilder
.AddButton($"Завтрак (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-1-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
.AddLine()
.AddButton($"Обед (до {Math.Round(curDayKkal * 1.2 * 0.4)} ккал)", "selectPersonalMenu-2-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
.AddLine()
.AddButton($"Перекус (до {Math.Round(curDayKkal * 1.2 * 0.1)} ккал)", "selectPersonalMenu-3-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
.AddLine()
.AddButton($"Ужин (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-4-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
//.SetInline();
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
Thread.Sleep(1500);
}
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,453 @@
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.LK
{
public class SelectEditDataCommand : Command
{
public override string Name => "{\"button\":\"selectEditData-";
public override 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();
Regex regex = new Regex("[^0-9]");
string tag = "";
string msgSports = "";
string strSportKind = "";
string sportName = "";
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Личный кабинет - Данные";
db.SaveChanges();
Dictionary<int, string> colors = new Dictionary<int, string>(3);
colors.Add(1, "🟩"); //З
colors.Add(2, "🟦"); //C
colors.Add(3, "🟨"); //Ж
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
tracks.Add(1, "Оптимизация питания");
tracks.Add(2, "Снижение жировой массы");
tracks.Add(3, "Увеличение мышечной массы");
tracks.Add(4, "Персональный режим");
Dictionary<int, string> notifies = new Dictionary<int, string>(4);
notifies.Add(1, "1 раз в день");
notifies.Add(3, "3 раза в день");
notifies.Add(4, "Более 3х раз в день");
notifies.Add(0, "Никогда");
int weight = user.weight;
int height = user.height;
int gender = user.gender;
int notifyCount = user.notifyCount;
string fio = user.fio;
var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);
var birthday = user.birthday;
int track = user.track;
int waterNotify = user.waterNotify;
int activityKind = user.activityKind;
int sportId = user.sportId;
keyboardBuilder
.AddButton("⚖Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
.AddButton("📐Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("🔔Уведомления", "selectEditData-3", KeyboardButtonColor.Primary)
.AddButton("✏ФИО", "selectEditData-4", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("📅Дата рождения", "selectEditData-5", KeyboardButtonColor.Primary)
.AddButton("📞Телефон", "selectEditData-6", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Режим питания", "selectEditData-7", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Вид спорта/активности", "selectEditData-8", KeyboardButtonColor.Primary)
.AddLine();
if (activityKind == 0 || activityKind == 3)
msgSports = "Ничем не занимаюсь";
else
{
msgSports = "";
var sport = db.SportKinds.Single(s => s.id == sportId);
sportName = sport.name;
int sportKind = sport.kind;
if (sportKind == 1) strSportKind = sportName + " (Спорт)";
else strSportKind = sportName + " (Физ. активность)";
}
if (waterNotify == 1)
{
keyboardBuilder
.AddButton("✅Напоминания о воде", "selectOffWaterNotify", KeyboardButtonColor.Positive);
}
else
{
keyboardBuilder
.AddButton("⛔Напоминания о воде", "selectGoWaterNotify", KeyboardButtonColor.Negative);
}
keyboardBuilder
.AddLine()
.AddButton("Готово", "startPL", KeyboardButtonColor.Default);
@params.Message = "РЕДАКТИРОВАНИЕ ДАННЫХ" +
"\n\n" +
"ФИО: " + fio +
"\n" +
"Телефон: " + jsPhones[0] +
"\n" +
"Дата рождения: " + birthday.ToShortDateString() +
"\n" +
"Рост: " + height + " см" +
"\n" +
"Вес: " + weight + " кг" +
"\n" +
colors[track] + "Выбранный трек: " + tracks[track] +
"\n" +
"Уведомления: " + notifies[notifyCount] +
"\n" +
$"Вид спорта/активности: {msgSports}{strSportKind}" +
"\n\n" +
"Выберите на клавиатуре показатель, который хотите изменить или нажмите \"Готово\"👇🏻";
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectEditDataCommand.Execute: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
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]");
string tag = "";
int startYear = DateTime.Now.Year - 18;
int i = 0;
int btnCount = 0;
int btnLines = 0;
string msgSports = "";
string strSportKind = "";
string sportName = "";
try
{
string[] payload = update.@object.message.payload.Split('-');
int curOption = Convert.ToInt32(regex.Replace(payload[1], ""));
Dictionary<int, string> notifies = new Dictionary<int, string>(4);
notifies.Add(1, "1 раз в день");
notifies.Add(3, "3 раза в день");
notifies.Add(4, "Более 3х раз в день");
notifies.Add(0, "Никогда");
Dictionary<int, string> colors = new Dictionary<int, string>(3);
colors.Add(1, "🟩"); //З
colors.Add(2, "🟦"); //C
colors.Add(3, "🟨"); //Ж
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
tracks.Add(1, "Оптимизация питания");
tracks.Add(2, "Снижение жировой массы");
tracks.Add(3, "Увеличение мышечной массы");
tracks.Add(4, "Персональный режим");
var user = db.Users.Single(usr => usr.chatId == chatId);
int weight = user.weight;
int height = user.height;
int gender = user.gender;
int notifyCount = user.notifyCount;
string fio = user.fio;
var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);
var birthday = user.birthday;
int track = user.track;
int waterNotify = user.waterNotify;
int activityKind = user.activityKind;
int sportId = user.sportId;
switch (curOption)
{
case 0:
tag = "Личный кабинет - Данные";
keyboardBuilder
.AddButton("⚖Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
.AddButton("📐Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("🔔Уведомления", "selectEditData-3", KeyboardButtonColor.Primary)
.AddButton("✏ФИО", "selectEditData-4", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("📅Дата рождения", "selectEditData-5", KeyboardButtonColor.Primary)
.AddButton("📞Телефон", "selectEditData-6", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Режим питания", "selectEditData-7", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Вид спорта/активности", "selectEditData-8", KeyboardButtonColor.Primary)
.AddLine();
if (activityKind == 0)
msgSports = "Ничем не занимаюсь";
else
{
msgSports = "";
var sport = db.SportKinds.Single(s => s.id == sportId);
sportName = sport.name;
int sportKind = sport.kind;
if (sportKind == 1) strSportKind = sportName + " (Спорт)";
else strSportKind = sportName + " (Физ. активность)";
}
if (waterNotify >= 1 && waterNotify != 10)
{
keyboardBuilder
.AddButton("✅Напоминания о воде", "selectOffWaterNotify", KeyboardButtonColor.Positive);
}
else
{
keyboardBuilder
.AddButton("⛔Напоминания о воде", "selectGoWaterNotify", KeyboardButtonColor.Negative);
}
keyboardBuilder
.AddLine()
.AddButton("Готово", "startPL", KeyboardButtonColor.Default);
@params.Message = "РЕДАКТИРОВАНИЕ ДАННЫХ" +
"\n\n" +
"ФИО: " + fio +
"\n" +
"Телефон: " + jsPhones[0] +
"\n" +
"Дата рождения: " + birthday.ToShortDateString() +
"\n" +
"Рост: " + height + " см" +
"\n" +
"Вес: " + weight + " кг" +
"\n" +
colors[track] + "Выбранный трек: " + tracks[track] +
"\n" +
"Уведомления: " + notifies[notifyCount] +
"\n" +
$"Вид спорта/активности: {msgSports}{strSportKind}" +
"\n\n" +
"Выберите на клавиатуре показатель, который хотите изменить или нажмите \"Готово\"👇🏻";
break;
case 1:
tag = "Личный кабинет - Изменить вес";
keyboardBuilder
//.AddButton("Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
//.AddLine()
//.AddButton("Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
//.AddLine()
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
@params.Message = "Введите свой вес в кг. Например, 65.\n\n" +
"⚠ Лучшее время для измерения веса - утро. Взвешиваться следует после утренних процедур и до приёма пищи."; //❕
break;
case 2:
tag = "Личный кабинет - Изменить рост";
keyboardBuilder
//.AddButton("Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
//.AddLine()
//.AddButton("Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
//.AddLine()
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
@params.Message = "Введите свой рост в см. Например, 168.";
break;
case 3:
tag = "Личный кабинет - Уведомления";
keyboardBuilder
.AddButton("Раз в день", "selectEditNotifyCount-1", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Три раза в день", "selectEditNotifyCount-3", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Более 3х раз", "selectEditNotifyCount-4", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Никогда", "selectEditNotifyCount-0", KeyboardButtonColor.Default)
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
@params.Message = "Как часто Вы готовы получать напоминания от чат-бота?\n\n" +
"Вы будете получать уведомления о приёмах пищи и воды. Если Вы хотите сформировать привычку " +
"по режиму питания или употреблению достаточного количества воды, выберите вариант \"Более 3х раз\".\n" +
"Наш чат-бот не будет рассылать рекламу или спам. Только персональные уведомления и рекомендации по здоровому питанию.";
break;
case 4:
tag = "Личный кабинет - ФИО";
keyboardBuilder
//.AddButton("Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
//.AddLine()
//.AddButton("Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
//.AddLine()
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
@params.Message = "Введите фамилию, имя и отчество одним сообщением.\n\nНапример: Иванов Иван Иванович";
break;
case 5:
tag = "Личный кабинет - ДР - Год";
@params.Message = "Выберите на клавиатуре внизу или введите свой год рождения, например 1993. \n";
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("Назад", "selectEditData-0", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder
.Build();
break;
case 6:
tag = "Личный кабинет - Телефон";
keyboardBuilder
//.AddButton("Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
//.AddLine()
//.AddButton("Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
//.AddLine()
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
@params.Message = "Напишите номер телефона в формате 11 цифр через \"8\" или \"7\" \n";
break;
case 7:
tag = "Личный кабинет - Режим питания";
//SqlCommand editTrack = new SqlCommand("UPDATE Users SET track = @track WHERE chatId = @chatId;", Con);
//editTrack.Parameters.AddWithValue("@chatId", chatId);
//editTrack.Parameters.AddWithValue("@track", 0);
//editTrack.ExecuteNonQuery();
@params.Message = "Выберите желаемый трек оптимизации питания👇🏻";
keyboardBuilder
.AddButton("🟩Оптимизация питания", "selectTrack-1", KeyboardButtonColor.Primary) //З🟩
.AddLine()
.AddButton("🟦Снижение жировой массы", "selectTrack-2", KeyboardButtonColor.Primary) //С🟦
.AddLine()
.AddButton("🟨Увеличение мыш. массы", "selectTrack-3", KeyboardButtonColor.Primary) //Ж🟨
.AddLine()
.AddButton("Персональный режим", "selectTrack-4", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
//keyboardBuilder
// //.AddButton("Вес: " + weight, "selectEditData-1", KeyboardButtonColor.Primary)
// //.AddLine()
// //.AddButton("Рост: " + height, "selectEditData-2", KeyboardButtonColor.Primary)
// //.AddLine()
// .AddButton("Назад", "selectEditData-0", KeyboardButtonColor.Default);
break;
case 8:
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("Назад", "selectEditData-0", KeyboardButtonColor.Default);
break;
}
user.tag = tag;
db.SaveChanges();
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectEditDataCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,59 @@
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.LK
{
public class SelectPersonalPlanCommand : Command
{
public override string Name => "{\"button\":\"selectPersonalPlan\"}";
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();
List<UserObject> users = new List<UserObject>();
List<int> chatIds = new List<int>();
string name = "";
try
{
@params.Message = "Ваш персональный план:\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 = "Ошибка в SelectPersonalPlanCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,214 @@
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.LK
{
public class ShowLKCommand
{
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<StackObject> techStack = new List<StackObject>();
string msg = "";
int age = 0;
string genderStr = "";
double indexMT = 0;
string IMT = "";
double kkalLow = 0;
double kkalHigh = 0;
try
{
msg = "📌Личный кабинет\n";
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Личный кабинет";
user.day = 0;
user.colorId = 0;
db.SaveChanges();
msg += user.fio + "\n\n";
if ((DateTime.Now.Month >= user.birthday.Month) && (DateTime.Now.Day >= user.birthday.Day))
age = DateTime.Now.Year - user.birthday.Year;
else
age = DateTime.Now.Year - user.birthday.Year - 1;
Dictionary<int, string> colors = new Dictionary<int, string>(3);
colors.Add(1, "🟩"); //З
colors.Add(2, "🟦"); //C
colors.Add(3, "🟨"); //Ж
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
tracks.Add(1, "Оптимизация питания");
tracks.Add(2, "Снижение жировой массы");
tracks.Add(3, "Увеличение мышечной массы");
tracks.Add(4, "Персональный режим");
//if (personal == 1)
//{
// keyboardBuilder
// .AddButton("✅Персональный режим", "selectPersonalPlan", KeyboardButtonColor.Positive)
// .AddLine();
//}
if (user.track == 0)
{
msg += "Выберите желаемый трек оптимизации питания👇🏻";
keyboardBuilder
.AddButton("🟩Оптимизация питания", "selectTrack-1", KeyboardButtonColor.Primary) //З🟩
.AddLine()
.AddButton("🟦Снижение жировой массы", "selectTrack-2", KeyboardButtonColor.Primary) //С🟦
.AddLine()
.AddButton("🟨Увеличение мыш. массы", "selectTrack-3", KeyboardButtonColor.Primary) //Ж🟨
.AddLine()
.AddButton("Персональный режим", "selectTrack-4", KeyboardButtonColor.Primary);
}
else
{
if (user.gender == 1)
genderStr = "Мужчина";
else
genderStr = "Женщина";
if (user.weight != 0 && user.height != 0)
{
indexMT = Math.Round(user.weight / (double)(user.height / 100.0 * user.height / 100.0), 1);
IMT = "Индекс массы тела: " + indexMT + " кг/м2 \n";
if (indexMT < 18.5)
IMT += "🔴 Дефицит" + "\n" +
"Риск сопутствующих заболеваний: Низкий (повышен риск других заболеваний)";
else if (indexMT >= 18.5 && indexMT < 25)
IMT += "✅ Норма" + "\n" +
"Риск сопутствующих заболеваний: Обычный";
else if (indexMT >= 25 && indexMT < 30)
IMT += "⚠ Избыточная масса тела" + "\n" +
"Риск сопутствующих заболеваний: Повышенный";
else if (indexMT >= 30 && indexMT < 35)
IMT += "🔴 Ожирение I степени" + "\n" +
"Риск сопутствующих заболеваний: Высокий";
else if (indexMT >= 35 && indexMT < 40)
IMT += "🔴 Ожирение II степени" + "\n" +
"Риск сопутствующих заболеваний: Очень высокий";
else
IMT += "🔴 Ожирение III степени" + "\n" +
"Риск сопутствующих заболеваний: Чрезвычайно высокий";
}
else
{
IMT = "⚠Индекс массы тела: не рассчитан (укажите рост и вес в разделе \"Редактировать данные\").";
}
msg += "🧬Показатели здоровья\n" +
"Вес: " + user.weight + " кг" +
"\n" +
"Рост: " + user.height + " см" +
"\n" +
"Возраст: " + age +
"\n" +
"Пол: " + genderStr +
"\n\n" +
IMT +
"\n\n";
if (user.kkal != 0)
{
kkalLow = Math.Round(user.kkal * 0.9);
kkalHigh = Math.Round(user.kkal * 1.2);
msg += $"Норма на сегодня: {kkalLow}-{kkalHigh} ккал";
}
else
msg += "⚠Норма ккал на сегодня: не рассчитана (воспользуйтесь калькулятором калорий).";
if (user.kkal == 0 || user.height == 0 || user.weight == 0)
{
keyboardBuilder
//.AddButton("📊Отправить отчёт", "selectCreateReport", KeyboardButtonColor.Positive)
//.AddLine()
.AddButton("📝Редактировать данные", "selectEditData-0", KeyboardButtonColor.Positive)
.AddLine()
.AddButton("🧮Калькулятор калорий", "selectCalcCcalResult-" + user.track, KeyboardButtonColor.Primary)
.AddLine()
.AddButton("⭐Рекомендации", "selectTrack-" + user.track, KeyboardButtonColor.Primary)
//.AddLine()
//.AddButton("⭐Идеальный вес", "selectIdealWeight", KeyboardButtonColor.Primary)
//.AddLine()
//.AddButton("📈Набор мышечной массы", "selectCalculatorCcal", KeyboardButtonColor.Primary)
//.AddLine()
//.AddButton("📋Меню", "selectMenu-0", KeyboardButtonColor.Primary)
//.AddLine()
.AddButton("💬Есть вопрос?", "selectConsultation", KeyboardButtonColor.Primary); //✏
}
else
{
keyboardBuilder
.AddButton("📊Отправить отчёт", "selectCreateReport", KeyboardButtonColor.Positive)
.AddLine()
.AddButton("🥗Дневной рацион", "selectDayFood", KeyboardButtonColor.Positive)
.AddLine()
.AddButton("📝Редактировать данные", "selectEditData-0", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("🧮Калькулятор калорий", "selectCalcCcalResult-" + user.track, KeyboardButtonColor.Primary)
.AddLine()
.AddButton("⭐Рекомендации", "selectTrack-" + user.track, KeyboardButtonColor.Primary)
//.AddLine()
//.AddButton("⭐Идеальный вес", "selectIdealWeight", KeyboardButtonColor.Primary)
//.AddLine()
//.AddButton("📈Набор мышечной массы", "selectCalculatorCcal", KeyboardButtonColor.Primary)
//.AddLine()
//.AddButton("📋Меню", "selectMenu-0", KeyboardButtonColor.Primary)
//.AddLine()
.AddButton("💬Есть вопрос?", "selectConsultation", KeyboardButtonColor.Primary); //✏
}
}
if (chatId == 59111081 || chatId == 10160301 || chatId == 369217524 || chatId == 178385801)
{
keyboardBuilder
.AddLine()
.AddButton("Администратору", "selectAdminMenu", KeyboardButtonColor.Default);
}
@params.Message = msg;
@params.UserId = chatId;
@params.Keyboard = keyboardBuilder.Build();
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в ShowLKCommnad: " + 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,126 @@
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.LK.SportsLK
{
public class ShowSportsLKCommand
{
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<StackObject> techStack = new List<StackObject>();
string msg = "";
int age = 0;
string genderStr = "";
double indexMT = 0;
string IMT = "";
try
{
msg = "📌Личный кабинет\n";
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Личный кабинет";
user.day = 0;
user.colorId = 0;
db.SaveChanges();
//SqlCommand getUser = new SqlCommand("SELECT * FROM Users WHERE chatId = @chatId;", Con);
//getUser.Parameters.AddWithValue("@chatId", chatId);
//SqlDataReader rgetUser = getUser.ExecuteReader();
//rgetUser.Read();
//string fio = rgetUser["fio"].ToString();
//int weight = Convert.ToInt32(rgetUser["weight"]);
//int height = Convert.ToInt32(rgetUser["height"]);
//int gender = Convert.ToInt32(rgetUser["gender"]);
//var birthday = DateTime.Parse(rgetUser["birthday"].ToString());
//int kkal = Convert.ToInt32(rgetUser["kkal"]);
//rgetUser.Close();
msg += user.fio + "\n\n";
age = (DateTime.Today.Year - user.birthday.Year);
if (user.gender == 1)
genderStr = "Мужчина";
else
genderStr = "Женщина";
msg += "🧬Показатели здоровья\n" +
"Вес: " + user.weight + " кг" +
"\n" +
"Рост: " + user.height + " см" +
"\n" +
"Возраст: " + age +
"\n" +
"Пол: " + genderStr +
"\n\n" +
IMT +
"\n\n";
if (user.kkal != 0)
msg += "Норма ккал на сегодня: " + user.kkal;
else
msg += "Норма ккал на сегодня: не рассчитана";
keyboardBuilder
.AddButton("📊Отправить отчёт", "selectCreateReport", KeyboardButtonColor.Positive)
.AddLine()
.AddButton("📝Редактировать данные", "selectEditData-0", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("📈Набор мышечной массы", "selectCalculatorCcal", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("📋Меню", "selectMenu-0", KeyboardButtonColor.Primary)
//.AddLine()
.AddButton("💬Консультация", "selectConsultation", KeyboardButtonColor.Primary); //✏
if (chatId == 59111081)
{
keyboardBuilder
.AddLine()
.AddButton("Администратору", "selectAdminMenu", KeyboardButtonColor.Default);
}
@params.Message = msg;
@params.UserId = chatId;
@params.Keyboard = keyboardBuilder.Build();
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в ShowSportsLKCommnad: " + 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 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.LK.Tracks
{
public class SelectChooseTrackCommand : Command
{
public override string Name => "{\"button\":\"selectChooseTrack-";
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 colorPercent = 0;
double dayCoef = 0;
double curDayKkal = 0;
try
{
string[] payload = update.@object.message.payload.Split('-');
int track = Convert.ToInt32(regex.Replace(payload[1], ""));
Dictionary<int, string> colors = new Dictionary<int, string>(3);
colors.Add(1, "🟩"); //З
colors.Add(2, "🟦"); //C
colors.Add(3, "🟨"); //Ж
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
tracks.Add(1, "Оптимизация питания");
tracks.Add(2, "Снижение жировой массы");
tracks.Add(3, "Увеличение мышечной массы");
tracks.Add(4, "Персональный режим");
var user = db.Users.Single(usr => usr.chatId == chatId);
user.track = track;
db.SaveChanges();
/*
SqlCommand getUser = new SqlCommand("SELECT * FROM Users WHERE chatId = @chatId;", Con);
getUser.Parameters.AddWithValue("@chatId", chatId);
SqlDataReader rgetUser = getUser.ExecuteReader();
rgetUser.Read();
string fio = rgetUser["fio"].ToString();
int weight = Convert.ToInt32(rgetUser["weight"]);
int height = Convert.ToInt32(rgetUser["height"]);
int gender = Convert.ToInt32(rgetUser["gender"]);
var birthday = DateTime.Parse(rgetUser["birthday"].ToString());
var activityCoef = Convert.ToDouble(rgetUser["activityCoef"]);
List<int> sportDays = JsonConvert.DeserializeObject<List<int>>(rgetUser["sportDays"].ToString());
rgetUser.Close();
age = (DateTime.Today.Year - birthday.Year);
*/
@params.Message = $"{colors[track]} Вы выбрали трек {tracks[track]}! В личном кабинете для Вас доступны рекомендации и калькулятор калорий.";
//keyboardBuilder
// .AddButton("💬Консультация", "selectLiveConsultation", KeyboardButtonColor.Primary)
// .AddLine()
// //.AddButton(cons, "selectGotConsultation", KeyboardButtonColor.Primary)
// //.AddLine()
// .AddButton("Назад", "selectCalculatorCcal", KeyboardButtonColor.Default);
keyboardBuilder
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Positive);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectChooseTrackCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,316 @@
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.LK.Tracks
{
public class SelectExampleMenuCommand : Command
{
public override string Name => "{\"button\":\"selectExampleMenu-";
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 colorPercent = 0;
double dayCoef = 0;
double curDayKkal = 0;
double kkalResultLow = 0;
double kkalResultHigh = 0;
try
{
string[] payload = update.@object.message.payload.Split('-');
int track = Convert.ToInt32(regex.Replace(payload[1], ""));
Dictionary<int, string> colors = new Dictionary<int, string>(3);
colors.Add(1, "🟩"); //З
colors.Add(2, "🟦"); //C
colors.Add(3, "🟨"); //Ж
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
tracks.Add(1, "Оптимизация питания");
tracks.Add(2, "Снижение жировой массы");
tracks.Add(3, "Увеличение мышечной массы");
tracks.Add(4, "Персональный режим");
var user = db.Users.Single(usr => usr.chatId == chatId);
List<int> sportDays = JsonConvert.DeserializeObject<List<int>>(user.sportDays);
//SqlCommand getUser = new SqlCommand("SELECT * FROM Users WHERE chatId = @chatId;", Con);
//getUser.Parameters.AddWithValue("@chatId", chatId);
//SqlDataReader rgetUser = getUser.ExecuteReader();
//rgetUser.Read();
////string fio = rgetUser["fio"].ToString();
//int choosenTrack = Convert.ToInt32(rgetUser["track"]);
//int height = Convert.ToInt32(rgetUser["height"]);
//int weight = Convert.ToInt32(rgetUser["weight"]);
//int gender = Convert.ToInt32(rgetUser["gender"]); // 1 - М / 2 - Ж
//var birthday = DateTime.Parse(rgetUser["birthday"].ToString());
//var activityCoef = Convert.ToDouble(rgetUser["activityCoef"]);
//List<int> sportDays = JsonConvert.DeserializeObject<List<int>>(rgetUser["sportDays"].ToString());
//rgetUser.Close();
//age = (DateTime.Today.Year - birthday.Year);
if ((DateTime.Now.Month >= user.birthday.Month) && (DateTime.Now.Day >= user.birthday.Day))
age = DateTime.Now.Year - user.birthday.Year;
else
age = DateTime.Now.Year - user.birthday.Year - 1;
#region ccalCalculator
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, "Воскресенье");
Dictionary<int, string> gend = new Dictionary<int, string>(3);
gend.Add(0, "Мужской");
gend.Add(1, "Мужской");
gend.Add(2, "Женский");
int curDay = (int)DateTime.Now.DayOfWeek;
if (curDay == 0) curDay = 7;
if (user.weight == 0 || user.height == 0)
{
keyboardBuilder
.AddButton("📝Редактировать данные", "selectEditData-0", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
@params.Message = "Не хватает данных о росте/весе.\n" +
"Нажмите \"📝Редактировать данные\" и заполните показатели.";
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return;
}
if (user.gender == 1)
{
genderCoef = 5;
}
else
{
genderCoef = -161;
}
switch (track)
{
case 1: //не изменяя веса
colorPercent = 1;
break;
case 2:
colorPercent = 0.75; //1 - 15%
break;
case 3:
colorPercent = 1.2; //1 - 15%
break;
default:
colorPercent = 1;
break;
}
for (int i = 1; i <= 7; i++)
{
switch (i)
{
case 2:
dayCoef = 0.8;
break;
case 3:
dayCoef = 1.2;
break;
case 5:
dayCoef = 0.9;
break;
case 6:
dayCoef = 1.1;
break;
default:
dayCoef = 1;
break;
}
kkalResult = Math.Round((((10 * user.weight) + (6.25 * user.height) - (5 * age) + genderCoef) * user.activityCoef) * colorPercent * dayCoef);
kkalResultHigh = Math.Round(kkalResult * 1.2);
kkalResultLow = Math.Round(kkalResult * 0.9);
if (i == curDay)
{
//@params.Message += $"⭐ {days[i]}: {kkalResultLow}-{kkalResultHigh} ккал\n";
curDayKkal = kkalResult;
}
//else
//@params.Message += $"{days[i]}: {kkalResultLow}-{kkalResultHigh} ккал\n";
}
#endregion ccalCalculator
double belki_opt = 0;
double zhiry_opt = 0;
double uglevody_opt = 0;
switch (track)
{
case 1:
//Распределение объема пищи в течение дня должно быть следующим: завтрак 20-30%, обед 30-40%, полдник 5-10%, ужин 20-30%.
//В рационе питания должно быть на килограмм массы тела: белков 1,4-2,0 грамма, жиров 1,0-1,1 грамма и углеводов 2,4-3,0 грамма.
@params.Message =
"Примерное меню" +
"\n\n" +
$"Пол: {gend[user.gender]} | Возраст: {age}\n" +
$"Рост: {user.height} см | Масса тела: {user.weight} кг\n\n" +
//"Активность: низкая (1-3 тренировки в неделю)\n" +
$"Рекомендуемая норма КБЖУ:\n" +
$"Калории {curDayKkal*0.9} - {curDayKkal*1.2}\n" +
$"Белки {user.weight *1.4}-{user.weight *2} грамм\n" +
$"Жиры {user.weight}-{user.weight *1.1} грамм\n" +
$"Углеводы {user.weight *2.4}-{user.weight *3} грамм\n\n" +
$"Завтрак (Максимальное количество калорий {curDayKkal*0.3})\n" +
$"Белки {user.weight * 2 * 0.3}, Жиры - {user.weight * 1.1 * 0.3}, Углеводы {user.weight *3 * 0.3}.\n" +
$"Рисовая каша на молоке 310 грамм, яблоко 340 грамм, черный кофе без сахара 400 грамм\n\n" +
$"Обед (Максимальное количество калорий {curDayKkal * 0.4})\n" +
$"Белки {user.weight * 2 * 0.4}, Жиры - {user.weight * 1.1 * 0.4}, Углеводы {user.weight * 3 * 0.4}.\n" +
$"Борщ 380 грамм, бифштекс классический 90 грамм, картофельное пюре 120 грамм, винегрет 140 грамм, морс 220 грамм\n\n" +
$"Полдник (Максимальное количество калорий {curDayKkal * 0.1})\n" +
$"Белки {user.weight * 2 * 0.1}, Жиры - {user.weight * 1.1 * 0.1}, Углеводы {user.weight * 3 * 0.1}.\n" +
$"Творожная запеканка 130 грамм, сметана 20% 10 грамм, яйцо 80 грамм, апельсиновый сок 270 грамм\n\n" +
$"Ужин (Максимальное количество калорий {curDayKkal * 0.2})\n" +
$"Белки {user.weight * 2 * 0.2}, Жиры - {user.weight * 1.1 * 0.2}, Углеводы {user.weight * 3 * 0.2}.\n" +
$"Минтай отварной 290 грамм, рис белый вареный 80 грамм, салат из белокочанной капусты с морковью 120 грамм, чай зеленый без сахара 150 грамм\n" +
$"\n" +
//$"Всего: Калории 2083, Белки 124, Жиры 75, Углеводы 208\n\n" +
$"Блюда, рекомендованные для оптимизации питания, в комбинате общественного питания промаркированы зеленым цветом." +
$"\n\n" +
$"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
break;
case 2:
//Распределение объема пищи в течение дня должно быть следующим: завтрак 20-30%, обед 30-40%, полдник 5-10%, ужин 20-30%, второй завтрак (5-10%) и второй ужин (до 5%).
//В рационе питания должно быть на килограмм массы тела: белков 1,2 - 1,7 грамма, жиров 0,9 - 1,0 грамма и углеводов 2,0 - 2,6 грамма.
@params.Message =
"Примерное меню" +
"\n\n" +
$"Пол: {gend[user.gender]} | Возраст: {age}\n" +
$"Рост: {user.height} см | Масса тела: {user.weight} кг\n\n" +
//"Активность: низкая (1-3 тренировки в неделю)\n" +
$"Рекомендуемая норма КБЖУ:\n" +
$"Калории {curDayKkal * 0.9} - {curDayKkal * 1.2}\n" +
$"Белки {user.weight * 1.2}-{user.weight * 1.7} грамм\n" +
$"Жиры {user.weight *0.9}-{user.weight} грамм\n" +
$"Углеводы {user.weight * 2}-{user.weight * 2.6} грамм\n\n" +
$"Первый завтрак (Максимальное количество калорий {curDayKkal * 0.3})\n" +
$"Белки {user.weight * 1.7 * 0.3}, Жиры - {user.weight * 0.3}, Углеводы {user.weight * 2.6 * 0.3}.\n" +
$"Омлет 230 грамм, яблоко 300 грамм, черный кофе без сахара 400 грамм\n" +
$"Второй завтрак (Максимальное количество калорий {curDayKkal * 0.1}) " +
$"Белки {user.weight * 1.7 * 0.3}, Жиры - {user.weight * 0.3}, Углеводы {user.weight * 2.6 * 0.3}.\n" +
$"Сырники 110 грамм, сметана 20% 10 грамм, яйцо 70 грамм, апельсиновый сок 240 грамм\n\n" +
$"Обед (Максимальное количество калорий {curDayKkal * 0.4})\n" +
$"Белки {user.weight * 1.7 * 0.4}, Жиры - {user.weight * 0.4}, Углеводы {user.weight * 2.6 * 0.4}.\n" +
$"Борщ 340 грамм, семга стейк на гриле 120 грамм, рис белый вареный 80 грамм, салат из белокочанной капусты с морковью 180 грамм, хлеб зерновой 25 грамм, морс 200 грамм\n\n" +
$"Полдник (Максимальное количество калорий {curDayKkal * 0.05})\n" +
$"Белки {user.weight * 1.7 * 0.1}, Жиры - {user.weight * 0.1}, Углеводы {user.weight * 2.6 * 0.1}.\n" +
$"Творожная запеканка 130 грамм, сметана 20% 10 грамм, яйцо 80 грамм, апельсиновый сок 270 грамм\n\n" +
$"Ужин (Максимальное количество калорий {curDayKkal * 0.3})\n" +
$"Белки {user.weight * 1.7 * 0.2}, Жиры - {user.weight * 0.2}, Углеводы {user.weight * 2.6 * 0.2}.\n" +
"Говядина вареная 80 грамм, картофель вареный 90 грамм, салат цезарь с креветками 80 грамм, хлеб зерновой 25 грамм, чай черный без сахара 150 грамм\n\n" +
//"Всего: Калории 1904, Белки 101, Жиры 78, Углеводы 170" +
//"\n\n" +
"Блюда, рекомендованные для оптимизации питания, в комбинате общественного питания промаркированы зеленым цветом." +
"\n\n" +
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
break;
case 3:
@params.Message =
"Примерное меню" +
"\n\n" +
$"Пол: {gend[user.gender]} | Возраст: {age}\n" +
$"Рост: {user.height} см | Масса тела: {user.weight} кг\n\n" +
//"Активность: низкая (1-3 тренировки в неделю)\n" +
"Рекомендуемая норма КБЖУ: Калории 2474-2824 Белки 112-156 грамм, Жиры 77-84 грамм, Углеводы 196-238 грамм\n" +
"Первый завтрак (Максимальное количество калорий 677) Калории - 554, Белки 24, Жиры -24, Углеводы 60.\n" +
"Рисовая каша на молоке 370 грамм, яйцо 120 грамм, черный кофе без сахара 400 грамм\n" +
"Второй завтрак (Максимальное количество калорий 649) Калории - 618, Белки - 35, Жиры - 19, Углеводы 70\n" +
"Сырники 240 грамм, сметана 20% 10 грамм, апельсиновый сок 320 грамм\n" +
"Обед (Максимальное количество калорий 931) Калории - 837, Белки - 41, Жиры - 35, Углеводы - 84\n" +
"Борщ 400 грамм, стейк из филе куриного 120 грамм, гречневая каша 80 грамм, кетчуп 30 грамм, салат овощной 350 грамм, чай черный без сахара 150 грамм\n" +
"Ужин (Максимальное количество калорий 564) Калории - 447, Белки - 65, Жиры - 7, Углеводы 25\n" +
"Треска отварная 350 грамм, рис белый вареный 90 грамм, салат греческий 80 грамм, чай зеленый 150 грамм\n" +
"\n" +
"Всего: Калории 2456, Белки 165, Жиры 85, Углеводы 239" +
"\n\n" +
"Блюда, рекомендованные для оптимизации питания, в комбинате общественного питания промаркированы зеленым цветом." +
"\n\n" +
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
break;
}
if (track != 4 && user.track == 0)
{
keyboardBuilder
.AddButton(colors[track] + "Выбрать этот трек", "selectChooseTrack-" + track, KeyboardButtonColor.Positive)
.AddLine()
.AddButton("Рацион питания", "selectRation-" + track, KeyboardButtonColor.Primary)
//.AddButton("Примерное меню", "selectExampleMenu-" + track, KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Персональный режим", "selectTrack-4", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Назад", "selectTrack-" + track, KeyboardButtonColor.Default);
}
else if (track != 0 && user.track != 0)
{
keyboardBuilder
.AddButton("Рацион питания", "selectRation-" + track, KeyboardButtonColor.Primary)
//.AddButton("Примерное меню", "selectExampleMenu-" + track, KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Персональный режим", "selectTrack-4", 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 = "‼Ошибка в SelectExampleMenuCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,197 @@
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.LK.Tracks
{
public class SelectRationCommand : Command
{
public override string Name => "{\"button\":\"selectRation-";
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 colorPercent = 0;
double dayCoef = 0;
double curDayKkal = 0;
try
{
string[] payload = update.@object.message.payload.Split('-');
int track = Convert.ToInt32(regex.Replace(payload[1], ""));
Dictionary<int, string> colors = new Dictionary<int, string>(3);
colors.Add(1, "🟩"); //З
colors.Add(2, "🟦"); //C
colors.Add(3, "🟨"); //Ж
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
tracks.Add(1, "Оптимизация питания");
tracks.Add(2, "Снижение жировой массы");
tracks.Add(3, "Увеличение мышечной массы");
tracks.Add(4, "Персональный режим");
var user = db.Users.Single(usr => usr.chatId == chatId);
switch (track)
{
case 1:
@params.Message =
"Необходимо свести к минимуму в рационе питания:" +
"\n" +
"• жирное мясо;\n" +
"• майонез, сливочные соусы;\n" +
"• консервы и соления;\n" +
"• копчености;\n" +
"• фастфуд;\n" +
"• белый хлеб и выпечку;\n" +
"• кондитерские изделия;\n" +
"• пакетированные соки;\n" +
"• газированную воду;\n" +
"• лакомства из пакетов (чипсы, снеки, сухарики с добавками). " +
"\n\n" +
"Как можно чаще на столе должны быть:" +
"\n" +
"• свежие фрукты и овощи,\n" +
"• молочные продукты,\n" +
"• цельнозерновой хлеб,\n" +
"• белое мясо,\n" +
"• рыба и морепродукты,\n" +
"• каши,\n" +
"• свежевыжатые соки,\n" +
"• орехи и семечки, \n" +
"• сухофрукты,\n" +
"• яйца,\n" +
"• твердый сыр,\n" +
"• растительные масла (оливковое, льняное и т.д.)" +
"\n\n" +
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
break;
case 2:
@params.Message =
"Необходимо свести к минимуму в рационе питания:" +
"\n" +
"• жирное мясо;\n" +
"• майонез, сливочные соусы;\n" +
"• консервы и соления;\n" +
"• копчености;\n" +
"• фастфуд;\n" +
"• белый хлеб и выпечку;\n" +
"• кондитерские изделия;\n" +
"• пакетированные соки;\n" +
"• газированную воду;\n" +
"• лакомства из пакетов (чипсы, снеки, сухарики с добавками). " +
"\n\n" +
"Как можно чаще на столе должны быть:" +
"\n" +
"• свежие фрукты и овощи,\n" +
"• молочные продукты,\n" +
"• цельнозерновой хлеб,\n" +
"• белое мясо,\n" +
"• рыба и морепродукты,\n" +
"• каши,\n" +
"• свежевыжатые соки,\n" +
"• орехи и семечки, \n" +
"• сухофрукты,\n" +
"• яйца,\n" +
"• твердый сыр,\n" +
"• растительные масла (оливковое, льняное и т.д.)" +
"\n\n" +
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
break;
case 3:
@params.Message =
"Необходимо свести к минимуму в рационе питания:" +
"\n" +
"• жирное мясо;\n" +
"• майонез, сливочные соусы;\n" +
"• консервы и соления;\n" +
"• копчености;\n" +
"• фастфуд;\n" +
"• белый хлеб и выпечку;\n" +
"• кондитерские изделия;\n" +
"• пакетированные соки;\n" +
"• газированную воду;\n" +
"• лакомства из пакетов (чипсы, снеки, сухарики с добавками). " +
"\n\n" +
"Как можно чаще на столе должны быть:" +
"\n" +
"• свежие фрукты и овощи,\n" +
"• молочные продукты,\n" +
"• цельнозерновой хлеб,\n" +
"• белое мясо,\n" +
"• рыба и морепродукты,\n" +
"• каши,\n" +
"• свежевыжатые соки,\n" +
"• орехи и семечки, \n" +
"• сухофрукты,\n" +
"• яйца,\n" +
"• твердый сыр,\n" +
"• растительные масла (оливковое, льняное и т.д.)" +
"\n\n" +
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
break;
}
if (track != 4 && user.track == 0)
{
keyboardBuilder
.AddButton(colors[track] + "Выбрать этот трек", "selectChooseTrack-" + track, KeyboardButtonColor.Positive)
.AddLine()
.AddButton("Примерное меню", "selectExampleMenu-" + track, KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Персональный режим", "selectTrack-4", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Назад", "selectTrack-" + track, KeyboardButtonColor.Default);
}
else if (track != 0 && user.track != 0)
{
keyboardBuilder
//.AddButton("Рацион питания", "selectRation-" + track, KeyboardButtonColor.Primary)
.AddButton("Примерное меню", "selectExampleMenu-" + track, KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Персональный режим", "selectTrack-4", 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 = "‼Ошибка в SelectRationCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,199 @@
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.LK.Tracks
{
public class SelectTrackCommand : Command
{
public override string Name => "{\"button\":\"selectTrack-";
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 colorPercent = 0;
double dayCoef = 0;
double curDayKkal = 0;
try
{
string[] payload = update.@object.message.payload.Split('-');
int track = Convert.ToInt32(regex.Replace(payload[1], ""));
Dictionary<int, string> colors = new Dictionary<int, string>(3);
colors.Add(1, "🟩"); //З
colors.Add(2, "🟦"); //C
colors.Add(3, "🟨"); //Ж
Dictionary<int, string> tracks = new Dictionary<int, string>(7);
tracks.Add(1, "Оптимизация питания");
tracks.Add(2, "Снижение жировой массы");
tracks.Add(3, "Увеличение мышечной массы");
tracks.Add(4, "Персональный режим");
//SqlCommand updTag = new SqlCommand("UPDATE Users SET track = @track WHERE chatId = @chatId;", Con);
//updTag.Parameters.AddWithValue("@chatId", chatId);
//updTag.Parameters.AddWithValue("@track", track);
//updTag.ExecuteNonQuery();
var user = db.Users.Single(usr => usr.chatId == chatId);
//SqlCommand getUser = new SqlCommand("SELECT * FROM Users WHERE chatId = @chatId;", Con);
//getUser.Parameters.AddWithValue("@chatId", chatId);
//SqlDataReader rgetUser = getUser.ExecuteReader();
//rgetUser.Read();
//int choosenTrack = Convert.ToInt32(rgetUser["track"]);
//rgetUser.Close();
////age = (DateTime.Today.Year - birthday.Year);
switch (track)
{
case 1:
@params.Message =
"Рекомендации для поддержания массы тела:" +
"\n\n" +
"Режим питания: 3 - 4 разовое питание, из них 3 основных приема пищи (завтрак, обед и ужин) и 1 дополнительный прием.\n" +
"Распределение объема пищи в течение дня должно быть следующим: завтрак 20-30%, обед 30-40%, полдник 5-10%, ужин 20-30%.\n" +
"В рационе питания должно быть на килограмм массы тела: белков 1,4-2,0 грамма, жиров 1,0-1,1 грамма и углеводов 2,4-3,0 грамма." +
"\n\n" +
"Жмите \"Рацион питания\", чтобы увидеть список рекомендуемых и нерекомендуемых продуктов.\n" +
"\"Примерное меню\" поможет Вам составить персональное меню." +
"\n\n" +
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
break;
case 2:
@params.Message =
"Рекомендации для снижения жировой массы тела:" +
"\n\n" +
"Режим питания: 4 - 5 разового питание, из них 3 основных приема пищи (завтрак, обед и ужин) и 1-2 дополнительных приема.\n" +
"Распределение объема пищи в течение дня должно быть следующим: завтрак 20-30%, обед 30-40%, полдник 5-10%, ужин 20-30%, второй завтрак (5-10%) и второй ужин (до 5%).\n" +
"В рационе питания должно быть на килограмм массы тела: белков 1,2-1,7 грамма, жиров 0,9-1,0 грамма и углеводов 2,0-2,6 грамма." +
"\n\n" +
"Жмите \"Рацион питания\", чтобы увидеть список рекомендуемых и нерекомендуемых продуктов.\n" +
"\"Примерное меню\" поможет Вам составить персональное меню." +
"\n\n" +
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
break;
case 3:
@params.Message =
"Рекомендации для набора мышечной массы тела:" +
"\n\n" +
"Режим питания: 4 - 5 разового питание, из них 3 основных приема пищи (завтрак, обед и ужин) и 1-2 дополнительных приема.\n" +
"Распределение объема пищи в течение дня должно быть следующим: завтрак 20-30%, обед 30-40%, полдник 5-10%, ужин 20-30%, второй завтрак (5-10%) и второй ужин (до 5%).\n" +
"В рационе питания должно быть на килограмм массы тела: белков 1,6-2,2 грамма, жиров 1,1-1,2 грамма и углеводов 2,8-3,4 грамма." +
"\n\n" +
"Жмите \"Рацион питания\", чтобы увидеть список рекомендуемых и нерекомендуемых продуктов.\n" +
"\"Примерное меню\" поможет Вам составить персональное меню." +
"\n\n" +
"Если Вас не устраивает данный рацион и Вам необходима индивидуальная консультация специалиста, то выберете трек \"Персональный режим\"";
break;
case 4:
@params.Message =
"⚠Персональный режим определяется после консультации со специалистом.\n\n" +
"Консультация включает: \n\n" +
"- определение и оценка состава тела\n" +
"- коррекция рациона питания\n" +
"- оценка функционального состояния\n" +
"- психофизиологическое тестирование\n\n" +
"📍Консультации проводятся по субботам по адресу: г. Киров, ул. Молодой Гвардии, д.13.\n" +
"☎Тел. 70-81-22.\n" +
"Стоимость и условия по телефону. \n\n" +
"Специалист: Кадочникова Наталья Ивановна.\n\n" +
"Чтобы узнать подробнее, нажмите кнопку \"О специалисте\"\n\n" +
"Вы можете оформить заявку на запись. Для этого нажмите кнопку \"Оставить заявку\".\n" +
"Ваши данные будут отправлены менеджеру, с Вами свяжутся для уточнения даты и времени консультации.";
keyboardBuilder
.AddButton("Оставить заявку", "selectSubmitConsultation", KeyboardButtonColor.Positive)
.AddLine()
.AddButton("О специалисте", "selectMoreAboutSpec", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return;
}
//keyboardBuilder
// .AddButton("💬Консультация", "selectLiveConsultation", KeyboardButtonColor.Primary)
// .AddLine()
// //.AddButton(cons, "selectGotConsultation", KeyboardButtonColor.Primary)
// //.AddLine()
// .AddButton("Назад", "selectCalculatorCcal", KeyboardButtonColor.Default);
if (track != 4) // && choosenTrack == 0)
{
if (user.track != track)
{
keyboardBuilder
.AddButton(colors[track] + "Выбрать этот трек", "selectChooseTrack-" + track, KeyboardButtonColor.Positive)
.AddLine();
}
keyboardBuilder
.AddButton("Рацион питания", "selectRation-" + track, KeyboardButtonColor.Primary)
//.AddButton("Примерное меню", "selectExampleMenu-" + track, KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Персональный режим", "selectTrack-4", KeyboardButtonColor.Primary)
.AddLine()
.AddButton("Назад", "startPL", KeyboardButtonColor.Default);
}
//else if (track != 0 && choosenTrack != 0)
//{
// keyboardBuilder
// .AddButton("Рацион питания", "selectRation-" + track, KeyboardButtonColor.Primary)
// //.AddButton("Примерное меню", "selectExampleMenu-" + track, KeyboardButtonColor.Primary)
// .AddLine()
// .AddButton("Персональный режим", "selectTrack-4", 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 = "‼Ошибка в SelectTrackCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

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);
}
}
}

View File

@@ -0,0 +1,105 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Linq;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands
{
public class SelectAboutCommand : Command
{
public override string Name => "{\"button\":\"selectAbout\"}";
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();
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
int reg = user.reg;
@params.Message = "✒Росмолодежь — федеральный орган исполнительной власти, деятельность которого целиком сосредоточена на создании равных условий для самореализации нашего подрастающего поколения.\n\n" +
"Задача Росмолодежи сегодня состоит в создании максимального количества возможностей для самореализации молодых людей и, как следствие, эффективной реализации инновационного потенциала молодежи в обществе.";
Uri URL = new Uri("https://fadm.gov.ru/");
#region keyboard
var row = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){
Type = KeyboardButtonActionType.OpenLink,
Link = URL,
Label = "Официальный сайт",
Payload = "{\"button\":\"selectOpenLink\"}"
},
}
};
listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row));
if (reg == 0)
{
var row1 = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){
Label = "#ХочуВРосМол",
Payload = "{\"button\":\"selectRegistration\"}",
Type = KeyboardButtonActionType.Text},
Color = KeyboardButtonColor.Positive
},
};
listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row1));
}
var row3 = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){
Label = "⬅Назад",
Payload = "{\"button\":\"startPL\"}",
Type = KeyboardButtonActionType.Text},
Color = KeyboardButtonColor.Default
}
};
listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row3));
var buttons = new ReadOnlyCollection<ReadOnlyCollection<MessageKeyboardButton>>(listButtons);
var keyboard = new MessageKeyboard()
{
Buttons = buttons,
OneTime = false
};
#endregion keyboard
@params.Keyboard = keyboard;
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectAboutCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,53 @@
using System;
using System.Data.SqlClient;
using System.Linq;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands
{
public class SelectAskQuestionsCommand : Command
{
public override string Name => "{\"button\":\"selectAskQuestions\"}";
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();
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Вопрос";
db.SaveChanges();
keyboardBuilder
.AddButton("⬅Назад", "startPL", KeyboardButtonColor.Default)
.Build();
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.Message = "Запиши сюда свой вопрос одним сообщением. Я отправлю его специалисту.✌🏻";
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectAskQuestionsCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 System.Linq;
namespace SvetoforVKBot.Models.Commands
{
public class SelectRecallMeCommand : Command
{
public override string Name => "{\"button\":\"selectRecallMe\"}";
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();
int i = 0;
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
user.tag = "Перезвоните мне - Телефон";
db.SaveChanges();
var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);
if (jsPhones.Count > 0)
{
for (i = 0; i < jsPhones.Count && i < 4; i++)
{
keyboardBuilder
.AddButton(jsPhones[i], "selectSavedPhone-2-" + i, KeyboardButtonColor.Default)
.AddLine();
}
@params.Message = "Напишите мне свой номер телефона в формате 89123456789 или выберите из ранее введённых 😊👇";
}
else
{
@params.Message = "Напишите мне свой номер телефона в формате 89123456789 😊👇";
}
keyboardBuilder
.AddButton("⬅Назад", "startPL", KeyboardButtonColor.Default);
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в SelectRecallMeCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,240 @@
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.LK;
using SvetoforVKBot.Models.Commands.LK.SportsLK;
using System.Collections.ObjectModel;
using System.Linq;
namespace SvetoforVKBot.Models.Commands
{
public class StartCommand : Command
{
public override string Name => "Начать";
public override 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();
string tag = "";
string utm = "";
try
{
var ids = new long[] { chatId };
var user = client.Users.Get(ids, ProfileFields.Sex);
var gender = Convert.ToInt32(user[0].Sex);
var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
Uri URL = new Uri("https://www.vyatsu.ru/");
#region UTM
/*
utm = update.@object.message.@ref;
if (utm != "" && utm != null)
{
if (int.TryParse(utm, out int refer))
{
if (refer != chatId)
{
int referId = 1;
//Проверяем приглашали ли этого пользователя раннее
getUser = new SqlCommand("SELECT referId FROM Users WHERE chatId = @chatId;", Con);
getUser.Parameters.AddWithValue("@chatId", chatId);
rgetUser = getUser.ExecuteReader();
rgetUser.Read();
int uReferId = Convert.ToInt32(rgetUser["referId"]);
rgetUser.Close();
if (uReferId == 0) // 0 - не приглашали
{
//Ищем пользователя, который пригласил
SqlCommand getRefer = new SqlCommand("SELECT chatId FROM Users WHERE chatId = @refer;", Con);
getRefer.Parameters.AddWithValue("@refer", refer);
SqlDataReader rgetRefer = getRefer.ExecuteReader();
if (rgetRefer.HasRows) // если пользователь существует
{
rgetRefer.Close();
SqlCommand updReferId = new SqlCommand("UPDATE Users SET referId = @referId WHERE chatId = @chatId;", Con);
updReferId.Parameters.AddWithValue("@chatId", chatId);
updReferId.Parameters.AddWithValue("@referId", refer);
updReferId.ExecuteNonQuery();
selectQuestRoom.ExecutePL(update, client, Con);
return;
}
else
rgetRefer.Close();
}
else
{
selectQuestRoom.ExecutePL(update, client, Con);
return;
}
}
else
{
selectQuestRoom.ExecutePL(update, client, Con);
return;
}
}
SourceUpdate sourceUpdate = new SourceUpdate();
sourceUpdate.Execute(update, client, Con);
switch (utm)
{
case "afisha":
SelectEventsCommand selectEvents = new SelectEventsCommand();
selectEvents.ExecutePL(update, client, Con);
return;
case "quest":
selectQuestRoom.ExecutePL(update, client, Con);
return;
case "project":
SelectProjectOfficeCommand selectProjectOffice = new SelectProjectOfficeCommand();
selectProjectOffice.ExecutePL(update, client, Con);
return;
case "faq":
SelectOSCommand selectOS = new SelectOSCommand();
selectOS.ExecutePL(update, client, Con);
return;
}
}
*/
#endregion UTM
var getUser = db.Users.Single(usr => usr.chatId == chatId);
int reg = getUser.reg;
int admin = getUser.admin;
int activityKind = getUser.activityKind;
getUser.tag = "Старт";
db.SaveChanges();
switch (reg)
{
case 1:
if (activityKind == 2 || activityKind == 3)
{
ShowLKCommand showLK = new ShowLKCommand();
showLK.Execute(update, client, db);
}
else // спортсмены
{
ShowLKCommand showLK = new ShowLKCommand();
showLK.Execute(update, client, db);
//ShowSportsLKCommand showSportsLK = new ShowSportsLKCommand();
//showSportsLK.Execute(update, client, Con);
}
return;
default:
@params.Message = "Добрый день, " + user[0].FirstName + "!" +
"\n\n" +
"🍏Проект \"Здоровое питание\" это доступная возможность для каждого студента, сотрудника и любого желающего " +
"улучшить свою жизнь, здоровье и самочувствие." +
"\n\n" +
"👉🏻Проект направлен на формирование культуры правильного питания, мотивации к регулярным занятиям физическими упражнениями. " +
"Для участников проекта разработано меню правильного питания, будет осуществляться исследование морфофункционального " +
"состояния участников, разрабатываться комплекс физических упражнений." +
"\n\n" +
"💬Участники проекта будут обеспечены консультационной поддержкой от организаторов.";
//keyboardBuilder
// .AddButton("🚦Принять участие", "selectAgreement", KeyboardButtonColor.Positive); //✅ selectAgreement
//.AddLine()
var row2 = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){
Label = "🚦Принять участие",
Payload = "{\"button\":\"selectParticipate\"}", //selectAgreement
Type = KeyboardButtonActionType.Text},
Color = KeyboardButtonColor.Positive
}
};
listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row2)); //.AddButton("❔Вопросы и ответы", "selectInProgress", KeyboardButtonColor.Primary);
//var row = new List<MessageKeyboardButton>()
//{
// new MessageKeyboardButton() {
// Action = new MessageKeyboardButtonAction(){
// Type = KeyboardButtonActionType.OpenLink,
// Link = URL,
// Label = "Узнать подробнее",
// Payload = "{\"button\":\"selectOpenSheet\"}"
// },
// }
//};
//listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row));
if (chatId == 59111081 || chatId == 10160301 || chatId == 369217524 || chatId == 178385801)
{
var row3 = new List<MessageKeyboardButton>()
{
new MessageKeyboardButton() {
Action = new MessageKeyboardButtonAction(){
Type = KeyboardButtonActionType.Text,
Label = "Администратору",
Payload = "{\"button\":\"selectAdminMenu\"}"
},
Color = KeyboardButtonColor.Default
}
};
listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row3));
//keyboardBuilder
// .AddLine()
// .AddButton("Администратору", "selectAdminMenu", KeyboardButtonColor.Default);
}
var buttons = new ReadOnlyCollection<ReadOnlyCollection<MessageKeyboardButton>>(listButtons);
var keyboard = new MessageKeyboard()
{
Buttons = buttons,
OneTime = false
};
@params.Keyboard = keyboard;
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
return;
}
}
catch (Exception ee)
{
@params.Message = "‼Ошибка в StartCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands
{
public class StartLowerCommand : Command
{
public override string Name => "начать";
public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
var chatId = update.@object.message.from_id;
MessagesSendParams @params = new MessagesSendParams();
try
{
StartCommand start = new StartCommand();
start.Execute(update, client, db);
}
catch (Exception ee)
{
@params.Message = "Ошибка в StartLowerCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
{
}
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands
{
public class StartPLCommand : Command
{
public override string Name => "{\"button\":\"startPL\"}";
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();
try
{
StartCommand start = new StartCommand();
start.Execute(update, client, db);
}
catch (Exception ee)
{
@params.Message = "Ошибка в StartPLCommand: " + ee.Message;
@params.Attachments = null;
@params.Keyboard = null;
@params.UserId = 59111081;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
}
}
}

View File

@@ -0,0 +1,74 @@
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.Water
{
public class SelectGoWaterNotifyCommand : Command
{
public override string Name => "{\"button\":\"selectGoWaterNotify\"}";
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();
List<UserObject> users = new List<UserObject>();
List<int> chatIds = new List<int>();
string name = "";
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
user.waterNotify = 1;
db.SaveChanges();
//SqlCommand updUser = new SqlCommand("UPDATE Users SET waterNotify = 1 WHERE chatId = @chatId;", Con);
//updUser.Parameters.AddWithValue("@chatId", chatId);
//updUser.ExecuteNonQuery();
//@params.Message = "Отлично! Напоминания включены.\n" +
// "Самое время выпить воду😉";
@params.Message = "Сколько раз в день Вы готовы получать напоминания?";
keyboardBuilder
.AddButton("1", "selectWaterNotifyCount-1", KeyboardButtonColor.Primary)
.AddButton("3", "selectWaterNotifyCount-3", KeyboardButtonColor.Primary)
.AddButton("6", "selectWaterNotifyCount-6", KeyboardButtonColor.Primary)
.SetInline();
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectGoWaterNotifyCommand: " + 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,73 @@
using Newtonsoft.Json;
using SvetoforVKBot.Models.Commands.LK;
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 System.Threading;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Attachments;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace SvetoforVKBot.Models.Commands.Water
{
public class SelectOffWaterNotifyCommand : Command
{
public override string Name => "{\"button\":\"selectOffWaterNotify\"}";
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();
List<UserObject> users = new List<UserObject>();
List<int> chatIds = new List<int>();
string name = "";
try
{
var user = db.Users.Single(usr => usr.chatId == chatId);
user.waterNotify = 0;
db.SaveChanges();
@params.Message = "Напоминания отключены.\n" +
"Настроить напоминания можно в Личном кабинете, в разделе \"📝Редактировать данные\".";
keyboardBuilder
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Primary)
.SetInline();
@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
//Thread.Sleep(1500);
//SelectEditDataCommand selectEditData = new SelectEditDataCommand();
//selectEditData.Execute(update, client, Con);
//return;
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectOffWaterNotifyCommand: " + 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,90 @@
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.Water
{
public class SelectWaterNotifyCountCommand : Command
{
public override string Name => "{\"button\":\"selectWaterNotifyCount-";
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();
List<UserObject> users = new List<UserObject>();
List<int> chatIds = new List<int>();
string name = "";
Regex regex = new Regex("[^0-9]");
try
{
string[] payload = update.@object.message.payload.Split('-');
int count = Convert.ToInt32(regex.Replace(payload[1], ""));
var user = db.Users.Single(usr => usr.chatId == chatId);
user.waterNotify = count;
db.SaveChanges();
//SqlCommand updUser = new SqlCommand("UPDATE Users SET waterNotify = @waterNotify WHERE chatId = @chatId;", Con);
//updUser.Parameters.AddWithValue("@chatId", chatId);
//updUser.Parameters.AddWithValue("@waterNotify", count);
//updUser.ExecuteNonQuery();
if (count == 10)
{
@params.Message = "Хорошо! Мы не будем присылать Вам рассылку о воде.\n" +
"Если что-то изменится, данную функцию Вы можете подключить в Личном кабинете, в разделе \"Редактировать данные\"";
keyboardBuilder
.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Primary)
.SetInline();
@params.Keyboard = keyboardBuilder.Build();
}
else
@params.Message = "Отлично! Напоминания включены.\n" +
"Самое время выпить воду😉";
//@params.Message = "Сколько раз в день Вы готовы получать напоминания?";
//keyboardBuilder
// .AddButton("1", "selectWaterNotifyCount-1", KeyboardButtonColor.Primary)
// .AddButton("3", "selectWaterNotifyCount-2", KeyboardButtonColor.Primary)
// .AddButton("6", "selectWaterNotifyCount-3", KeyboardButtonColor.Primary)
// .SetInline();
//@params.Keyboard = keyboardBuilder.Build();
@params.UserId = chatId;
@params.RandomId = GetRandomId();
client.Messages.SendAsync(@params);
}
catch (Exception ee)
{
@params.Message = "Ошибка в SelectWaterNotifyCountCommand: " + 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)
{
}
}
}