コード例 #1
0
def exec_commands():
    global sleep
    while sleep == 0:
        commands = cmd.get_commands()

        if "hira" in commands:
            if (len(commands) <= 10):  #if Previous command is only wake word
                str = "Hi sir."
                txt_out(str, 1, 1, 1)
                commands = cmd.get_commands()

            x = f.db.get_commands(commands)
            commands = commands.replace("\n", "")
            txt_out("cmd:" + commands + "  exec:" + x, 1, 1, 0)
            result = eval("f." + x + "('" + commands + "')")
            res = result.replace("::OK", "").replace("::FAIL", "")
            txt_out(res, 1, 1, 1)
            if "::OK" in result:
                f.db.insert_cmd_executed(commands, 1)
            else:
                f.db.insert_cmd_executed(commands, 0)
            if "reboot" in res:
                sleep = 1
                lnx_cmd = "sudo reboot"
                os.system(lnx_cmd)
            elif "shut down" in res:
                lnx_cmd = "sudo shutdown -h now"
                os.system(lnx_cmd)
コード例 #2
0
def main():
    if not path.isfile(ip_path):
        print("Check the IP path")
    elif not path.isfile(auth_path):
        print("Check the authentication path")
    elif not path.isfile(command_path):
        print("Check the commands path")
    else:
        list_ips = ip_list.get_ip_list(ip_path)
        user, pwd = ssh_auth.extract_user_password(auth_path)
        commands_ = commands.get_commands(command_path)

        print("Start sending commands...")

        threads = []

        for ip in list_ips:
            try:
                th = threading.Thread(target=ssh_connection.ssh_connect,
                                      args=(user, pwd, ip, commands_))
                th.start()
                threads.append(th)
            except AuthenticationException:
                print("Wrong username and password!")

        for th in threads:
            th.join()

        print("Done :)")
コード例 #3
0
ファイル: command_runner.py プロジェクト: olegyablokov/lemys
 def __load_commands(self):
     _Commands = get_commands()
     _CommandsDict = {}
     for _Command in _Commands:
         _Object = _Command(self.State)
         for name in _Object.names:
             _CommandsDict[name] = _Object
     return _CommandsDict
コード例 #4
0
def edit():

    res = get_events('', True)
    events = res['events']
    size = res['size']

    if request.method == 'GET':
        if (request.args):
            title = request.args.get('title')
            fromTitle = []
            club = request.args.get('club')
            fromClub = []
            if (title):
                for event in events:
                    title = title.lower()
                    if title in event['title'].lower():
                        fromTitle.append(event)

            if (club):
                for event in events:
                    club = club.lower()
                    if club in event['club'].lower():
                        fromClub.append(event)

            events = fromTitle
            for item in fromClub:
                present = False
                for event in events:
                    if (event['id'] == item['id']):
                        present = True
                if (not present):
                    events.append(item)
            size = len(events)
        return render_template('allEditor.html', events=events, size=size)

    else:
        data = request.form.to_dict()
        if (data['password'] == PASSWORD):
            commands = get_commands(data)

            cur = mysql.connection.cursor()

            for i in commands:
                try:
                    print("Executing: " + i)
                    cur.execute(i)
                except (MySQLdb.Error, MySQLdb.Warning) as e:
                    print(e)

            mysql.connection.commit()
            cur.close()

            return redirect('/')
        else:
            return "Incorrect Password"

        return 'POST'
コード例 #5
0
    def __init__(self, channel_id, connection):
        self.channel_id = channel_id
        self.connection = connection

        # Get the list of commands
        self.command_list = commands.get_commands()

        # Print available commands
        print(f'Commands: {commands.get_names()}')
コード例 #6
0
ファイル: main.py プロジェクト: davidmm01/py-toy-robot
def main():
    input_file_name = get_cli_arguments()
    board = Board(0, 0, 4, 4)
    robot = Robot()
    try:
        commands = get_commands(input_file_name)
    except InvalidCommand:
        print("INVALID COMMAND SUPPLIED, EXITING...")
        return
    for command in commands:
        robot.process_command(command, board)
コード例 #7
0
ファイル: help.py プロジェクト: ToxicFrog/doomrl-server
    def run(self, cmd):
        from inspect import getdoc

        if not cmd:
            for cmd in get_commands():
                print(getdoc(get_command(cmd)).split('\n')[0])
            return

        if not get_command(cmd):
            print('No such command. Try "help" for a list of all commands.')
        else:
            print(getdoc(get_command(cmd)))
コード例 #8
0
ファイル: help.py プロジェクト: ToxicFrog/doomrl-server
  def run(self, cmd):
    from inspect import getdoc

    if not cmd:
      for cmd in get_commands():
        print(getdoc(get_command(cmd)).split('\n')[0])
      return

    if not get_command(cmd):
      print('No such command. Try "help" for a list of all commands.')
    else:
      print(getdoc(get_command(cmd)))
