-
Notifications
You must be signed in to change notification settings - Fork 0
/
UserCommandHandler.cs
92 lines (85 loc) · 3.35 KB
/
UserCommandHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using System;
using System.Collections.Generic;
using System.Linq;
using RestSharp;
using Spoofi.FreudBot.Data.Entities;
using Spoofi.FreudBot.Data.Services;
using Spoofi.FreudBot.Logic.Bot;
using Spoofi.FreudBot.Logic.Handlers.Interfaces;
using Message = Telegram.Bot.Types.Message;
namespace Spoofi.FreudBot.Logic.Handlers
{
public class UserCommandHandler : IUserCommandHandler
{
private readonly IDatabaseService _db;
private readonly IBotManager _bot;
private readonly IPermissionChecker _permissionChecker;
public UserCommandHandler(IDatabaseService databaseService, IBotManager botManager, IPermissionChecker permissionChecker)
{
_db = databaseService;
_bot = botManager;
_permissionChecker = permissionChecker;
}
public void AddCommand(Message message)
{
var text = message.Text.Split(' ').ToList();
switch (text.Count())
{
case 1:
case 2:
case 3:
_bot.SendText(message.Chat.Id, Responses.UserCommandHandler_AddCommand_UsingText);
break;
default:
var newCommand = new UserCommand
{
Command = text[1],
Type = text[2].ToLower() == "post" ? UserCommandType.PostRequest : UserCommandType.GetRequest,
ChatId = message.Chat.Id,
Url = text[3],
Data = GetData(text.Skip(4))
};
_db.SaveUserCommand(newCommand);
_bot.SendText(message.Chat.Id, string.Format(Responses.UserCommandHandler_AddCommand_SuccesfullyAddedCommand, text[1]));
break;
}
}
public bool Execute(Message message)
{
var userCommand = _db.GetCommandByChat(message.Chat.Id, message.Text);
if (userCommand == null) return false;
switch (userCommand.Type)
{
case UserCommandType.PostRequest:
case UserCommandType.GetRequest:
Execute(userCommand);
break;
}
_bot.SendText(message.Chat.Id, Responses.UserCommandHandler_Execute_SuccessRunCommand);
return true;
}
public IEnumerable<string> GetCommandsByChat(int chatId)
{
var commands = _db.GetCommandsByChat(chatId).Select(x => x.Command).ToList();
if (_permissionChecker.Check(chatId))
commands.Insert(0, "/add");
return commands;
}
private static void Execute(UserCommand userCommand)
{
var request = new RestRequest
{
Method = userCommand.Type == UserCommandType.PostRequest ? Method.POST : Method.GET
};
foreach (var parameter in userCommand.Data)
{
request.AddParameter(parameter.Key, parameter.Value);
}
new RestClient(new Uri(userCommand.Url)).Execute(request);
}
private static Dictionary<string, string> GetData(IEnumerable<string> parameters)
{
return parameters.ToDictionary(parameter => parameter.Split('|')[0], parameter => parameter.Split('|')[1]);
}
}
}