예제 #1
0
def answer(vk, settings, config, object):
    editor = settings['editor']
    user_id = object.message['from_id']

    if 1 == commands.isMember(vk,
                              token=settings['token'],
                              group_id=settings['group_id'],
                              user_id=user_id):
        if user_id == editor:
            if object.message['text'].lower(
            ) == 'принять' or object.message['text'].lower() == 'отклонить':
                commands.editor_answer(vk, settings, config, object)
            if object.message['text'].lower() == 'заявки':
                commands.req(vk, settings, config, object)

        table = commands.check_in_table(user_id)
        if table:
            if table == 'create_reminder':
                commands.create_reminder(vk, settings, config, object)
            elif table == 'del_reminders':
                commands.del_reminder(vk, settings, config, object)
        elif object.message['text'].lower() == 'создать напоминание':
            commands.create_reminder(vk, settings, config, object)
        elif object.message['text'].lower() == 'мои напоминания':
            commands.show_reminders(vk, settings, config, object)
        elif object.message['text'].lower() == 'удалить напоминания':
            commands.del_reminder(vk, settings, config, object)
        elif object.message['text'].lower() == 'таблица занятости':
            commands.table(vk, settings, config, object)
        elif object.message['text'].lower() == 'предложить идею':
            commands.idea(vk, settings, config, object)
        else:
            commands.start(vk, settings, config, object)
    else:
        introduction.intr(vk, settings, config, object)
예제 #2
0
def main():
    logging.basicConfig(
        format="[%(asctime)s] [%(levelname)s] [%(name)s] "
        "[%(funcName)s():%(lineno)s] [PID:%(process)d TID:%(thread)d] "
        "%(message)s",
        level=logging.DEBUG)
    updater = Updater(token=secret.token, use_context=True)
    # updater.dispatcher.add_error_handler(on_error)
    updater.dispatcher.add_handler(
        CommandHandler(['start', 'help'], start(messages.start)))
    updater.dispatcher.add_handler(
        ConversationHandler(
            entry_points=[CommandHandler('register', register_start)],
            states={
                "waiting for password":
                [MessageHandler(Filters.text, received_password)]
            },
            fallbacks=[CommandHandler('cancel', cancel)]))
    updater.dispatcher.add_handler(CommandHandler('unregister', unregister))
    updater.dispatcher.add_handler(CommandHandler('status', register_status))

    updater.dispatcher.add_handler(CommandHandler('list_users', list_users))
    updater.dispatcher.add_handler(
        CommandHandler('shrug', start(messages.shrug)))

    # updater.job_queue.run_once(
    #     start_ss,
    #     datetime.datetime.now() + datetime.timedelta(seconds=2),
    #     context=updater)
    updater.job_queue.run_once(start_ss, DAY_X, context=updater)
    updater.start_polling()
예제 #3
0
def _add_handlers(updater):
    for group, handlers in updater.dispatcher.handlers.items():
        updater.dispatcher.handlers[group] = []
    updater.dispatcher.add_handler(
        CommandHandler(['start', 'help'], start(messages.ss_help)))
    updater.dispatcher.add_handler(
        ConversationHandler(
            entry_points=[CommandHandler('temudaje', message_start)],
            states={
                'waiting for message': [
                    MessageHandler(Filters.text,
                                   received_message('taker_chat_id'))
                ]
            },
            fallbacks=[CommandHandler('cancel', cancel)]))
    updater.dispatcher.add_handler(
        ConversationHandler(
            entry_points=[CommandHandler('santa', message_start)],
            states={
                'waiting for message': [
                    MessageHandler(Filters.text,
                                   received_message('giver_chat_id'))
                ]
            },
            fallbacks=[CommandHandler('cancel', cancel)]))
    updater.dispatcher.add_handler(
        CommandHandler('shrug', start(messages.shrug)))
