-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwebhook_11_keyboard.psgi
More file actions
107 lines (80 loc) · 2.18 KB
/
webhook_11_keyboard.psgi
File metadata and controls
107 lines (80 loc) · 2.18 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
use 5.010;
use strict;
use Data::Dumper;
use JSON;
use Bot;
my $bot = Bot::bot();
my %currency = (
LEI => 1,
EUR => 4.45621098,
USD => 3.95439788,
);
return main_app();
sub main_app {
my $app = sub {
my $env = shift;
my $status = 200;
my $headers = [
'Content-Type' => 'text/plain',
];
my $body = '';
my $path = $env->{PATH_INFO};
my $input = $env->{'psgi.input'};
my $json = join '', <$input>;
my $data = from_json($json);
say Dumper($data);
process_message($data) if $data->{message};
return [$status, $headers, [$body]];
};
return $app;
}
sub process_message {
my ($data) = @_;
my $message = $data->{message};
my $text = $message->{text};
my $chat_id = $message->{chat}{id};
my ($amount, $currency_from, $currency_to) = $text =~ /([\d.]+)\s*(\w+)(?:\s+(?:to|in)\s+(\w+))?/;
$currency_from = uc $currency_from;
$currency_to = uc $currency_to;
if ($amount && $currency_from && $currency_to) {
convert($chat_id, $amount, $currency_from, $currency_to);
}
elsif ($amount && $currency_from) {
refine($chat_id, $amount, $currency_from);
}
else {
usage($chat_id);
}
}
sub usage {
my ($chat_id) = @_;
$bot->sendMessage({
chat_id => $chat_id,
text => 'Example: 100 LEI',
});
}
sub convert {
my ($chat_id, $amount, $currency_from, $currency_to) = @_;
my $result = '?';
if ($currency{$currency_from} && $currency{$currency_to}) {
$result = sprintf '%.2f', $amount * $currency{$currency_from} / $currency{$currency_to};
}
$bot->sendMessage({
chat_id => $chat_id,
text => $result,
parse_mode => 'HTML',
});
}
sub refine {
my ($chat_id, $amount, $currency_from) = @_;
my @other = grep {$_ ne $currency_from} sort keys %currency;
my $keyboard = {
keyboard => [map {["$amount $currency_from in $_"]} @other],
one_time_keyboard => JSON::true,
};
$bot->sendMessage({
chat_id => $chat_id,
text => 'Wat wil je precies?',
reply_markup => to_json($keyboard),
});
}