def __init__(self): self.log = logging.getLogger(__name__) self.name = config["server"]["user"] self.log.debug("Init Mumble") self.com = com_mumble.ComMumble(self.name, config["server"]["host"], int(config["server"]["port"]), config["server"]["home_channel"]) self.tag = self.com.get_tag() self.tag_len = len(self.tag) self.log.debug("Init DeepSpeech") self.voice = voice_deep_speech.VoiceDeepSpeech( config["deepspeech"]["model"], config["deepspeech"]["scorer"], config["deepspeech"]["record_wav"].lower() == "true", config["deepspeech"]["record_user"].split(",")) self.commands = commands.Command([self.name, self.tag]) self.commands_to_process = collections.deque() available_commands = self.commands.get_available_commands() self.voice.add_hot_words(available_commands) self.voice.add_hot_words([self.name.lower()], 20) self.follow = config["users"].get("follow", None)
def run_pyvuka_command(self, native_pyvuka_command): if not isinstance(native_pyvuka_command, str): raise ValueError(f'PyVuka command is not a valid string object!') try: return commands.Command(self)(native_pyvuka_command) except Exception as e: raise ValueError(f'Invalid PyVuka command!\n\t{str(e)}')
def parse_message(message, output = None): # Tokenize the message. The command should be the first word. tokens = message.split(' ') # Check how many tokens there are. tokens_count = len(tokens) # If there's at least one token, define the command used as the first item in the tokens list. command = tokens[0].lower() if tokens_count > 0 else None # Create command object for your command. command_object = commands.Command( tokens=tokens, message=message, ) # Check the main command map for the requested command. global command_map command_found = command_map.get(command) if command_found is not None: # Execute found command. return command_found(command_object) else: # Could not find the inputted command. response = "That is not a valid command." return response
async def on_message(self, msg): if self.is_our_message(msg): return # Process the message to generate a command object. cmd = commands.Command(msg) self.console_log(msg, cmd) # Reply will be sent if command was valid, or ignored otherwise. await cmd.send_reply_as(self)
def test_plusplus(self): slack_impl = slack.TestSlack() command = commands.Command({ 'text': u'@JohnG, @jorgeo for fs-slack', 'channel_name': u'testchan' }) expected = u'@JohnG\u200e++ (now at 1), @jorgeo\u200e++ (now at 1) for fs-slack' commands.plusplus(slack_impl, command) self.assertEqual(expected, slack_impl.last_payload['text']) # do it again expected = u'@JohnG\u200e++ (now at 2), @jorgeo\u200e++ (now at 2) for fs-slack' commands.plusplus(slack_impl, command) self.assertEqual(expected, slack_impl.last_payload['text'])
import logging from telegram.ext import CommandHandler from telegram.ext import MessageHandler, Filters from telegram.ext import Updater from py_translator import Translator from py_translator import LANGUAGES import commands import settings import model updater = Updater(token=settings.BOT_TOKEN) dispatcher = updater.dispatcher storage = model.Storage(settings.HOST, settings.DB) command_handler = commands.Command() def start(bot, update): command_handler.command_start(bot, update) def respond(bot, update): command_handler.command_respond(bot, update) def change_lang(bot, update): command_handler.command_change_lang(bot, update) def memebers(bot, update): command_handler.command_memebers(bot, update)
from apscheduler.schedulers.background import BackgroundScheduler def start(user_id, token, *args): define.scheduler[str(user_id)] = BackgroundScheduler() session = searchers.init_session(searchers.TLSAdapter()) link = None for s in args: if str(s).find("avito.ru") != -1: link = str(s) break if link == None: return "Ты что-то ввел неправильно :с \n Попробуй еще раз или напиши 'помощь'" define.scheduler[str(user_id)].add_job( lambda: searchers.continious_search(session, args[0], user_id, token, define.proxies), "interval", seconds=randint(int(define.update_time.get(str(user_id), 3) * 6 * 9), int(define.update_time.get(str(user_id), 3) * 11 * 6))) define.scheduler[str(user_id)].start() return "Хорошо, начинаем" start_command = commands.Command() start_command.keys = ["старт", "start", "go"] start_command.description = "запустить меня. добавь через пробел ссылку на нужный тебе поиск в авито и я буду присылать уведомления о новых сообщениях там\n\nпример: start https://www.avito.ru/moskva/kvartiry?s=104&s_trg=11" start_command.process = start
def chatLoop(cls): import commands room = '' while True: rawMessage = cls.ws.recv() username = cls.getUsername(rawMessage, 3) room = cls.getRoom(rawMessage, room) message = cls.getMessage(rawMessage) isPM = False if rawMessage[:8].find('|pm|') != -1: isPM = True username = cls.getUsername(rawMessage, 2) n = message.find(' ') if n == -1: n = len(message) if message[1:n] in Bot.availableCommands and message[0] in Bot.cfg[ 'config']['commmand_characters']: try: x = commands.Command(message[1:n], message[n + 1:], room, username, isPM) if Bot.cfg['commands'][message[1:n]][ 'function'] == 'reload': # reload only if x.canUse: cls.reloadCommands(cls, room) cls.sendMessage( commands.Command( 'reload', 'Commands and config reloaded successfully!', room, username, isPM)) continue else: cls.sendMessage( commands.Command('reload', 'Invalid permissions.', room, username, True)) func = getattr( commands, Bot.cfg['commands'][message[1:n]]['function']) x = func(message[1:n], message[n + 1:], room, username, isPM) if x == None: pass elif not x.canUse: cls.sendMessage( commands.Command(message[1:n], 'Invalid permissions.', room, username, True)) elif x.isEnabled == False: cls.sendMessage( commands.Command(message[1:n], 'Command disabled.', room, username, True)) else: print(x.command) print(x.message) cls.sendMessage(x) except Exception as e: cls.sendMessage( commands.Command( 'say', 'Wew, an error. In case developers (minnow) are curious: ' + str(e), room, username, isPM)) pass
def parse_cmd(cmd): return commands.Command(cmd)
import commands import asyncio import functools from threading import Thread test = commands.Command([('000000000010', 0)]) def start_loop(loop): asyncio.set_event_loop(loop) loop.run_forever() commandloop = asyncio.new_event_loop() t = Thread(target=start_loop, args=(commandloop, )) t.start() #test.run(commandloop, None) ser = commands.ser ser.write(b'\xFF') print(ser.readline()) ser.write(b'\xF0')
def __init__(self): QtGui.QWidget.__init__(self) self.setupUi(self) self.command = commands.Command(self.frame)
def handle(self): if self.cmd_handler is None: self.initiate() while True: self.data = self.rfile.readline().strip() if not self.data: break # print("raw_data", self.data) self.data = self.data.decode() if self.data != "" and not self.distance_interrupt: cmd = commands.Command(command_string=self.data) self.cmd_handler.addCommand(cmd) movementCommand = self.cmd_handler.lastCommand( commands.COMMAND_TYPE_AUTOPILOT) if movementCommand is not None and movementCommand.type == commands.COMMAND_TYPE_AUTOPILOT: direction = movementCommand.arguments[-1] current_direction = self.steering_motor.current_direction() if direction == "FORWARD": print("Direction(Must be):", direction) elif direction == "LEFT": print("Direction(Must be):", direction) elif direction == "RIGHT": print("Direction(Must be):", direction) if direction == "FORWARD": # self.steering_motor.stop() self.steering_motor.forward_dir() self.motor.forward(speed=50) elif direction == "RIGHT": # self.steering_motor.stop() self.steering_motor.right() elif direction == "LEFT": # self.steering_motor.stop() self.steering_motor.left() elif direction == "STOP": self.motor.stop() self.steering_motor.forward_dir() self.steering_motor.stop() if movementCommand is not None and movementCommand.type == commands.COMMAND_TYPE_MOVEMENT_CONTROL: yaxis = int(movementCommand.arguments[1]) xaxis = int(movementCommand.arguments[0]) if xaxis > 50: self.steering_motor.right() elif xaxis < 50: self.steering_motor.left() else: self.steering_motor.stop() if yaxis > 50: self.motor.forward(speed=50) elif yaxis < 50: self.motor.backward(speed=50) else: self.motor.stop() print("Movement Control data:", self.data, " xaxis:", xaxis, "yaxis:", yaxis) #self.wfile.write(("%s %s\n" % (xaxis, yaxis)).encode()) self.get_measurement = False self.steering_motor.cleanup() self.motor.cleanup() self.rightw_button.cleanup() self.leftw_button.cleanup() self.forwardw_button.cleanup()
import commands def help(*args): msg = "Напиши:\n" for cmd in commands.cmds: msg += "◾ '" + cmd.keys[0] + "' - " + cmd.description + '\n' return msg help_command = commands.Command() help_command.keys = ["помощь", "помоги", "что", "help", "?"] help_command.description = "открою справку" help_command.process = help
def main(): com = commands.Command() com.event_loop() start = Vipercmd() start.cmd_loop()
def cmd_loop(self): while not self.done: commands.Command().event_loop()
import commands import define def tick(user_id, token, *args): time = define.update_time.get(str(user_id), 3) for num in args: try: time = int(num) except: continue define.update_time[str(user_id)] = time return f"Договорились, буду писать не чаще раза в {define.update_time.get(str(user_id), 3)} мин. ⌛" tick_command = commands.Command() tick_command.keys = ["тик", "tick", "время", "update"] tick_command.description = "введи 'тик [время_в_минутах]' и так часто я буду проверять новые объявления.\nпо умолчанию стоит 3 мин." tick_command.process = tick
import commands, random cmd = commands.Command() cmd.event("randint")( lambda args: str(random.randint(int(args[0]), int(args[1])))) @cmd.event("randomcase") def randomcase(args: list) -> str: res = "" for i in " ".join(args): if random.randint(0, 1): res += i.lower() else: res += i.upper() return res
import commands import define def stop(user_id, token, *args): if str(user_id) in define.scheduler.keys(): define.scheduler[str(user_id)].shutdown(wait=False) define.scheduler.pop(str(user_id), None) return "Окей, заканчиваю. Если что - знаешь, где меня найти 😉" else: return "Мы и не начинали вроде как(:" stop_command = commands.Command() stop_command.keys = ["стоп", "остановись", "выход", "stop"] stop_command.description = "завершу свою работу и перестану тебя донимать сообщениями" stop_command.process = stop