예제 #4
0
def handle(msg):
    chat_id = msg['chat']['id']
    command = msg['text']

    print('Got command: %s from chat_id: %d' % (command, chat_id))

    if (command == "/start" or command == "/start@UbuntuCat_bot"):
        commands.start(bot, chat_id)
    elif (command == "/ordredia" or command == "/ordredia@UbuntuCat_bot"):
        commands.ordredia(bot, chat_id)
예제 #5
0
def handle_args(args):
    if args.recordings:
        commands.recordings()
    elif args.reset:
        commands.reset()
    elif args.setup:
        commands.setup()
    elif args.show:
        commands.show()
    elif args.start:
        commands.start(args.start)
    elif args.stop:
        commands.stop(args.stop)
    elif args.teardown:
        commands.teardown()
    else:
        print("You must select an argument.")
예제 #6
0
    def __init__(self, setup=False):
        super(Sms, self).__init__()
        self.daemon = True
        self.cancelled = False

        if setup:
            self.cancelled = True

        # if not using sms exit
        if not cm.sms.enable:
            self.cancelled = True
            sys.exit()

        levels = {
            'DEBUG': logging.DEBUG,
            'INFO': logging.INFO,
            'WARNING': logging.WARNING,
            'ERROR': logging.ERROR,
            'CRITICAL': logging.CRITICAL
        }

        # set logging level from config or command line if used
        try:
            level = levels.get(args.log.upper(), logging.NOTSET)
        except NameError:
            level = levels.get(cm.sms.log_level, logging.NOTSET)

        logging.getLogger().setLevel(level)

        try:
            self.playlist = args.playlist
        except NameError:
            self.playlist = cm.sms.playlist_path

        self.songs = list()
        logging.info('loading playlist ' + self.playlist)

        self.load_playlist()
        commands.start(cm)
        self.voice = Voice()
예제 #7
0
def main_loop():
    global connected, prev_time, running
    notification.show("Starting Proccess!")
    Logger.log("Starting up program.")
    playlist_list = dataAccess.load_songs()
    while running:
        if not paused:
            if connected:
                for playlist in playlist_list:
                    main_process(playlist)
                    dataAccess.json_pickle(playlist_list)
                    #dataAccess.load_song(playlist_list)
                prev_time = time.time()

            if not dataAccess.internet_connection():
                if connected:
                    notification.show("No Internet Connection")
                    Logger.log("Disconnected from internet")
                    connected = False
            else:
                if not connected:
                    notification.show("Connected")
                    Logger.log("Connected to the internet")
                    connected = True

        loaded_config = dataAccess.load_config()
        current_globals = globals()
        for con_vars in loaded_config.keys():
            current_globals[con_vars] = loaded_config[con_vars]

        if restart:
            import commands
            commands.start()
            running = False

        # running = 0

        time.sleep(5)
예제 #8
0
def start(args):
    """
    provide a argparse namespace object.
    Calls the start command
    """
    commands.start(args.task)
