1
+ <?php
2
+
3
+
4
+ namespace Vbot \Blacklist ;
5
+
6
+
7
+ use Hanson \Vbot \Extension \AbstractMessageHandler ;
8
+ use Illuminate \Support \Collection ;
9
+ use Predis \Client ;
10
+ use Redis ;
11
+
12
+ class Blacklist extends AbstractMessageHandler
13
+ {
14
+ public $ author = 'HanSon ' ;
15
+
16
+ public $ version = '1.0 ' ;
17
+
18
+ public $ name = 'blacklist ' ;
19
+
20
+ public $ zhName = '黑名单 ' ;
21
+
22
+ /** @var Redis */
23
+ private $ cache ;
24
+
25
+ private $ frequencyPrefix = 'vbot.blacklist.frequency. ' ;
26
+
27
+ private $ prefix = 'vbot.blacklist. ' ;
28
+
29
+ public $ status = true ;
30
+
31
+ private $ configs ;
32
+
33
+ public function handler (Collection $ message )
34
+ {
35
+ if (!in_array ($ message ['type ' ], $ this ->configs ['type ' ])) {
36
+ return false ;
37
+ }
38
+
39
+ if ($ this ->cache ->get ($ this ->prefix .$ message ['type ' ].$ message ['username ' ])) {
40
+ return true ;
41
+ }
42
+
43
+ $ key = $ this ->frequencyPrefix .$ message ['type ' ].$ message ['username ' ];
44
+ $ count = $ this ->cache ->get ($ key ) + 1 ;
45
+ $ this ->cache ->set ($ key ,$ count );
46
+ $ this ->cache ->expire ($ key , 10 );
47
+
48
+ if ($ count == 4 ) {
49
+ $ this ->warn ($ message );
50
+ return true ;
51
+ }
52
+
53
+ if ($ count >= 7 ) {
54
+ $ this ->block ($ message );
55
+ return true ;
56
+ }
57
+
58
+ }
59
+
60
+ private function warn ($ message )
61
+ {
62
+ if (is_callable ($ callable = $ this ->configs ['warn ' ])) {
63
+ call_user_func_array ($ callable , [$ message ]);
64
+ }
65
+ }
66
+
67
+ private function block ($ message )
68
+ {
69
+
70
+ if ($ this ->cache ->get ($ this ->prefix .$ message ['type ' ].$ message ['username ' ])) {
71
+ return true ;
72
+ }
73
+
74
+ $ this ->cache ->set ($ this ->prefix .$ message ['type ' ].$ message ['username ' ], 1 );
75
+
76
+ if (is_callable ($ callable = $ this ->configs ['block ' ])) {
77
+ call_user_func_array ($ callable , [$ message ]);
78
+ }
79
+ }
80
+
81
+
82
+ /**
83
+ * 注册拓展时的操作.
84
+ */
85
+ public function register ()
86
+ {
87
+ $ this ->configs = vbot ('config ' )->get ('extension. ' .$ this ->name );
88
+ $ this ->cache = new Client ([
89
+ 'host ' => vbot ('config ' )->get ('database.redis.default.host ' ),
90
+ 'port ' => vbot ('config ' )->get ('database.redis.default.port ' ),
91
+ 'password ' => vbot ('config ' )->get ('database.redis.default.password ' ),
92
+ 'database ' => vbot ('config ' )->get ('database.redis.default.database ' ),
93
+ ]);
94
+ }
95
+ }
0 commit comments