コード例 #9
0
ファイル: space.py プロジェクト: krother/space
    def travel(self):
        while self.is_running:
            planet = self.ship.location
            shipreport = self.ship.get_report()
            planreport = planet.get_report()
            print('\n' * 30)
            print_twocolumn(planreport, shipreport)
            print("\nAvailable commands:")
            commands = get_commands(self.ship, planet)
            for cmd in commands:
                print("[%s] %s" % (cmd.key, cmd.description))
            print()

            key = input("What shall we do? ")
            for cmd in commands:
                if key == cmd.key:
                    print(key)
                    if views.SLOW_MOTION:
                        time.sleep(3)
                    cmd.execute()
コード例 #10
0
def test_get_commands_with_real_data(file_name, expected_num_commands):
    commands = get_commands(f'tests/in_spec_examples/{file_name}')
    assert len(commands) == expected_num_commands
コード例 #11
0
 def __init__(self):
     self.list_commands = get_list_commands()
     self.commands = get_commands()
     self.clean_commands = get_clean_commands()
     self.id_handler = id_handler()
     self.text_and_folder_converter = FolderAndTextConverter()
コード例 #12
0
from discord.ext import commands

import utils.utils
import commands as cmd
import events

DISCORD_BOT_TOKEN = os.environ.get('TOKEN')

# creating logger
logger = utils.utils.get_logger('discord bot', logging.INFO)

# creating bot
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
cmd.get_commands(bot)
events.get_events(bot, logger)

# Main function

if __name__ == '__main__':
    try:
        logger.info('Preparing to run bot...')
        bot.run(DISCORD_BOT_TOKEN)
    except Exception as e:
        import sys

        logger.error(sys.exc_info()[0])
        logger.error("---- -----")
        import traceback
コード例 #13
0
def get_bot(token):
    assert type(token) == str
    assert len(token) > 0
    return telegram.Bot(token)


def get_updater(token):
    return Updater(token=token)


if __name__ == '__main__':
    logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level = logging.INFO)

    redis_config = config_reader.get_redis_address_from_config(default_config_filename)
    redis_client = redis.StrictRedis(host=redis_config['ip'],
                                     port=redis_config['port'],
                                     db=0)

    token = config_reader.get_token_from_config(default_config_filename)
    bot = get_bot(token)
    updater = get_updater(token)

    commands = commands.get_commands(redis_client)

    dispatcher = updater.dispatcher
    for name, func in commands.items():
        handler = CommandHandler(name, func)
        dispatcher.add_handler(handler)

    updater.start_polling()