예제 #9
0
파일: source.py 프로젝트: dderenok/Skaffer
def main():

    new_offset = None

    while True:
        # Получение информации с сервера
        skaffer.get_updates(new_offset)
        last_update = skaffer.get_last_update()

        # При получении непустого ответа с сервера
        if last_update != {}:

            try:
                last_update_id = last_update['update_id']
                last_chat_text = last_update['message']['text'].lower()
                last_chat_id = last_update['message']['chat']['id']
                last_chat_name = last_update['message']['chat']['first_name']
            except KeyError as key_error_message:
                print("Exception while obtaining data from server",
                      key_error_message)

            if last_chat_text in start_dict:
                commands.start(last_chat_id, last_chat_name)
            elif last_chat_text in weather_dict:
                commands.weather(last_chat_id)
            elif last_chat_text in next_dict:
                commands.next(last_chat_id)
            elif last_chat_text in help_dict:
                commands.help(last_chat_id)
            elif last_chat_text in tt_dict:
                commands.timetable(last_chat_id)
            elif last_chat_text in tod_dict:
                commands.today_timetable(last_chat_id)
            elif last_chat_text in tom_dict:
                commands.tomorrow_timetable(last_chat_id)
            elif last_chat_text in bus47_dict:
                bus_command.bus(last_chat_id)
            elif last_chat_text == 'курчатова':
                bus_command.kurch(last_chat_id)
            elif last_chat_text == 'факультет радиофизики':
                bus_command.raf(last_chat_id)
            elif last_chat_text in alt_dict:
                commands.alt(last_chat_id)
            elif last_chat_text in greet_dict:
                greet_msg = last_chat_text
                greet_msg += ', '
                greet_msg += last_chat_name
                greet_msg += ' :)'
                skaffer.send_message(last_chat_id, greet_msg)
            else:
                err_msg = 'Я тебя не понял, '
                err_msg += last_chat_name
                err_msg += ' :(\nИспользуй /help, чтобы узнать, что я умею'
                skaffer.send_message(last_chat_id, err_msg)

            log = ''
            log += str(last_chat_id)
            log += ' typed '
            log += '['
            log += last_chat_text
            log += ']'
            print(log)

            new_offset = last_update_id + 1
def main():
    """Process sms messages

    Download and process all sms messages from a Google Voice account.
    Runs in a loop that is executed every 15 seconds
    """
    # Load playlist from file, notifying users of any of their requests that have now played
    logging.info('loading playlist ' + args.playlist)
    start_commands = False
    while True:
        with open(args.playlist, 'rb') as playlist_fp:
            fcntl.lockf(playlist_fp, fcntl.LOCK_SH)
            playlist = csv.reader(playlist_fp, delimiter='\t')
            songs = []

            for song in playlist:
                logging.debug(song)

                if len(song) < 2 or len(song) > 4:
                    logging.error('Invalid playlist.  Each line should be in the form: '
                                  '<song name><tab><path to song>')
                    logging.warning('Removing invalid entry')
                    print "Error found in playlist"
                    print "Deleting entry:", song
                    continue
                elif len(song) == 2:
                    song.append(set())
                elif len(song) >= 3:
                    # Votes for the song are stored in the 3rd column
                    song[2] = set(song[2].split(','))

                    if len(song) == 4:
                        # Notification of a song being played is stored in the 4th column
                        song_played(song)
                        del song[3]
                        song[2] = set()

                songs.append(song)

            fcntl.lockf(playlist_fp, fcntl.LOCK_UN)

        logging.info('loaded %d songs from playlist', len(songs))
        cm.set_playlist(songs)

        if not start_commands:
            commands.start(cm)
            start_commands = True

        # Parse and act on any new sms messages
        messages = VOICE.sms().messages
        for msg in extract_sms(VOICE.sms.html):
            logging.debug(str(msg))
            response = commands.execute(msg['text'], msg['from'])
            if response:
                logging.info('Request: "' + msg['text'] + '" from ' + msg['from'])

                try:
                    if isinstance(response, basestring):
                        VOICE.send_sms(msg['from'], response)
                    else:
                        # Multiple parts, send them with a delay in hopes to avoid
                        # them being received out of order by the recipient.
                        for part in response:
                            VOICE.send_sms(msg['from'], str(part))
                            time.sleep(2)
                except ValidationError as v_error:
                    logging.warn(
                        str(v_error) + ': Error sending sms response (command still executed)',
                        exc_info=1)

                logging.info('Response: "' + str(response) + '"')
            else:
                logging.info('Unknown request: "' + msg['text'] + '" from ' + msg['from'])
                VOICE.send_sms(msg['from'], cm.sms.unknown_command_response)

        # Update playlist with latest votes
        with open(args.playlist, 'wb') as playlist_fp:
            fcntl.lockf(playlist_fp, fcntl.LOCK_EX)
            writer = csv.writer(playlist_fp, delimiter='\t')
            for song in songs:
                if len(song[2]) > 0:
                    song[2] = ",".join(song[2])
                else:
                    del song[2]
            writer.writerows(songs)
            fcntl.lockf(playlist_fp, fcntl.LOCK_UN)

        # Delete all messages now that we've processed them
        for msg in messages:
            msg.delete(1)

        if args.setup:
            break
        time.sleep(15)
