1
0
mirror of https://github.com/MarkParker5/STARK.git synced 2025-07-02 22:36:54 +02:00

infinite context problem solved, add question type

This commit is contained in:
MarkParker5
2020-10-31 15:29:58 +02:00
parent 8c5d6215f0
commit 0126e93e5c
7 changed files with 99 additions and 32 deletions

18
Command/Callback.py Normal file
View File

@ -0,0 +1,18 @@
from .Command import Command
import re
class Callback:
def __init__(this, patterns):
this.patterns = patterns
def setStart(this, function):
this.start = function
def start(this, params):
pass
def answer(this, string):
for pattern in this.patterns:
if match := re.search(re.compile(Command.compilePattern(pattern)), string):
return this.start({**match.groupdict(), 'string':string})
return None

View File

@ -1 +1,2 @@
from .Command import * from .Command import *
from .Callback import *

View File

@ -1,10 +1,10 @@
from .film import * from .Film import *
import requests import requests
from bs4 import BeautifulSoup as BS from bs4 import BeautifulSoup as BS
import os import os
import Command
################################################################################ ################################################################################
def method(params):
def findFilm(name): def findFilm(name):
query = name + ' site:kinogo.by' query = name + ' site:kinogo.by'
responce = requests.get(f'https://www.google.ru/search?&q={query}&lr=lang_ru&lang=ru') responce = requests.get(f'https://www.google.ru/search?&q={query}&lr=lang_ru&lang=ru')
@ -18,27 +18,46 @@ def method(params):
url = page.select_one('div[style="padding:22px; float:left; margin-left: 30px;"]>a[download]:last-child') url = page.select_one('div[style="padding:22px; float:left; margin-left: 30px;"]>a[download]:last-child')
return url['href'] if url else None return url['href'] if url else None
def start(url): def startFilm(url):
os.system(f'lxterminal --command="vlc {url}"') os.system(f'lxterminal --command="vlc {url}"')
def main(params):
name = params.get('text') name = params.get('text')
print(name)
if name: if name:
if url:= extractUrl(findFilm(name)): if url:= extractUrl(findFilm(name)):
start(url) startFilm(url)
voice = text = 'Включаю' voice = text = 'Включаю'
else: else:
voice = text = 'Не могу найти фильм' voice = text = 'Не могу найти фильм'
type = 'simple'
else: else:
voice = text = 'Какой фильм включить?' voice = text = 'Какой фильм включить?'
type = 'question'
callback = kinogo_cb
return {
'type': type,
'text': text,
'voice': voice,
'callback': callback or None,
}
def start(params):
name = params.get('text')
voice = text = 'Не могу найти фильм'
if name:
if url:= extractUrl(findFilm(name)):
startFilm(url)
voice = text = 'Включаю'
return { return {
'type': 'simple', 'type': 'simple',
'text': text, 'text': text,
'voice': voice, 'voice': voice,
} }
kinogo_cb = Command.Callback(['$text',])
kinogo_cb.setStart(start)
patterns = ['* включ* фильм $text', '* включ* фильм*'] patterns = ['* включ* фильм $text', '* включ* фильм*']
subpatterns = ['$text',] kinogo = Film('KinogoPlayer', {}, patterns)
kinogo = film('KinogoPlayer', {}, patterns, subpatterns) kinogo.setStart(main)
kinogo.setStart(method)

View File

@ -1,5 +1,5 @@
from Command import Command from Command import Command
class film(Command): class Film(Command):
def start(this, string): # main method def start(this, string): # main method
pass pass

View File

@ -20,6 +20,9 @@ def reply(id, responce):
bot.send_message(id, responce['text']) bot.send_message(id, responce['text'])
if responce['voice']: if responce['voice']:
bot.send_voice(id, voice.generate(responce['voice']).getBytes() ) bot.send_voice(id, voice.generate(responce['voice']).getBytes() )
if responce['type'] == 'background': # add background thread to list
responce['thread']['id'] = id
threads.append(responce['thread'])
def check_threads(threads): def check_threads(threads):
for thread in threads: for thread in threads:
@ -34,13 +37,24 @@ def main(id, text):
if Command.isRepeat(text): if Command.isRepeat(text):
reply(memory[0]['responce']); reply(memory[0]['responce']);
return return
try: cmd, params = memory[0]['cmd'].checkContext(text).values(); params = {**memory[0]['params'], **params} if memory:
except: cmd, params = Command.reg_find(text).values() responce = memory[0]['responce']
if responce['type'] == 'question':
if new_responce := responce['callback'].answer(text):
reply(id, new_responce)
memory.insert(0, {
'cmd': responce['callback'],
'params': None,
'responce': new_responce,
})
return
try:
cmd, params = memory[0]['cmd'].checkContext(text).values()
if memory[0].get('params'): params = {**memory[0].get('params'), **params}
except:
cmd, params = Command.reg_find(text).values()
responce = cmd.start(params) responce = cmd.start(params)
reply(id, responce) reply(id, responce)
if responce['type'] == 'background': # add background thread to list
responce['thread']['id'] = id
threads.append(responce['thread'])
memory.insert(0, { memory.insert(0, {
'cmd': cmd, 'cmd': cmd,
'params': params, 'params': params,

View File

@ -33,30 +33,45 @@ def check_threads():
while True: # main loop while True: # main loop
check_threads() check_threads()
print('\nYou: ', end='') print('\nYou: ', end='')
# input
speech = listener.listen() speech = listener.listen()
text = speech['text'] text = speech['text']
if speech['status'] == 'ok': if speech['status'] == 'ok':
print(text) print(text)
voids = 0 voids = 0
# set online add clean input if name in text
if name := list(set(config.names) & set(text.split(' '))): if name := list(set(config.names) & set(text.split(' '))):
online = True online = True
text = text.replace(name[0], '').strip() text = text.replace(name[0], '').strip()
# recognize and execute command
if online: if online:
# repeat last answer
if Command.isRepeat(text): if Command.isRepeat(text):
reply(memory[0]['responce']); reply(memory[0]['responce']);
continue continue
# recognize command with context
try: try:
cmd, params = memory[0]['cmd'].checkContext(text).values() cmd, params = memory[0]['cmd'].checkContext(text).values()
if memory[0].get('params'): if memory[0].get('params'): params = {**memory[0].get('params'), **params}
params = {**memory[0].get('params'), **params}
except: except:
cmd, params = Command.reg_find(text).values() cmd, params = Command.reg_find(text).values()
# execute command
responce = cmd.start(params) responce = cmd.start(params)
# say answer
reply(responce) reply(responce)
# waiting answer on question
if responce['type'] == 'question':
print('\nYou: ', end='')
speech = listener.listen()
if speech['status'] == 'ok':
text = speech['text']
print(text)
if responce:= responce['callback'].answer(text): reply(responce)
# remember the command
memory.insert(0, { memory.insert(0, {
'text': text, 'text': text,
'cmd': cmd, 'cmd': cmd,
'responce': responce 'responce': responce,
}) })
else: else:
if speech['status'] == 'error': print('Отсутсвует подключение к интернету'); if speech['status'] == 'error': print('Отсутсвует подключение к интернету');