/
index.p6
91 lines (77 loc) · 2.82 KB
/
index.p6
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
use Telegram;
use Red;
use Schema;
class Msg {
has $!bot;
has $.chat;
has $.sender;
has Str $.text;
method TWEAK(:$!bot!, :$msg!) {
$!chat = $msg.chat;
$!sender = $msg.sender;
$!text = $msg.text;
}
method answer(Str() $text, Bool :$prefix = True) {
say self;
$!bot.sendMessage: :chat_id($!chat.id), :text(self!encode-msg: "{ "{ $!sender.username }:" if $prefix } $text")
}
method !encode-msg($msg) { $msg.subst: /<-alnum>/, *.ord.fmt("%%%02X"), :g }
method is-cmd(--> Bool()) { $!text.starts-with: "/" }
method command(--> Str()) {
die "Not a command" unless self.is-cmd;
$!text.substr(1).split(" ").head
}
method args(--> Str()) {
die "Not a command" unless self.is-cmd;
my $index = $!text.index: " ";
return Str without $index;
$!text.substr(1 + $index).head
}
}
my $*RED-DB = database "SQLite", :database<./alive.db>;
.^create-table for Chat, Person, Log;
my $bot = Telegram::Bot.new: "<the botfather token>";
$bot.start(interval => 1);
my $msgTap = $bot.messagesTap;
react {
whenever $msgTap.map(-> $msg { Msg.new: :$bot, :$msg }).grep: *.is-cmd -> $msg {
my $nick = $msg.sender.username;
if $msg.command eq "start" {
say "started";
Chat.^create: :id($msg.chat.id);
$msg.answer: "Started";
} else {
my $chat = Chat.^find: id => $msg.chat.id;
given $msg.command {
when "give-birth" {
say "give-birth";
$chat.give-birth: $msg.sender.id, $nick;
$msg.answer: "$nick was born."
}
when "kill" {
say "kill";
$chat.kill: $msg.args;
$msg.answer: "{ $msg.args } was killed."
}
when "resurrect" {
say "resurrect";
$chat.resurrect: $msg.args;
$msg.answer: "{ $msg.args } is alive again."
}
when "alive" {
say "alive";
for $chat.alive.map: *.nick -> $user {
$msg.answer: $user, :!prefix
}
}
default {
$msg.answer: "command '{ $_ }' not recognized"
}
}
}
}
whenever signal(SIGINT) {
$bot.stop;
exit;
}
}