예제 #11
0
파일: run.py 프로젝트: smilliken/mut
def main():
    if not sys.argv:
        raise InvalidUsageException()
    argv = sys.argv[1:] # chop off script name as first arg
    try:
        command = argv[0]
    except IndexError:
        raise InvalidUsageException()
    if command == '--help':
        usage()
    elif argv[-1] == '--help':
        usage(command)
    elif command == 'init':
        try:
            repo_name = argv[1]
        except IndexError:
            raise InvalidUsageException('repo_name is required.')
        commands.init(repo_name)
    elif command == 'switch':
        try:
            repo_name = argv[1]
        except IndexError:
            raise InvalidUsageException('repo_name is required.')
        commands.switch(repo_name)
    elif command == 'add-remote':
        try:
            repo_uri = argv[1]
        except IndexError:
            raise InvalidUsageException('repo_uri is required.')
        try:
            remote_name = argv[2]
        except IndexError:
            remote_name = None
        commands.add_remote(repo_uri, remote_name=remote_name)
    elif command == 'drop-remote':
        try:
            remote_name = argv[1]
        except IndexError:
            raise InvalidUsageException('remote_name is required.')
        commands.drop_remote(remote_name)
    elif not active_repo:
        raise InvalidUsageException('no active repository, must init or switch to a repository.')
    elif command == 'ls':
        flags = _parse_flags(argv[1:])
        commands.ls(tags=flags['tags'], neg_tags=flags['neg_tags'])
    elif command == 'add':
        try:
            description = argv[1]
        except IndexError:
            raise InvalidUsageException('Task description is required.')
        flags = _parse_flags(argv[2:])
        if flags['neg_tags']:
            raise InvalidUsageException('Negative tags not valid when adding task.')
        for tag in flags['tags']:
            if tag in reserved_tags:
                raise InvalidUsageException('That tag is reserved. The following tags are automatically attached to tasks: %s.' % ', '.join(reserved_tags))
        commands.add(description, priority=flags['priority'], tags=flags['tags'])
    elif command == 'mod':
        try:
            id = argv[1]
        except IndexError:
            raise InvalidUsageException('id is required.')
        flags = _parse_flags(argv[2:])
        for tag in flags['tags'] + flags['neg_tags']:
            if tag in reserved_tags:
                raise InvalidUsageException('That tag is reserved. The following tags are automatically attached to tasks: %s.' % ', '.join(reserved_tags))
        commands.mod(id, priority=flags['priority'], tags=flags['tags'], neg_tags=flags['neg_tags'])
    elif command == 'edit':
        try:
            id = argv[1]
        except IndexError:
            raise InvalidUsageException('id is required.')
        flags = _parse_flags(argv[2:])
        if flags['priority'] or flags['tags'] or flags['neg_tags']:
            raise InvalidUsageException('Invalid options specified.')
        commands.edit(id)
    elif command == 'start':
        try:
            id = argv[1]
        except IndexError:
            raise InvalidUsageException('id is required.')
        flags = _parse_flags(argv[2:])
        if flags['priority'] or flags['tags'] or flags['neg_tags']:
            raise InvalidUsageException('Invalid options specified.')
        commands.start(id)
    elif command == 'stop':
        try:
            id = argv[1]
        except IndexError:
            raise InvalidUsageException('id is required.')
        flags = _parse_flags(argv[2:])
        if flags['priority'] or flags['tags'] or flags['neg_tags']:
            raise InvalidUsageException('Invalid options specified.')
        commands.stop(id)
    elif command == 'finish':
        try:
            id = argv[1]
        except IndexError:
            raise InvalidUsageException('id is required.')
        flags = _parse_flags(argv[2:])
        if flags['priority'] or flags['tags'] or flags['neg_tags']:
            raise InvalidUsageException('Invalid options specified.')
        commands.finish(id)
    elif command == 'rm':
        try:
            id = argv[1]
        except IndexError:
            raise InvalidUsageException('id is required.')
        flags = _parse_flags(argv[2:])
        if flags['priority'] or flags['tags'] or flags['neg_tags']:
            raise InvalidUsageException('Invalid options specified.')
        commands.rm(id)
    else:
        raise InvalidUsageException('Unrecognized command: %s.' % command)
