forked from MycroftAI/mycroft-core
-
Notifications
You must be signed in to change notification settings - Fork 15
/
mycroft_skill.py
1645 lines (1388 loc) · 64 KB
/
mycroft_skill.py
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2019 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Common functionality relating to the implementation of mycroft skills."""
import re
import sys
import traceback
from copy import copy
from inspect import signature
from itertools import chain
from os.path import join, abspath, dirname, basename, exists, isfile
from threading import Event
from ovos_utils.intents import Intent, IntentBuilder
from ovos_utils.skills import get_non_properties
from json_database import JsonStorage
from mycroft import dialog
from mycroft.api import DeviceApi
from mycroft.audio import wait_while_speaking
from mycroft.configuration import Configuration
from mycroft.dialog import load_dialogs
from mycroft.filesystem import FileSystemAccess
from mycroft.gui import SkillGUI
from mycroft.messagebus.message import Message, dig_for_message
from mycroft.metrics import report_metric
from mycroft.skills.event_scheduler import EventSchedulerInterface
from mycroft.skills.intent_service_interface import IntentServiceInterface
from mycroft.skills.mycroft_skill.event_container import EventContainer, \
create_wrapper, get_handler_name
from mycroft.skills.skill_data import (
munge_regex,
munge_intent_parser,
find_resource,
ResourceFile,
SkillResources,
CoreResources
)
# backwards compat imports, do not delete!
from mycroft.deprecated.skills import (
read_vocab_file, read_value_file, read_translated_file,
load_vocabulary, load_regex,
to_alnum,)
from mycroft.util import (
resolve_resource_file,
play_audio_file,
camel_case_split
)
from mycroft.util.format import pronounce_number, join_list
from mycroft.util.log import LOG
from mycroft.util.parse import match_one, extract_number
from mycroft.util.file_utils import FileWatcher
from ovos_utils.configuration import get_xdg_base, get_xdg_data_save_path, get_xdg_config_save_path
from ovos_utils.enclosure.api import EnclosureAPI
from ovos_utils.file_utils import get_temp_path
from ovos_utils.messagebus import get_message_lang
import shutil
def simple_trace(stack_trace):
"""Generate a simplified traceback.
Args:
stack_trace: Stack trace to simplify
Returns: (str) Simplified stack trace.
"""
stack_trace = stack_trace[:-1]
tb = 'Traceback:\n'
for line in stack_trace:
if line.strip():
tb += line
return tb
class MycroftSkill:
"""Base class for mycroft skills providing common behaviour and parameters
to all Skill implementations.
For information on how to get started with creating mycroft skills see
https://mycroft.ai/documentation/skills/introduction-developing-skills/
Args:
name (str): skill name
bus (MycroftWebsocketClient): Optional bus connection
use_settings (bool): Set to false to not use skill settings at all (DEPRECATED)
"""
def __init__(self, name=None, bus=None, use_settings=True):
self._init_event = Event()
self.name = name or self.__class__.__name__
self.resting_name = None
self.skill_id = '' # will be set by SkillLoader, guaranteed unique
self.settings_meta = None # set when skill is loaded in SkillLoader
# Get directory of skill
#: Member variable containing the absolute path of the skill's root
#: directory. E.g. $XDG_DATA_HOME/mycroft/skills/my-skill.me/
self.root_dir = dirname(abspath(sys.modules[self.__module__].__file__))
self.gui = SkillGUI(self)
self._bus = None
self._enclosure = EnclosureAPI()
#: Mycroft global configuration. (dict)
self.config_core = Configuration()
self._settings = None
self._initial_settings = {}
self.settings_write_path = None
self._settings_watchdog = None
# old kludge from fallback skills, unused according to grep
if use_settings is False:
LOG.warning("use_settings has been deprecated! skill settings are always enabled")
#: Set to register a callback method that will be called every time
#: the skills settings are updated. The referenced method should
#: include any logic needed to handle the updated settings.
self.settings_change_callback = None
# fully initialized when self.skill_id is set
self._file_system = None
self.log = LOG
self.reload_skill = True #: allow reloading (default True)
self.events = EventContainer(bus)
self.voc_match_cache = {}
# loaded lang file resources
self._lang_resources = {}
# Delegator classes
self.event_scheduler = EventSchedulerInterface()
self.intent_service = IntentServiceInterface()
# Skill Public API
self.public_api = {}
self.__original_converse = self.converse
@property
def is_fully_initialized(self):
"""Determines if the skill has been fully loaded and setup.
When True all data has been loaded and all internal state and events setup"""
return self._init_event.is_set()
def handle_first_run(self):
"""The very first time a skill is run, speak the intro."""
intro = self.get_intro_message()
if intro:
# supports .dialog files for easy localization
# when .dialog does not exist, the text is spoken
# it is backwards compatible
self.speak_dialog(intro)
def _check_for_first_run(self):
"""Determine if its the very first time a skill is run."""
first_run = self.settings.get("__mycroft_skill_firstrun", True)
if first_run:
LOG.info("First run of " + self.skill_id)
self.handle_first_run()
self.settings["__mycroft_skill_firstrun"] = False
self.settings.store()
def _startup(self, bus, skill_id=""):
"""Startup the skill.
This connects the skill to the messagebus, loads vocabularies and
data files and in the end calls the skill creator's "intialize" code.
Arguments:
bus: Mycroft Messagebus connection object.
skill_id (str): need to be unique, by default is set from skill path
but skill loader can override this
"""
if self.is_fully_initialized:
LOG.warning(f"Tried to initialize {self.skill_id} multiple times, ignoring")
return
# NOTE: this method is called by SkillLoader
# it is private to make it clear to skill devs they should not touch it
try:
# set the skill_id
self.skill_id = skill_id or basename(self.root_dir)
self.intent_service.set_id(self.skill_id)
self.event_scheduler.set_id(self.skill_id)
self.enclosure.set_id(self.skill_id)
# initialize anything that depends on skill_id
self.log = LOG.create_logger(self.skill_id)
self._init_settings()
# initialize anything that depends on the messagebus
self.bind(bus)
self.load_data_files()
self._register_decorated()
self.register_resting_screen()
# run skill developer initialization code
self.initialize()
self._check_for_first_run()
self._init_event.set()
except Exception as e:
LOG.exception('Skill initialization failed')
# If an exception occurs, attempt to clean up the skill
try:
self.default_shutdown()
except Exception as e2:
pass
raise e
def _init_settings(self):
"""Setup skill settings."""
LOG.debug(f"initializing skill settings for {self.skill_id}")
# migrate settings if needed
if not exists(self._settings_path) and exists(self._old_settings_path):
LOG.warning("Found skill settings at pre-xdg location, migrating!")
shutil.copy(self._old_settings_path, self._settings_path)
LOG.info(f"{self._old_settings_path} moved to {self._settings_path}")
# NOTE: lock is disabled due to usage of deepcopy and to allow json serialization
self._settings = JsonStorage(self._settings_path, disable_lock=True)
if self._initial_settings:
# TODO make a debug log in next version
LOG.warning("Copying default settings values defined in __init__ \n"
"Please move code from __init__() to initialize() if you did not expect to see this message")
for k, v in self._initial_settings.items():
if k not in self._settings:
self._settings[k] = v
self._initial_settings = copy(self.settings)
self._start_filewatcher()
def _start_filewatcher(self):
if self._settings_watchdog is None and isfile(self._settings.path):
self._settings_watchdog = FileWatcher([self._settings.path],
callback=self.settings_change_callback)
def _handle_settings_file_change(self):
if self._settings:
self._settings.reload()
if self.settings_change_callback:
try:
self.settings_change_callback()
except:
self.log.exception("settings change callback failed, "
"file changes not handled!")
@property
def _old_settings_path(self):
old_dir = self.config_core.get("data_dir", "/opt/mycroft")
old_folder = self.config_core.get("skills", {}).get("msm", {}).get("directory", "skills")
return join(old_dir, old_folder, self.skill_id, 'settings.json')
@property
def _settings_path(self):
if self.settings_write_path:
LOG.warning("self.settings_write_path has been deprecated! "
"Support will be dropped in a future release")
return join(self.settings_write_path, 'settings.json')
return join(get_xdg_config_save_path(), 'skills', self.skill_id, 'settings.json')
@property
def settings(self):
if self._settings is not None:
return self._settings
else:
LOG.error('Skill not fully initialized. '
'Only default values can be set, no settings can be read or changed.'
'Move code from __init__() to initialize() to correct this.')
return self._initial_settings
@settings.setter
def settings(self, val):
assert isinstance(val, dict)
# init method
if self._settings is None:
self._initial_settings = val
return
# ensure self._settings remains a JsonDatabase
self._settings.clear() # clear data
self._settings.merge(val) # merge new data
@property
def dialog_renderer(self):
return self._resources.dialog_renderer
@property
def enclosure(self):
if self._enclosure:
return self._enclosure
else:
LOG.error('Skill not fully initialized. Move code ' +
'from __init__() to initialize() to correct this.')
LOG.error(simple_trace(traceback.format_stack()))
raise Exception('Accessed MycroftSkill.enclosure in __init__')
@property
def file_system(self):
""" Filesystem access to skill specific folder.
See mycroft.filesystem for details.
"""
if not self._file_system and self.skill_id:
self._file_system = FileSystemAccess(join('skills', self.skill_id))
if self._file_system:
return self._file_system
else:
LOG.error('Skill not fully initialized. Move code ' +
'from __init__() to initialize() to correct this.')
LOG.error(simple_trace(traceback.format_stack()))
raise Exception('Accessed MycroftSkill.file_system in __init__')
@file_system.setter
def file_system(self, fs):
"""Provided mainly for backwards compatibility with derivative MycroftSkill classes
Skills are advised against redefining the file system directory"""
self._file_system = fs
@property
def bus(self):
if self._bus:
return self._bus
else:
LOG.error('Skill not fully initialized. Move code ' +
'from __init__() to initialize() to correct this.')
LOG.error(simple_trace(traceback.format_stack()))
raise Exception('Accessed MycroftSkill.bus in __init__')
@property
def location(self):
"""Get the JSON data struction holding location information."""
# TODO: Allow Enclosure to override this for devices that
# contain a GPS.
return self.config_core.get('location')
@property
def location_pretty(self):
"""Get a more 'human' version of the location as a string."""
loc = self.location
if type(loc) is dict and loc['city']:
return loc['city']['name']
return None
@property
def location_timezone(self):
"""Get the timezone code, such as 'America/Los_Angeles'"""
loc = self.location
if type(loc) is dict and loc['timezone']:
return loc['timezone']['code']
return None
@property
def lang(self):
"""Get the current language."""
lang = self._core_lang
message = dig_for_message()
if message:
lang = get_message_lang(message)
return lang.lower()
@property
def _core_lang(self):
"""Get the configured default language.
NOTE: this should be public, but since if a skill uses this it wont
work in regular mycroft-core it was made private!"""
return self.config_core.get("lang", "en-us").lower()
@property
def _secondary_langs(self):
"""Get the configured secondary languages, mycroft is not
considered to be in these languages but i will load it's resource
files. This provides initial support for multilingual input
NOTE: this should be public, but since if a skill uses this it wont
work in regular mycroft-core it was made private!"""
return [l.lower() for l in self.config_core.get('secondary_langs', [])
if l != self._core_lang]
@property
def _native_langs(self):
"""Languages natively supported by core
ie, resource files available and explicitly supported
NOTE: this should be public, but since if a skill uses this it wont
work in regular mycroft-core it was made private!
"""
return [self._core_lang] + self._secondary_langs
@property
def _alphanumeric_skill_id(self):
"""skill id converted to only alphanumeric characters
Non alpha-numeric characters are converted to "_"
NOTE: this should be public, but since if a skill uses this it wont
work in regular mycroft-core it was made private!
Returns:
(str) String of letters
"""
return ''.join(c if c.isalnum() else '_'
for c in str(self.skill_id))
@property
def _resources(self):
"""Instantiates a ResourceFileLocator instance when needed.
a new instance is always created to ensure self.lang
reflects the active language and not the default core language
NOTE: this should be public, but since if a skill uses this it wont
work in regular mycroft-core it was made private!
"""
return self._load_lang(self.root_dir, self.lang)
def _load_lang(self, root_directory=None, lang=None):
"""Instantiates a ResourceFileLocator instance when needed.
a new instance is always created to ensure lang
reflects the active language and not the default core language
NOTE: this should be public, but since if a skill uses this it wont
work in regular mycroft-core it was made private!
"""
lang = lang or self.lang
root_directory = root_directory or self.root_dir
if lang not in self._lang_resources:
self._lang_resources[lang] = SkillResources(root_directory, lang, skill_id=self.skill_id)
return self._lang_resources[lang]
def bind(self, bus):
"""Register messagebus emitter with skill.
Args:
bus: Mycroft messagebus connection
"""
if bus:
self._bus = bus
self.events.set_bus(bus)
self.intent_service.set_bus(bus)
self.event_scheduler.set_bus(bus)
self._enclosure.set_bus(bus)
self._register_system_event_handlers()
# Initialize the SkillGui
self.gui.setup_default_handlers()
self._register_public_api()
def _register_public_api(self):
""" Find and register api methods.
Api methods has been tagged with the api_method member, for each
method where this is found the method a message bus handler is
registered.
Finally create a handler for fetching the api info from any requesting
skill.
"""
def wrap_method(func):
"""Boiler plate for returning the response to the sender."""
def wrapper(message):
result = func(*message.data['args'], **message.data['kwargs'])
message.context["skill_id"] = self.skill_id
self.bus.emit(message.response(data={'result': result}))
return wrapper
methods = [attr_name for attr_name in get_non_properties(self)
if hasattr(getattr(self, attr_name), '__name__')]
for attr_name in methods:
method = getattr(self, attr_name)
if hasattr(method, 'api_method'):
doc = method.__doc__ or ''
name = method.__name__
self.public_api[name] = {
'help': doc,
'type': f'{self.skill_id}.{name}',
'func': method
}
for key in self.public_api:
if ('type' in self.public_api[key] and
'func' in self.public_api[key]):
LOG.debug(f"Adding api method: {self.public_api[key]['type']}")
# remove the function member since it shouldn't be
# reused and can't be sent over the messagebus
func = self.public_api[key].pop('func')
self.add_event(self.public_api[key]['type'],
wrap_method(func))
if self.public_api:
self.add_event(f'{self.skill_id}.public_api',
self._send_public_api)
@property
def stop_is_implemented(self):
return self.__class__.stop is not MycroftSkill.stop
@property
def converse_is_implemented(self):
return self.__class__.converse is not MycroftSkill.converse or \
self.__original_converse != self.converse
def _register_system_event_handlers(self):
"""Add all events allowing the standard interaction with the Mycroft
system.
"""
# Only register stop if it's been implemented
if self.stop_is_implemented:
self.add_event('mycroft.stop', self.__handle_stop)
self.add_event('skill.converse.ping', self._handle_converse_ack)
self.add_event('skill.converse.request', self._handle_converse_request)
self.add_event(f"{self.skill_id}.activate", self.handle_activate)
self.add_event(f"{self.skill_id}.deactivate", self.handle_deactivate)
self.add_event("intent.service.skills.deactivated", self._handle_skill_deactivated)
self.add_event("intent.service.skills.activated", self._handle_skill_activated)
self.add_event('mycroft.skill.enable_intent', self.handle_enable_intent)
self.add_event('mycroft.skill.disable_intent', self.handle_disable_intent)
self.add_event('mycroft.skill.set_cross_context', self.handle_set_cross_context)
self.add_event('mycroft.skill.remove_cross_context', self.handle_remove_cross_context)
self.add_event('mycroft.skills.settings.changed', self.handle_settings_change)
def handle_settings_change(self, message):
"""Update settings if the remote settings changes apply to this skill.
The skill settings downloader uses a single API call to retrieve the
settings for all skills. This is done to limit the number API calls.
A "mycroft.skills.settings.changed" event is emitted for each skill
that had their settings changed. Only update this skill's settings
if its remote settings were among those changed
"""
if self.settings_meta is None or self.settings_meta.skill_gid is None:
LOG.error(f'The skill_gid was not set when {self.name} was loaded!')
else:
remote_settings = message.data.get(self.settings_meta.skill_gid)
if remote_settings is not None:
LOG.info('Updating settings for skill ' + self.skill_id)
self.settings.update(**remote_settings)
self.settings.store()
if self.settings_change_callback is not None:
try:
self.settings_change_callback()
except:
self.log.exception("settings change callback failed, "
"remote changes not handled!")
self._start_filewatcher()
def detach(self):
for (name, _) in self.intent_service:
name = f'{self.skill_id}:{name}'
self.intent_service.detach_intent(name)
def initialize(self):
"""Perform any final setup needed for the skill.
Invoked after the skill is fully constructed and registered with the
system.
"""
pass
def _send_public_api(self, message):
"""Respond with the skill's public api."""
message.context["skill_id"] = self.skill_id
self.bus.emit(message.response(data=self.public_api))
def get_intro_message(self):
"""Get a message to speak on first load of the skill.
Useful for post-install setup instructions.
Returns:
str: message that will be spoken to the user
"""
return None
# converse handling
def _handle_skill_activated(self, message):
""" intent service activated a skill
if it was this skill fire the skill activation event"""
if message.data.get("skill_id") == self.skill_id:
self.bus.emit(message.forward(f"{self.skill_id}.activate"))
def handle_activate(self, message):
""" skill is now considered active by the intent service
converse method will be called, skills might want to prepare/resume
"""
def _handle_skill_deactivated(self, message):
""" intent service deactivated a skill
if it was this skill fire the skill deactivation event"""
if message.data.get("skill_id") == self.skill_id:
self.bus.emit(message.forward(f"{self.skill_id}.deactivate"))
def handle_deactivate(self, message):
""" skill is no longer considered active by the intent service
converse method will not be called, skills might want to reset state here
"""
def activate(self):
"""Bump skill to active_skill list in intent_service.
This enables converse method to be called even without skill being
used in last 5 minutes.
"""
msg = dig_for_message() or Message("")
if "skill_id" not in msg.context:
msg.context["skill_id"] = self.skill_id
self.bus.emit(msg.forward("intent.service.skills.activate",
data={"skill_id": self.skill_id}))
def deactivate(self):
"""remove skill from active_skill list in intent_service.
This stops converse method from being called
"""
msg = dig_for_message() or Message("")
if "skill_id" not in msg.context:
msg.context["skill_id"] = self.skill_id
self.bus.emit(msg.forward(f"intent.service.skills.deactivate",
data={"skill_id": self.skill_id}))
def _handle_converse_ack(self, message):
"""Inform skills service if we want to handle converse.
individual skills may override the property self.converse_is_implemented"""
self.bus.emit(message.reply(
"skill.converse.pong",
data={"skill_id": self.skill_id,
"can_handle": self.converse_is_implemented},
context={"skill_id": self.skill_id}))
def _handle_converse_request(self, message):
"""Check if the targeted skill id can handle conversation
If supported, the conversation is invoked.
"""
skill_id = message.data['skill_id']
if skill_id == self.skill_id:
try:
# converse can have multiple signatures
params = signature(self.converse).parameters
kwargs = {"message": message,
"utterances": message.data['utterances'],
"lang": message.data['lang']}
kwargs = {k: v for k, v in kwargs.items() if k in params}
result = self.converse(**kwargs)
self.bus.emit(message.reply('skill.converse.response',
{"skill_id": self.skill_id,
"result": result}))
except Exception:
self.bus.emit(message.reply('skill.converse.response',
{"skill_id": self.skill_id,
"result": False}))
def converse(self, message=None):
"""Handle conversation.
This method gets a peek at utterances before the normal intent
handling process after a skill has been invoked once.
To use, override the converse() method and return True to
indicate that the utterance has been handled.
utterances and lang are depreciated
Args:
message: a message object containing a message type with an
optional JSON data packet
Returns:
bool: True if an utterance was handled, otherwise False
"""
return False
def __get_response(self):
"""Helper to get a response from the user
NOTE: There is a race condition here. There is a small amount of
time between the end of the device speaking and the converse method
being overridden in this method. If an utterance is injected during
this time, the wrong converse method is executed. The condition is
hidden during normal use due to the amount of time it takes a user
to speak a response. The condition is revealed when an automated
process injects an utterance quicker than this method can flip the
converse methods.
Returns:
str: user's response or None on a timeout
"""
event = Event()
def converse(utterances, lang=None):
converse.response = utterances[0] if utterances else None
event.set()
return True
# install a temporary conversation handler
self.activate()
converse.response = None
self.__original_converse = self.converse
self.converse = converse
event.wait(15) # 10 for listener, 5 for SST, then timeout
self.converse = self.__original_converse
return converse.response
def get_response(self, dialog='', data=None, validator=None,
on_fail=None, num_retries=-1):
"""Get response from user.
If a dialog is supplied it is spoken, followed immediately by listening
for a user response. If the dialog is omitted listening is started
directly.
The response can optionally be validated before returning.
Example::
color = self.get_response('ask.favorite.color')
Args:
dialog (str): Optional dialog to speak to the user
data (dict): Data used to render the dialog
validator (any): Function with following signature::
def validator(utterance):
return utterance != "red"
on_fail (any):
Dialog or function returning literal string to speak on
invalid input. For example::
def on_fail(utterance):
return "nobody likes the color red, pick another"
num_retries (int): Times to ask user for input, -1 for infinite
NOTE: User can not respond and timeout or say "cancel" to stop
Returns:
str: User's reply or None if timed out or canceled
"""
data = data or {}
def on_fail_default(utterance):
fail_data = data.copy()
fail_data['utterance'] = utterance
if on_fail:
if self.dialog_renderer:
return self.dialog_renderer.render(on_fail, fail_data)
return on_fail
else:
if self.dialog_renderer:
return self.dialog_renderer.render(dialog, data)
return dialog
def is_cancel(utterance):
return self.voc_match(utterance, 'cancel')
def validator_default(utterance):
# accept anything except 'cancel'
return not is_cancel(utterance)
on_fail_fn = on_fail if callable(on_fail) else on_fail_default
validator = validator or validator_default
# Speak query and wait for user response
if dialog:
self.speak_dialog(dialog, data, expect_response=True, wait=True)
else:
msg = dig_for_message()
msg = msg.reply('mycroft.mic.listen') if msg else \
Message('mycroft.mic.listen', context={"skill_id": self.skill_id})
self.bus.emit(msg)
return self._wait_response(is_cancel, validator, on_fail_fn,
num_retries)
def _wait_response(self, is_cancel, validator, on_fail, num_retries):
"""Loop until a valid response is received from the user or the retry
limit is reached.
Args:
is_cancel (callable): function checking cancel criteria
validator (callbale): function checking for a valid response
on_fail (callable): function handling retries
"""
msg = dig_for_message()
msg = msg.reply('mycroft.mic.listen') if msg else \
Message('mycroft.mic.listen',
context={"skill_id": self.skill_id})
num_fails = 0
while True:
response = self.__get_response()
if response is None:
# if nothing said, prompt one more time
num_none_fails = 1 if num_retries < 0 else num_retries
if num_fails >= num_none_fails:
return None
else:
if validator(response):
return response
# catch user saying 'cancel'
if is_cancel(response):
return None
num_fails += 1
if 0 < num_retries < num_fails:
return None
line = on_fail(response)
if line:
self.speak(line, expect_response=True)
else:
self.bus.emit(msg)
def ask_yesno(self, prompt, data=None):
"""Read prompt and wait for a yes/no answer
This automatically deals with translation and common variants,
such as 'yeah', 'sure', etc.
Args:
prompt (str): a dialog id or string to read
data (dict): response data
Returns:
string: 'yes', 'no' or whatever the user response if not
one of those, including None
"""
resp = self.get_response(dialog=prompt, data=data)
if self.voc_match(resp, 'yes'):
return 'yes'
elif self.voc_match(resp, 'no'):
return 'no'
else:
return resp
def ask_selection(self, options, dialog='',
data=None, min_conf=0.65, numeric=False):
"""Read options, ask dialog question and wait for an answer.
This automatically deals with fuzzy matching and selection by number
e.g.
* "first option"
* "last option"
* "second option"
* "option number four"
Args:
options (list): list of options to present user
dialog (str): a dialog id or string to read AFTER all options
data (dict): Data used to render the dialog
min_conf (float): minimum confidence for fuzzy match, if not
reached return None
numeric (bool): speak options as a numeric menu
Returns:
string: list element selected by user, or None
"""
assert isinstance(options, list)
if not len(options):
return None
elif len(options) == 1:
return options[0]
if numeric:
for idx, opt in enumerate(options):
number = pronounce_number(idx + 1, self.lang)
self.speak(f"{number}, {opt}", wait=True)
else:
opt_str = join_list(options, "or", lang=self.lang) + "?"
self.speak(opt_str, wait=True)
resp = self.get_response(dialog=dialog, data=data)
if resp:
match, score = match_one(resp, options)
if score < min_conf:
if self.voc_match(resp, 'last'):
resp = options[-1]
else:
num = extract_number(resp, ordinals=True, lang=self.lang)
resp = None
if num and num <= len(options):
resp = options[num - 1]
else:
resp = match
return resp
def voc_match(self, utt, voc_filename, lang=None, exact=False):
"""Determine if the given utterance contains the vocabulary provided.
By default the method checks if the utterance contains the given vocab
thereby allowing the user to say things like "yes, please" and still
match against "Yes.voc" containing only "yes". An exact match can be
requested.
The method first checks in the current Skill's .voc files and secondly
in the "res/text" folder of mycroft-core. The result is cached to
avoid hitting the disk each time the method is called.
Args:
utt (str): Utterance to be tested
voc_filename (str): Name of vocabulary file (e.g. 'yes' for
'res/text/en-us/yes.voc')
lang (str): Language code, defaults to self.lang
exact (bool): Whether the vocab must exactly match the utterance
Returns:
bool: True if the utterance has the given vocabulary it
"""
match = False
lang = lang or self.lang
cache_key = lang + voc_filename
if cache_key not in self.voc_match_cache:
vocab = self._resources.load_vocabulary_file(voc_filename) or \
CoreResources(lang).load_vocabulary_file(voc_filename)
self.voc_match_cache[cache_key] = list(chain(*vocab))
if utt:
if exact:
# Check for exact match
match = any(i.strip() == utt
for i in self.voc_match_cache[cache_key])
else:
# Check for matches against complete words
match = any([re.match(r'.*\b' + i + r'\b.*', utt)
for i in self.voc_match_cache[cache_key]])
return match
def report_metric(self, name, data):
"""Report a skill metric to the Mycroft servers.
Args:
name (str): Name of metric. Must use only letters and hyphens
data (dict): JSON dictionary to report. Must be valid JSON
"""
report_metric(f'{self.skill_id}:{name}', data)
def send_email(self, title, body):
"""Send an email to the registered user's email.
Args:
title (str): Title of email
body (str): HTML body of email. This supports
simple HTML like bold and italics
"""
DeviceApi().send_email(title, body, basename(self.root_dir))
def make_active(self):
"""Bump skill to active_skill list in intent_service.
This enables converse method to be called even without skill being
used in last 5 minutes.
deprecated: use self.activate() instead
"""
# TODO deprecate, backwards compat
self.activate()
def _handle_collect_resting(self, message=None):
"""Handler for collect resting screen messages.
Sends info on how to trigger this skills resting page.
"""
self.log.info('Registering resting screen')
msg = message or Message("")
message = msg.reply(
'mycroft.mark2.register_idle',
data={'name': self.resting_name, 'id': self.skill_id},
context={"skill_id": self.skill_id}
)
self.bus.emit(message)
def register_resting_screen(self):
"""Registers resting screen from the resting_screen_handler decorator.
This only allows one screen and if two is registered only one
will be used.
"""
for attr_name in get_non_properties(self):
method = getattr(self, attr_name)
if hasattr(method, 'resting_handler'):
self.resting_name = method.resting_handler
self.log.info(f'Registering resting screen {method} for {self.resting_name}.')
# Register for handling resting screen
self.add_event(f'{self.skill_id}.idle', method)