コード例 #14
0
ファイル: undulatus.py プロジェクト: grahame/undulatus
    def main():
        import readline, sys, os, threading, traceback
        from pprint import pprint

        from commands import get_commands
        from tracker import TweetTracker
        from timeline import TimelinePlayback, SearchPlayback
        import tweetdb, base64

        from twitter.oauth import OAuth, write_token_file, read_token_file
        from twitter.api import Twitter, TwitterError
        from twitter.api import TwitterHTTPError

        import argparse
        parser = argparse.ArgumentParser()
        parser.add_argument('--reauth', '-r', action='store_true', default=False, help="reauthenticate discarding existing tokens")
        parser.add_argument('screen_name', help="screen name")
        parser.add_argument('-u', default='http://localhost:5984', help="database URI")
        parser.add_argument('-d', default=None, help="database name")

        args = parser.parse_args()
        screen_name = args.screen_name
        srvuri = args.u
        dbname = args.d or args.screen_name.lower()
        reauth = args.reauth

        def obsc():
            # pretty pointless, and IMHO OAuth is broken for standalone, open source applications
            return [str(base64.decodebytes(t), encoding='utf8') for t in 
                    (b'aWdpcGRPVXp0dHJWVWF5Sk9kTVpLQQ==', b'Q1U2RHpFNzEwY1NFRGN3WnUzS0NsdEt1V0V0TmNqVVBVc1Zzb25abDVCOA==')]

        db = tweetdb.DBWrapper(app_path, screen_name, srvuri, dbname)
        oauth_doc, oauth_token, oauth_token_secret = db.tokens()

        if (oauth_token is None) or reauth:
            from twitter.oauth_dance import oauth_dance
            from tempfile import mkstemp
            fd, filepath = mkstemp()
            args = ["undulatus"] + obsc() + [filepath]
            oauth_dance(*args)
            oauth_token, oauth_token_secret = read_token_file(filepath)
            os.unlink(filepath)
            db.add_tokens(oauth_doc, oauth_token, oauth_token_secret)

        twitter = Twitter(
            auth=OAuth(
                oauth_token, oauth_token_secret, *obsc()),
            secure=True,
            api_version='1.1',
            domain='api.twitter.com')

        configuration = db.configuration()
        if configuration is None or (datetime.datetime.now() - datetime_strptime(configuration['updated'])).days > 1:
            print("retrieving twitter configuration.")
            new_config = twitter.help.configuration()
            configuration = db.save_configuration(new_config)

        tracker = TweetTracker(twitter, db)

        class TimelineUpdates(object):
            def __init__(self):
                self._lock = threading.Lock()
                self.thread = None
                self.update_delay = 60
                self._schedule = {}
                self.timelines = [
                        TimelinePlayback(tracker, twitter.statuses.home_timeline,
                            {'include_rts' : True, 'include_entities' : True}),
                        TimelinePlayback(tracker, twitter.statuses.mentions_timeline, {})]
                self.go_in(0)
                self.saved_search_playbacks = {}

            def update(self):
                def _update():
                    # try and suppress tweets that come through in multiple
                    # timelines, eg. @replies from people we follow
                    printed = set()
                    for timeline in self.timelines:
                        update = timeline.update()
                        if update is None:
                            print("timeline update failed: %s" % repr(timeline))
                            continue
                        recent = [tweet for tweet in update if tweet['id'] not in printed]
                        for tweet in recent:
                            printed.add(tweet['id'])
                        tracker.display_tweets(recent)
                def _update_searches():
                    saved_searches = db.saved_searches()
                    # manage search instances
                    existing = set(self.saved_search_playbacks)
                    required = set(saved_searches)
                    cancelled = existing - required
                    new = required - existing
                    for s in cancelled:
                        print("cancelled search: `%s'" % (s))
                        self.saved_search_playbacks.pop(s)
                    for s in new:
                        print("started search: `%s'" % (s))
                        self.saved_search_playbacks[s] = SearchPlayback(tracker,
                                twitter.search.tweets, {
                                    'q' : s,
                                    'result_type' : 'recent',
                                    'include_entities' : 't'
                                    })
                    # run and then print searches
                    printed = set()
                    for s in self.saved_search_playbacks:
                        timeline = self.saved_search_playbacks[s]
                        update = timeline.update()
                        if update is None:
                            print("search update failed (%s): %s" % (s, repr(timeline)))
                            continue
                        recent = [tweet for tweet in update if tweet['id'] not in printed]
                        for tweet in recent:
                            printed.add(tweet['id'])
                        tracker.display_tweets(recent)
                def _scheduled():
                    done = []
                    for cb in self._schedule.values():
                        try:
                            res = cb()
                        except Exception as e:
                            if isinstance(e, SystemExit):
                                raise
                            traceback.print_exc()
                        if not res:
                            done.append(id(cb))
                    for cb_id in done:
                        del self._schedule[cb_id]
                with self._lock:
                    try:
                        _scheduled()
                        _update()
                        _update_searches()
                    except TwitterHTTPError as e:
                        print("(twitter API error: %s)" % e)
                        return
                    except:
                        print("exception during timeline update")
                        last_tb.set(traceback.format_exc())
                    self.go_in(self.update_delay)

            def schedule(self, cb):
                with self._lock:
                    self._schedule[id(cb)] = cb

            def go_in(self, secs):
                if self.thread is not None:
                    self.thread.cancel()
                self.thread = threading.Timer(secs, self.update)
                self.thread.daemon = True
                self.thread.start()

        updates = TimelineUpdates()
        command_classes = get_commands(db, twitter, screen_name, tracker, updates, configuration['configuration'])

        class SmartCompletion(object):
            def __init__(self):
                self.last_s = None

            @classmethod
            def get_matches(cls, s):
                word = 0
                for (c1, c2) in pairwise(readline.get_line_buffer()):
                    if c2 == ' ' and c1 != ' ':
                        word += 1
                # command
                if word == 0 and s.startswith('/'):
                    return '', [x for x in list(command_classes.keys()) if x.startswith(s)]
                # word token, complete usernames
                prefix = ''
                if s.startswith('@'):
                    prefix = '@'
                    s = s[1:]
                return prefix, [x for x in tracker.seen_users if x.startswith(s)]

            def complete(self, s, state):
                if s != self.last_s:
                    self.prefix, self.matches = self.get_matches(s)
                    self.matches.sort()
                    self.last_s = s
                if state >= len(self.matches):
                    return None
                return self.prefix + self.matches[state] + ' '

        smart_complete = SmartCompletion()

        while True:
            line = get_line("%s> " % screen_name, smart_complete.complete)
            cmd = None
            arg = None
            if line.startswith('/'):
                cmd, arg = cmd_and_arg(line)
            else:
                cmd = '/say'
                arg = line.rstrip()
            ex = command_classes.get(cmd, None)
            if ex is not None:
                try:
                    cb = ex()(cmd[1:], arg)
                    # commands can return a callback function, which will then be 
                    # called each time update() is called until it returns False
                    if cb is not None:
                        updates.schedule(cb)
                except Exception as e:
                    if isinstance(e, SystemExit):
                        raise
                    traceback.print_exc()
            else:
                print("unknown command.")
コード例 #15
0
import boto3
import argparse
import commands
import func

ec2 = None

cmds = commands.get_commands()
while True:
    # func.print_ec2()
    args = input(">")
    args_list = args.split()
    if (len(args_list) < 1):
        print("Incorect command")
        continue
    if (args_list[0] == "exit"):
        quit()
    if (args_list[0] not in cmds.keys()):
        print("Incorect command:{0}".format(cmds.keys()))
        continue
    cmd = cmds.get(args_list[0])
    cmd_func = cmd[1]
    parser = cmd[0]
    try:
        parse_args = parser.parse_args(args_list[1:])
    except SystemExit:
        continue
    try:
        cmd_func(parse_args)
    except Exception as e:
        print("Error calling API:")