예제 #12
0
def main():
    """Process sms messages

    Download and process all sms messages from a Google Voice account.
    Runs in a loop that is executed every 15 seconds
    """
    # Load playlist from file, notifying users of any of their requests that have now played
    logging.info('loading playlist ' + args.playlist)
    start_commands = False
    while True:
        with open(args.playlist, 'rb') as playlist_fp:
            fcntl.lockf(playlist_fp, fcntl.LOCK_SH)
            playlist = csv.reader(playlist_fp, delimiter='\t')
            songs = []

            for song in playlist:
                logging.debug(song)

                if len(song) < 2 or len(song) > 4:
                    logging.error(
                        'Invalid playlist.  Each line should be in the form: '
                        '<song name><tab><path to song>')
                    logging.warning('Removing invalid entry')
                    print "Error found in playlist"
                    print "Deleting entry:", song
                    continue
                elif len(song) == 2:
                    song.append(set())
                elif len(song) >= 3:
                    # Votes for the song are stored in the 3rd column
                    song[2] = set(song[2].split(','))

                    if len(song) == 4:
                        # Notification of a song being played is stored in the 4th column
                        song_played(song)
                        del song[3]
                        song[2] = set()

                songs.append(song)

            fcntl.lockf(playlist_fp, fcntl.LOCK_UN)

        logging.info('loaded %d songs from playlist', len(songs))
        cm.set_playlist(songs)

        if not start_commands:
            commands.start(cm)
            start_commands = True

        # Parse and act on any new sms messages
        messages = VOICE.sms().messages
        for msg in extract_sms(VOICE.sms.html):
            logging.debug(str(msg))
            response = commands.execute(msg['text'], msg['from'])
            if response:
                logging.info('Request: "' + msg['text'] + '" from ' +
                             msg['from'])

                try:
                    if isinstance(response, basestring):
                        VOICE.send_sms(msg['from'], response)
                    else:
                        # Multiple parts, send them with a delay in hopes to avoid
                        # them being received out of order by the recipient.
                        for part in response:
                            VOICE.send_sms(msg['from'], str(part))
                            time.sleep(2)
                except ValidationError as v_error:
                    logging.warn(
                        str(v_error) +
                        ': Error sending sms response (command still executed)',
                        exc_info=1)

                logging.info('Response: "' + str(response) + '"')
            else:
                logging.info('Unknown request: "' + msg['text'] + '" from ' +
                             msg['from'])
                VOICE.send_sms(msg['from'], cm.sms.unknown_command_response)

        # Update playlist with latest votes
        with open(args.playlist, 'wb') as playlist_fp:
            fcntl.lockf(playlist_fp, fcntl.LOCK_EX)
            writer = csv.writer(playlist_fp, delimiter='\t')
            for song in songs:
                if len(song[2]) > 0:
                    song[2] = ",".join(song[2])
                else:
                    del song[2]
            writer.writerows(songs)
            fcntl.lockf(playlist_fp, fcntl.LOCK_UN)

        # Delete all messages now that we've processed them
        for msg in messages:
            msg.delete(1)

        if args.setup:
            break
        time.sleep(15)