Weixin/Plugin/SmartReply.pm untested

filter: Statementstmt 0.0% 0 / 63 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 17 MC/DCmcdc 0.0% 0 / 11 Subroutinesub 0.0% 0 / 2 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 132 CC 20 SCAR 59.9
CC
20
Cov
0%
call
420.0
BEGIN
2.0
CRAP 400.1
1 package Mojo::Weixin::Plugin::SmartReply;
2 use POSIX;
3 my $api = 'http://www.tuling123.com/openapi/api';
4 my %limit;
5 my %ban;
6 my @limit_reply = (
7 "对不起,请不要这么频繁的艾特我",
8 "对不起,您的艾特次数太多",
9 "说这么多话不累么,请休息几分钟",
10 "能不能小窗我啊,别吵着大家",
11 );
12 sub call{
13 my $client = shift;
14 my $data = shift;
15 $client->interval(600,sub{
16 my $key = strftime("%H:%M",localtime(time-600));
17 delete $limit{$key};
18 });
19 $client->on(receive_message=>sub{
20 my($client,$msg) = @_;
21 return if not $msg->allow_plugin;
22 return if $msg->type !~ /^friend_message|group_message$/;
23 return if exists $ban{$msg->sender->id};
24 my $sender_nick = $msg->sender->displayname;
25 my $user_nick = $msg->receiver->displayname;
26 return if $msg->type eq "group_message" and !$msg->is_at;
27  
28 $msg->allow_plugin(0);
29 if($msg->type eq 'group_message'){
30 my $key = POSIX::strftime("%H",localtime(time));
31 $limit{$key}{$msg->group->id}{$msg->sender->id}++;
32 my $limit = $limit{$key}{$msg->group->id}{$msg->sender->id};
33 if($limit>=8 and $limit<=9){
34 $client->reply_message($msg,"\@$sender_nick " . $limit_reply[int rand($#limit_reply+1)],sub{$_[1]->from("bot")});
35 return;
36 }
37 if($limit >=10 and $limit <=11){
38 $client->reply_message($msg,"\@$sender_nick " . "警告,您艾特过于频繁,即将被列入黑名单,请克制",sub{$_[1]->from("bot")});
39 return;
40 }
41 if($limit > 11){
42 $ban{$msg->sender->id} = 1;
43 $client->reply_message($msg,"\@$sender_nick " . "您已被列入黑名单,1小时内提问无视",sub{$_[1]->from("bot")});
44 $client->timer(3600,sub{delete $ban{$msg->sender->id};});
45 }
46 }
47  
48 my $input = $msg->content;
49 $input=~s/\@\Q$user_nick\E(|"\xe2\x80\x85")(\s+)?|\[[^\[\]]+\]//g;
50 return unless $input;
51  
52 my $json = {
53 "key" => $data->{apikey} || "bbdaba85b5cf47bc80e27cbaee7a77df",
54 "userid" => $msg->sender->id,
55 "info" => $input,
56 };
57  
58 $json->{"loc"} = $msg->sender->city if $msg->type eq "group_message" and $msg->sender->city;
59 $client->http_post($api,{json=>1},json=>$json,sub{
60 my $json = shift;
61 return unless defined $json;
62 return if $json->{code}=~/^4000[1-7]$/;
63 my $reply;
64 if($json->{code} == 100000){
65 return unless $json->{text};
66 $reply = $json->{text};
67 }
68 elsif($json->{code} == 200000){
69 $reply = "$json->{text}$json->{url}";
70 }
71 else{return}
72 $reply=~s#<br(\s*/)?>#\n#g;
73 eval{$reply= Mojo::Util::html_unescape($reply);};
74 $client->warn("html entities unescape fail: $@") if $@;
75 $reply = "\@$sender_nick " . $reply if $msg->type eq 'group_message' and rand(100)>20;
76 $reply = $client->truncate($reply,max_bytes=>500,max_lines=>10) if $msg->type eq 'group_message';
77 $client->reply_message($msg,$reply,sub{$_[1]->from("bot")}) if $reply;
78 });
79  
80 });
81 }
82 1;