-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDictController.php
99 lines (89 loc) · 2.35 KB
/
DictController.php
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
<?php declare(strict_types=1);
namespace Nadybot\User\Modules\DICT_MODULE;
require_once __DIR__ . '/vendor/autoload.php';
use AL\PhpWndb\{
DiContainerFactory,
WordNet,
Model\Synsets\SynsetInterface,
};
use Nadybot\Core\{
Attributes as NCA,
CmdContext,
ModuleInstance,
Text,
};
/**
* @author Nadyita (RK5) <nadyita@hodorraid.org>
*/
#[
NCA\Instance,
NCA\DefineCommand(
command: 'dict',
accessLevel: 'guest',
description: 'Look up the definition of a word',
)
]
class DictController extends ModuleInstance {
#[NCA\Inject]
public Text $text;
protected function getSynsetText(SynsetInterface $synset, string $search): string {
$indent = "\n<black>______<end>";
$blob = "<black>____<end><highlight>*<end><black>_<end>".
wordwrap(ucfirst($synset->getGloss()), 80, "${indent}");
$synonyms = array_map(
function($word) {
return $this->text->makeChatcmd($word, "/tell <myname> dict $word");
},
array_filter(
array_map(
function($word) {
return $word->getLemma();
},
$synset->getWords()
),
function($word) use ($search) {
return strtolower($word) !== strtolower($search);
}
)
);
if (count($synonyms) > 0) {
$blob .= "${indent}See also: " . join(', ', $synonyms);
}
return $blob;
}
/**
* Look up a word in the dictionary
*/
#[NCA\HandlesCommand("dict")]
public function dictCommand(CmdContext $context, string $term): void {
$containerFactory = new DiContainerFactory();
$container = $containerFactory->createContainer();
/** @var \AL\PhpWndb\WordNet */
$wordNet = $container->get(WordNet::class);
/** @var \AL\PhpWndb\Model\Synsets\SynsetInterface[] */
$synsets = $wordNet->searchLemma($term);
if (empty($synsets)) {
$msg = "No definition found for <highlight>{$term}<end>.";
$context->reply($msg);
return;
}
$blob = '';
$lastType = null;
foreach ($synsets as $synset) {
if ($lastType !== $synset->getPartOfSpeech()) {
$blob .= "\n\n<pagebreak><header2>" . ($lastType = $synset->getPartOfSpeech()) . "<end>";
} else {
$blob .= "\n";
}
$blob .= "\n" . $this->getSynsetText($synset, $term);
}
$blob .= "\n\n\n<i>Dictionary data provided by Princeton University</i>";
$msg = $this->text->makeBlob(
"Found " . count($synsets) . " definition".
(count($synsets) > 1 ? 's' : '').
" for {$term}",
$blob
);
$context->reply($msg);
}
}