<commit_before>#!/usr/bin/env python3

print('Loading...')

import subprocess, sys, json, time, os

# Color class used to print colors
class colors:
	PURPLE = '\033[95m'
	BLUE = '\033[94m'
	GREEN = '\033[92m'
	YELLOW = '\033[93m'
	RED = '\033[91m'
	BOLD = '\033[1m'
	UNDERLINE = '\033[4m'
	END = '\033[0m'

def print_help():
	print(colors.YELLOW + 'Usage:    ' + sys.argv[0] + ' interface [options | filename]')
	print('Options:')
	print('    -t | txt file output')
	print('    -j | json file output')
	print('    -o | txt and json file output (don\'t write file extension in filename)' + colors.END)

# Analyze argv to extract interface
interface = ''
output_file_mode = 'no'
output_filename = ''
if len(sys.argv) != 4 and len(sys.argv) != 2:
	print(colors.RED + 'ERROR: wrong arguments' + colors.END)
	print_help()
	exit()
else:
	interface = sys.argv[1]
	if len(sys.argv) == 4:
		if sys.argv[2] == '-j':
			output_file_mode = 'json'
			output_filename = sys.argv[3]
			if output_filename[-4:] != output_file_mode:
				print(colors.RED + 'ERROR: file extension' + colors.END)
				exit()
		elif sys.argv[2] == '-t':
			output_file_mode = 'txt'
			output_filename = sys.argv[3]
			if output_filename[-3:] != output_file_mode:
				print(colors.RED + 'ERROR: file extension' + colors.END)
				exit()
		elif sys.argv[2] == '-o':
			output_file_mode = 'both'
			output_filename = sys.argv[3]
		else:
			print(colors.RED + 'ERROR: wrong arguments' + colors.END)
			print_help()
			exit()

script_path = os.path.dirname(os.path.abspath(__file__)) + '/'

# Open JSON
try:
	people_file = open(script_path + 'people.json', 'r')
	people_json = json.load(people_file)
except:
	print(colors.RED + 'ERROR opening people.json' + colors.END)
	exit()

# Make people list
max_cycles = 30
people = []
allowed = '1234567890abcdef:'
for person_dict in people_json['people']:
	person_dict['target'] = person_dict['target'].lower()
	for c in person_dict['target']:
		if c not in allowed:
			print(colors.RED + 'ERROR: invalid character found in one or more MAC addresses' + colors.END)
			exit()
	if len(person_dict['target']) == 17:
		person_dict['target'] = person_dict['target'][9:]
	people.append(person_dict)
for person_dict in people:
	person_dict['lastSeen'] = max_cycles

def execute_process(bash_command):
    return subprocess.Popen(bash_command.split(), stdout=subprocess.PIPE)

# Main cycle,
arp_command = 'sudo arp-scan --interface ' + interface + ' --localnet'
while True:
	print()
	output = execute_process(arp_command)
	#file_txt = ''
	#file_json = ''
	if output_file_mode != 'no':
		if output_file_mode != 'both':
			file = open(output_filename, 'w')
		else:
			file_txt = open(output_filename + '.txt', 'w')
			file_json = open(output_filename + '.json', 'w')
	for line in output.stdout.readlines():
		line = line.decode('utf8')
		for split in line.split():
			if len(split) == 17:    # A MAC address is 17 characters long
				mac =  split[9:]    # Only the last 3 bytes of the MAC address are taken into account, to ensure compatibility with some network devices which may change the vendor part of MAC addresses
				for person in people:
					if mac == person['target']:
						person['lastSeen'] = -1    # The counter is set to -1 because every counter will be incremented in the next 'for' cycle
	for person in people:
		if person['lastSeen'] < max_cycles:
			person['lastSeen'] += 1
			print(colors.GREEN + person['name'] + ' is @ home ' + colors.END)
			if output_file_mode == 'txt':
				file.write(person['name'] + ' is @ home\n')
			elif output_file_mode == 'both':
				file_txt.write(person['name'] + ' is @ home\n')
		else:
			print(colors.PURPLE + person['name'] + ' is away ' + colors.END)
			if output_file_mode == 'txt':
				file.write(person['name'] + ' is away \n')
			elif output_file_mode == 'both':
				file_txt.write(person['name'] + ' is away \n')

	if output_file_mode != 'no':
		if output_file_mode == 'json':
			json.dump(people, file)
		elif output_file_mode == 'both':
			json.dump(people, file_json)
		try:
			file_txt.close()
			file_json.close()
		except:
			file.close()
	time.sleep(30)
<commit_msg>Update JSON export<commit_after>#!/usr/bin/env python3

print('Loading...')

import subprocess, sys, json, time, os

# Color class used to print colors
class colors:
	PURPLE = '\033[95m'
	BLUE = '\033[94m'
	GREEN = '\033[92m'
	YELLOW = '\033[93m'
	RED = '\033[91m'
	BOLD = '\033[1m'
	UNDERLINE = '\033[4m'
	END = '\033[0m'

def print_help():
	print(colors.YELLOW + 'Usage:    ' + sys.argv[0] + ' interface [options | filename]')
	print('Options:')
	print('    -t | txt file output')
	print('    -j | json file output')
	print('    -o | txt and json file output (don\'t write file extension in filename)' + colors.END)

# Analyze argv to extract interface
interface = ''
output_file_mode = 'no'
output_filename = ''
if len(sys.argv) != 4 and len(sys.argv) != 2:
	print(colors.RED + 'ERROR: wrong arguments' + colors.END)
	print_help()
	exit()
else:
	interface = sys.argv[1]
	if len(sys.argv) == 4:
		if sys.argv[2] == '-j':
			output_file_mode = 'json'
			output_filename = sys.argv[3]
			if output_filename[-4:] != output_file_mode:
				print(colors.RED + 'ERROR: file extension' + colors.END)
				exit()
		elif sys.argv[2] == '-t':
			output_file_mode = 'txt'
			output_filename = sys.argv[3]
			if output_filename[-3:] != output_file_mode:
				print(colors.RED + 'ERROR: file extension' + colors.END)
				exit()
		elif sys.argv[2] == '-o':
			output_file_mode = 'both'
			output_filename = sys.argv[3]
		else:
			print(colors.RED + 'ERROR: wrong arguments' + colors.END)
			print_help()
			exit()

script_path = os.path.dirname(os.path.abspath(__file__)) + '/'

# Open people.json
try:
	people_file = open(script_path + 'people.json', 'r')
	people_json = json.load(people_file)
except:
	print(colors.RED + 'ERROR opening people.json' + colors.END)
	exit()

# Make people list
max_cycles = 30
people = []
allowed = '1234567890abcdef:'
for person_dict in people_json['people']:
	person_dict['target'] = person_dict['target'].lower()
	for c in person_dict['target']:
		if c not in allowed:
			print(colors.RED + 'ERROR: invalid character found in one or more MAC addresses' + colors.END)
			exit()
	if len(person_dict['target']) == 17:
		person_dict['target'] = person_dict['target'][9:]
	people.append(person_dict)
for person_dict in people:
	person_dict['lastSeen'] = max_cycles

def execute_process(bash_command):
    return subprocess.Popen(bash_command.split(), stdout=subprocess.PIPE)

def create_json(file):
	json_obj = []
	for person in people:
		temp_dict = {}
		temp_dict['name'] = person['name']
		temp_dict['target'] = person['target']
		if person['lastSeen'] < max_cycles:
			temp_dict['home'] = True
		else:
			temp_dict['home'] = False
		json_obj.append(temp_dict)
	json.dump(json_obj, file)

# Main cycle,
arp_command = 'sudo arp-scan --interface ' + interface + ' --localnet'
while True:
	print()
	output = execute_process(arp_command)
	if output_file_mode != 'no':
		if output_file_mode != 'both':
			file = open(output_filename, 'w')
		else:
			file_txt = open(output_filename + '.txt', 'w')
			file_json = open(output_filename + '.json', 'w')
	for line in output.stdout.readlines():
		line = line.decode('utf8')
		for split in line.split():
			if len(split) == 17:    # A MAC address is 17 characters long
				mac =  split[9:]    # Only the last 3 bytes of the MAC address are taken into account, to ensure compatibility with some network devices which may change the vendor part of MAC addresses
				for person in people:
					if mac == person['target']:
						person['lastSeen'] = -1    # The counter is set to -1 because every counter will be incremented in the next 'for' cycle
	for person in people:
		if person['lastSeen'] < max_cycles:
			person['lastSeen'] += 1
			print(colors.GREEN + person['name'] + ' is @ home ' + colors.END)
			if output_file_mode == 'txt':
				file.write(person['name'] + ' is @ home\n')
			elif output_file_mode == 'both':
				file_txt.write(person['name'] + ' is @ home\n')
		else:
			print(colors.PURPLE + person['name'] + ' is away ' + colors.END)
			if output_file_mode == 'txt':
				file.write(person['name'] + ' is away \n')
			elif output_file_mode == 'both':
				file_txt.write(person['name'] + ' is away \n')

	if output_file_mode != 'no':
		if output_file_mode == 'json':
			create_json(file)
		elif output_file_mode == 'both':
			create_json(file_json)
		try:
			file_txt.close()
			file_json.close()
		except:
			file.close()
	time.sleep(30)
<|endoftext|>


<commit_before>#! /usr/bin/python

import cwiid
import time

def makeConnection():
  print "Press 1 + 2 on the wiimote yo"
  wm = cwiid.Wiimote()
  wm.led = 1
  wm.enable(cwiid.FLAG_MOTIONPLUS)
  wm.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC
  print "you be connected"
  return wm

def accelerationDir(wiimote):
  ax = 0
  ay = 0
  az = 0
  messages = wiimote.get_mesg()
  for mesg in messages:
    if mesg[0] == cwiid.MESG_ACC:
        ax = (((mesg[1][cwiid.X])-120)/2)
        ay = (((mesg[1][cwiid.Y])-120)/2)
        az = (((mesg[1][cwiid.Z])-120)/2)
        print "ax " + ax + "ay " + ay + "az " + az
  time.sleep(0.1)

def main():
  wiimote = makeConnection()
  while True:
    wiimote.led = (wiimote.state['led'] + 1) % 16
    accelerationDir(wiimote)

if __name__ == "__main__":
  main()
<commit_msg>test variables<commit_after>#! /usr/bin/python

import cwiid
import time

def makeConnection():
  print "Press 1 + 2 on the wiimote yo"
  wm = cwiid.Wiimote()
  wm.led = 1
  wm.enable(cwiid.FLAG_MOTIONPLUS)
  wm.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC
  print "you be connected"
  return wm

def accelerationDir(wiimote):
  print((wm.state['acc'][1]-125))
  time.sleep(0.1)

def main():
  wiimote = makeConnection()
  while True:
    wiimote.led = (wiimote.state['led'] + 1) % 16
    accelerationDir(wiimote)

if __name__ == "__main__":
  main()
<|endoftext|>


<commit_before>import codecs
import logging
from glob import iglob
from os.path import join, dirname

from gevent import monkey
from gevent.event import AsyncResult
from gevent.pool import Pool
monkey.patch_socket()
monkey.patch_ssl()

import requests
from lxml import html
from mutagen import easyid3, flac, easymp4, oggvorbis, musepack
from wikiapi import WikiApi

logger = logging.getLogger(__name__)

NOT_FOUND = object()
URI_SCHEME = 'http'
ARTICLE_URI = 'wikipedia.org/wiki/'
GENRE_CACHE = {}  # {(album, artist): AsyncResult([genre1, genre2, ...])}

class SetFile(set):
    def __init__(self, filename):
        try:
            with codecs.open(filename, 'r', encoding='utf-8') as fp:
                lines = fp.read().splitlines()
        except IOError:
            lines = []
        super(SetFile, self).__init__(lines)
        self.fp = codecs.open(filename, 'a', encoding='utf-8')

    def add(self, value):
        super(SetFile, self).add(value)
        self.fp.write(value)
        self.fp.write(u'\n')
        self.fp.flush()

    def close(self):
        self.fp.close()

    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        return self.fp.__exit__(*exc_info)

def titlecase(string):
    return u' '.join(part.capitalize() for part in string.split())

def get_genres(query):
    wiki = WikiApi()
    results = wiki.find(query.encode('utf-8'))
    if results:
        try:
            url = '{0}://{1}.{2}{3}'.format(
                URI_SCHEME, wiki.options['locale'], ARTICLE_URI,
                results[0].encode('utf-8'))
            resp = requests.get(url)
            dom = html.fromstring(resp.content)
            return (dom.xpath('.'
                              '//table[contains(@class, "haudio")]'
                              '//td[@class="category"]'
                              '/a'
                              '/text()') or
                    dom.xpath('.'
                              '//table[contains(@class, "infobox")]'
                              '//th'
                              '/a[text()="Genre"]'
                              '/..'
                              '/..'
                              '/td'
                              '/a'
                              '/text()'))
        except Exception as e:
            logger.error('Error getting genres for %s: %s', query, repr(e))
    return []

def search_variants(artist, album):
    if artist and album:
        yield get_genres(u'%s (%s album)' % (album, artist))
    if album:
        yield get_genres(u'%s (album)' % album)
        yield get_genres(album)
    if artist:
        yield get_genres(artist)

def albumgenres(artist='', album=''):
    result = GENRE_CACHE.get((artist, album))
    if result is None:
        result = AsyncResult()
        GENRE_CACHE[(artist, album)] = result
        result.set(reduce(lambda a, b: a or b, search_variants(artist, album)))
    return result.get()

def load_track(track):
    track_lower = track.lower()
    if track_lower.endswith('.mp3'):
        return easyid3.EasyID3(track)
    elif track_lower.endswith('.flac'):
        return flac.FLAC(track)
    elif track_lower.endswith('.mp4') or track_lower.endswith('.m4a'):
        return easymp4.EasyMP4(track)
    elif track_lower.endswith('.ogg'):
        return oggvorbis.OggVorbis(track)
    elif track_lower.endswith('.mpc'):
        return musepack.Musepack(track)
    else:
        raise ValueError("unhandled format '%s'" % track)

def wikigenre(track, force=False):
    try:
        audio = load_track(track)
        audio_genre = audio.get('genre')
        if audio_genre is not None and not force:
            logger.info('Skipping %s', track)
        else:
            artist = audio.get('artist', [None])[0]
            album = audio.get('album', [None])[0]
            genres = map(titlecase, albumgenres(artist, album))
            if genres:
                audio['genre'] = genres
                audio.save()
                logger.info('Tagged %s', track)
            else:
                logger.warn('No genres found for %s', track)
    except Exception as e:
        logger.error('Error tagging %s: %s', track, repr(e))
        raise

def main(string='', path=None, force=False):
    with open(join(dirname(__file__), 'wikigenre.log'), 'a') as log:
        handler = logging.StreamHandler()
        filehandler = logging.StreamHandler(log)

        formatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s')

        handler.setFormatter(formatter)
        filehandler.setFormatter(formatter)

        logger.addHandler(handler)
        logger.addHandler(filehandler)

        logger.setLevel('DEBUG')

        if string:
            for artistalbum in string.split('; '):
                parts = artistalbum.split(' - ', 1)
                try:
                    artist, album = parts
                except ValueError:
                    artist, album = '', artistalbum
                print (artistalbum + ': ' +
                       '; '.join(map(titlecase, albumgenres(artist, album))))
        else:
            logger.info('Starting')
            pool = Pool(8)
            for track in iglob(path):
                pool.spawn(wikigenre, track, force=force)
            pool.join()
            logger.info('Finished')

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('path', metavar='PATH', nargs='?')
    parser.add_argument('--string', metavar='STRING', nargs='?', default='',
                        help='[artist - ]album(; [artist - ]album)*')
    parser.add_argument('-f', '--force', action='store_true')
    namespace = parser.parse_args()
    kwargs = dict(namespace._get_kwargs())

    main(**kwargs)
<commit_msg>Normalize path<commit_after>import codecs
import logging
from glob import iglob
from os.path import join, dirname, normpath

from gevent import monkey
from gevent.event import AsyncResult
from gevent.pool import Pool
monkey.patch_socket()
monkey.patch_ssl()

import requests
from lxml import html
from mutagen import easyid3, flac, easymp4, oggvorbis, musepack
from wikiapi import WikiApi

logger = logging.getLogger(__name__)

URI_SCHEME = 'http'
ARTICLE_URI = 'wikipedia.org/wiki/'
GENRE_CACHE = {}  # {(album, artist): AsyncResult([genre1, genre2, ...])}

class SetFile(set):
    def __init__(self, filename):
        try:
            with codecs.open(filename, 'r', encoding='utf-8') as fp:
                lines = fp.read().splitlines()
        except IOError:
            lines = []
        super(SetFile, self).__init__(lines)
        self.fp = codecs.open(filename, 'a', encoding='utf-8')

    def add(self, value):
        super(SetFile, self).add(value)
        self.fp.write(value)
        self.fp.write(u'\n')
        self.fp.flush()

    def close(self):
        self.fp.close()

    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        return self.fp.__exit__(*exc_info)

def titlecase(string):
    return u' '.join(part.capitalize() for part in string.split())

def get_genres(query):
    wiki = WikiApi()
    results = wiki.find(query.encode('utf-8'))
    if results:
        try:
            url = '{0}://{1}.{2}{3}'.format(
                URI_SCHEME, wiki.options['locale'], ARTICLE_URI,
                results[0].encode('utf-8'))
            resp = requests.get(url)
            dom = html.fromstring(resp.content)
            return (dom.xpath('.'
                              '//table[contains(@class, "haudio")]'
                              '//td[@class="category"]'
                              '/a'
                              '/text()') or
                    dom.xpath('.'
                              '//table[contains(@class, "infobox")]'
                              '//th'
                              '/a[text()="Genre"]'
                              '/..'
                              '/..'
                              '/td'
                              '/a'
                              '/text()'))
        except Exception as e:
            logger.error('Error getting genres for %s: %s', query, repr(e))
    return []

def search_variants(artist, album):
    if artist and album:
        yield get_genres(u'%s (%s album)' % (album, artist))
    if album:
        yield get_genres(u'%s (album)' % album)
        yield get_genres(album)
    if artist:
        yield get_genres(artist)

def albumgenres(artist='', album=''):
    result = GENRE_CACHE.get((artist, album))
    if result is None:
        result = AsyncResult()
        GENRE_CACHE[(artist, album)] = result
        result.set(reduce(lambda a, b: a or b, search_variants(artist, album)))
    return result.get()

def load_track(track):
    track_lower = track.lower()
    if track_lower.endswith('.mp3'):
        return easyid3.EasyID3(track)
    elif track_lower.endswith('.flac'):
        return flac.FLAC(track)
    elif track_lower.endswith('.mp4') or track_lower.endswith('.m4a'):
        return easymp4.EasyMP4(track)
    elif track_lower.endswith('.ogg'):
        return oggvorbis.OggVorbis(track)
    elif track_lower.endswith('.mpc'):
        return musepack.Musepack(track)
    else:
        raise ValueError("unhandled format '%s'" % track)

def wikigenre(track, force=False):
    track = normpath(track)
    try:
        audio = load_track(track)
        audio_genre = audio.get('genre')
        if audio_genre is not None and not force:
            logger.info('Skipping %s', track)
        else:
            artist = audio.get('artist', [None])[0]
            album = audio.get('album', [None])[0]
            genres = map(titlecase, albumgenres(artist, album))
            if genres:
                audio['genre'] = genres
                audio.save()
                logger.info('Tagged %s', track)
            else:
                logger.warn('No genres found for %s', track)
    except Exception as e:
        logger.error('Error tagging %s: %s', track, repr(e))
        raise

def main(string='', path=None, force=False):
    with open(join(dirname(__file__), 'wikigenre.log'), 'a') as log:
        handler = logging.StreamHandler()
        filehandler = logging.StreamHandler(log)

        formatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s')

        handler.setFormatter(formatter)
        filehandler.setFormatter(formatter)

        logger.addHandler(handler)
        logger.addHandler(filehandler)

        logger.setLevel('DEBUG')

        if string:
            for artistalbum in string.split('; '):
                parts = artistalbum.split(' - ', 1)
                try:
                    artist, album = parts
                except ValueError:
                    artist, album = '', artistalbum
                print (artistalbum + ': ' +
                       '; '.join(map(titlecase, albumgenres(artist, album))))
        else:
            logger.info('Starting')
            pool = Pool(8)
            for track in iglob(path):
                pool.spawn(wikigenre, track, force=force)
            pool.join()
            logger.info('Finished')

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('path', metavar='PATH', nargs='?')
    parser.add_argument('--string', metavar='STRING', nargs='?', default='',
                        help='[artist - ]album(; [artist - ]album)*')
    parser.add_argument('-f', '--force', action='store_true')
    namespace = parser.parse_args()
    kwargs = dict(namespace._get_kwargs())

    main(**kwargs)
<|endoftext|>


<commit_before>def link(input_file, output_file):
    pass
    # check args?
    # build symbol/relocation tables
    # Find .text section of input
    # write all instructions to output, making sure to lookup in relocation table as needed
<commit_msg>Implemented linker<commit_after>import sys
from exceptions import *
from utils import SymbolTable, write_inst_hex

def inst_needs_relocation(instruction):
    return (instruction >> 26) == 2 or (instruction >> 26) == 3

def relocate_inst(instruction, offset, symtbl, reltbl):
    jump_addr = symtbl.get_addr(reltbl.get_label(offset))
    return (instruction & 0xfc000000) | (jump_addr >> 2)

def parse_table_entry(line):
    tokens = line.split("\t")
    return tokens[0], tokens[1]

def build_tables(obj_code, symtbl, reltbl):
    mode = None
    tables = [symtbl, reltbl]
    for line in obj_code:
        if line == ".symbol":
            # mode = "symbol"
            mode = 0
        elif line == ".relocation":
            # mode = "relocation"
            mode = 1
        elif line != "" and mode != None:
            # add this entry to the correct table
            addr, label = parse_table_entry(line)
            tables[mode].add(label, int(addr))

def find_text_block(obj_code):
    start = 0
    end = 0
    found_text = False
    index = 0
    for line in obj_code:
        if line == ".text":
            found_text = True
            start = index + 1
        elif found_text and line == "":
            end = index
            found_text = False
        index += 1
    return start, end

def link(input_file, out_file):
    # check args?
    obj_code = []
    with open(input_file, 'r') as f:
        for line in f:
            if len(line) > 0:
                obj_code += [line.strip()]
    # build symbol/relocation tables
    symtbl = SymbolTable(False)
    reltbl = SymbolTable(True)
    build_tables(obj_code, symtbl, reltbl)
    # Find .text section of input
    byte_off = 0
    output = []
    errors = []
    line_num = 0
    start, end = find_text_block(obj_code)
    for line in obj_code[start:end]:
        try:
            line_num += 1
            # write instruction out
            instruction = int(line, 16)
            if inst_needs_relocation(instruction):
                instruction = relocate_inst(instruction, byte_off, symtbl, reltbl)
            write_inst_hex(output, instruction)
        except AssemblerException as e:
            errors += [(line_num, e)]
        byte_off += 4

    if len(errors) > 0:
        print("Errors during linking:")
        for line_num, e in errors:
            print("Error: line {0}: {1}".format(line_num, e))

    with open(out_file, 'w') as f:
        for line in output:
            f.write(line + '\n')

def main():
    args = sys.argv[1:]
    link(args[0], args[1])

if __name__ == "__main__": main()
<|endoftext|>


<commit_before>from bot.action.core.action import ActionGroup
from bot.action.core.command import CommandAction
from bot.action.core.filter import MessageAction, TextMessageAction, NoPendingAction, EditedMessageAction, \
    PendingAction, NoForwardedMessage, VoiceMessageAction
from bot.action.extra.audios import SaveVoiceAction, ListVoiceAction
from bot.action.extra.hashtags import SaveHashtagsAction, ListHashtagsAction
from bot.action.extra.legacypole import LegacyPoleAction
from bot.action.extra.message import ShowMessageAction
from bot.action.extra.messages import SaveMessageAction, ListMessageAction
from bot.action.extra.pole import SavePoleAction, ListPoleAction, ManagePoleTimezonesAction
from bot.action.extra.random import RandomChoiceAction
from bot.action.standard.admin import RestartAction, EvalAction, AdminActionWithErrorMessage, AdminAction, HaltAction, \
    GroupAdminAction
from bot.action.standard.answer import AnswerAction
from bot.action.standard.chatsettings.action import ChatSettingsAction
from bot.action.standard.config import ConfigAction
from bot.action.standard.enterexit import GreetAction, LeaveAction
from bot.action.standard.gapdetector import GlobalGapDetectorAction
from bot.action.standard.internationalization import InternationalizationAction
from bot.action.standard.logger import LoggerAction
from bot.action.standard.perchat import PerChatAction
from bot.action.standard.silence import SilenceAction
from bot.action.standard.toggle import GetSetFeatureAction, ToggleableFeatureAction
from bot.action.standard.userinfo import SaveUserAction
from bot.bot import Bot

class BotManager:
    def __init__(self):
        self.bot = Bot()

    def setup_actions(self):
        self.bot.set_action(
            ActionGroup(
                LoggerAction().then(
                    GlobalGapDetectorAction().then(

                        # # ALWAYS (or SAVE) ACTIONS # #

                        MessageAction().then(
                            SaveUserAction(),

                            PerChatAction().then(
                                NoForwardedMessage().then(
                                    VoiceMessageAction().then(
                                        SaveVoiceAction()
                                    )
                                ),

                                SaveMessageAction(),
                                SavePoleAction(),

                                ToggleableFeatureAction("pole").then(
                                    LegacyPoleAction()
                                ),

                                TextMessageAction().then(
                                    SaveHashtagsAction()
                                )
                            )
                        ),

                        EditedMessageAction().then(
                            PerChatAction().then(
                                SaveMessageAction()
                            )
                        ),

                        # # INTERACTIVE ACTIONS # #

                        NoPendingAction().then(
                            MessageAction().then(
                                PerChatAction().then(
                                    InternationalizationAction().then(

                                        ToggleableFeatureAction("greet").then(
                                            GreetAction()
                                        ),
                                        ToggleableFeatureAction("leave").then(
                                            LeaveAction()
                                        ),

                                        TextMessageAction().then(

                                            CommandAction("start").then(
                                                AnswerAction(
                                                    "Hello! I am " + self.bot.cache.bot_info.first_name + " and I am here to serve you.\nSorry if I cannot do too much for you now, I am still under construction.")
                                            ),

                                            CommandAction("ping").then(
                                                AnswerAction("Up and running, sir!")
                                            ),

                                            CommandAction("restart").then(
                                                AdminActionWithErrorMessage().then(
                                                    RestartAction()
                                                )
                                            ),
                                            CommandAction("halt").then(
                                                AdminActionWithErrorMessage().then(
                                                    HaltAction()
                                                )
                                            ),
                                            CommandAction("eval").then(
                                                AdminActionWithErrorMessage().then(
                                                    EvalAction()
                                                )
                                            ),
                                            CommandAction("config").then(
                                                AdminActionWithErrorMessage().then(
                                                    ConfigAction()
                                                )
                                            ),

                                            CommandAction("settings").then(
                                                GroupAdminAction().then(
                                                    ChatSettingsAction()
                                                )
                                            ),

                                            CommandAction("silence").then(
                                                GroupAdminAction().then(
                                                    SilenceAction()
                                                )
                                            ),

                                            CommandAction("hashtags").then(
                                                ListHashtagsAction()
                                            ),

                                            CommandAction("feature").then(
                                                GetSetFeatureAction()
                                            ),

                                            CommandAction("polestzman").then(
                                                GroupAdminAction().then(
                                                    ManagePoleTimezonesAction()
                                                )
                                            ),

                                            CommandAction("poles").then(
                                                ListPoleAction("poles")
                                            ),

                                            CommandAction("subpoles").then(
                                                ListPoleAction("subpoles")
                                            ),

                                            CommandAction("subsubpoles").then(
                                                ListPoleAction("subsubpoles")
                                            ),

                                            CommandAction("messages").then(
                                                ListMessageAction()
                                            ),

                                            CommandAction("message").then(
                                                ShowMessageAction()
                                            ),

                                            CommandAction("audios").then(
                                                ListVoiceAction()
                                            ),

                                            CommandAction("random").then(
                                                RandomChoiceAction()
                                            )

                                        )

                                    )
                                )
                            )
                        ),

                        # # PENDING ACTIONS # #

                        PendingAction().then(
                            MessageAction().then(
                                PerChatAction().then(
                                    TextMessageAction().then(

                                        CommandAction("ping").then(
                                            AnswerAction("I'm back! Sorry for the delay...")
                                        ),

                                        AdminAction().then(
                                            CommandAction("restart").then(
                                                RestartAction()
                                            ),
                                            CommandAction("halt").then(
                                                HaltAction()
                                            )
                                        )

                                    )
                                )
                            )
                        )

                    )
                )
            )
        )

    def run(self):
        self.bot.run()
<commit_msg>Remove the 'on construction' message from /start response<commit_after>from bot.action.core.action import ActionGroup
from bot.action.core.command import CommandAction
from bot.action.core.filter import MessageAction, TextMessageAction, NoPendingAction, EditedMessageAction, \
    PendingAction, NoForwardedMessage, VoiceMessageAction
from bot.action.extra.audios import SaveVoiceAction, ListVoiceAction
from bot.action.extra.hashtags import SaveHashtagsAction, ListHashtagsAction
from bot.action.extra.legacypole import LegacyPoleAction
from bot.action.extra.message import ShowMessageAction
from bot.action.extra.messages import SaveMessageAction, ListMessageAction
from bot.action.extra.pole import SavePoleAction, ListPoleAction, ManagePoleTimezonesAction
from bot.action.extra.random import RandomChoiceAction
from bot.action.standard.admin import RestartAction, EvalAction, AdminActionWithErrorMessage, AdminAction, HaltAction, \
    GroupAdminAction
from bot.action.standard.answer import AnswerAction
from bot.action.standard.chatsettings.action import ChatSettingsAction
from bot.action.standard.config import ConfigAction
from bot.action.standard.enterexit import GreetAction, LeaveAction
from bot.action.standard.gapdetector import GlobalGapDetectorAction
from bot.action.standard.internationalization import InternationalizationAction
from bot.action.standard.logger import LoggerAction
from bot.action.standard.perchat import PerChatAction
from bot.action.standard.silence import SilenceAction
from bot.action.standard.toggle import GetSetFeatureAction, ToggleableFeatureAction
from bot.action.standard.userinfo import SaveUserAction
from bot.bot import Bot

class BotManager:
    def __init__(self):
        self.bot = Bot()

    def setup_actions(self):
        self.bot.set_action(
            ActionGroup(
                LoggerAction().then(
                    GlobalGapDetectorAction().then(

                        # # ALWAYS (or SAVE) ACTIONS # #

                        MessageAction().then(
                            SaveUserAction(),

                            PerChatAction().then(
                                NoForwardedMessage().then(
                                    VoiceMessageAction().then(
                                        SaveVoiceAction()
                                    )
                                ),

                                SaveMessageAction(),
                                SavePoleAction(),

                                ToggleableFeatureAction("pole").then(
                                    LegacyPoleAction()
                                ),

                                TextMessageAction().then(
                                    SaveHashtagsAction()
                                )
                            )
                        ),

                        EditedMessageAction().then(
                            PerChatAction().then(
                                SaveMessageAction()
                            )
                        ),

                        # # INTERACTIVE ACTIONS # #

                        NoPendingAction().then(
                            MessageAction().then(
                                PerChatAction().then(
                                    InternationalizationAction().then(

                                        ToggleableFeatureAction("greet").then(
                                            GreetAction()
                                        ),
                                        ToggleableFeatureAction("leave").then(
                                            LeaveAction()
                                        ),

                                        TextMessageAction().then(

                                            CommandAction("start").then(
                                                AnswerAction(
                                                    "Hello! I am " + self.bot.cache.bot_info.first_name + " and I am here to serve you.")
                                            ),

                                            CommandAction("ping").then(
                                                AnswerAction("Up and running, sir!")
                                            ),

                                            CommandAction("restart").then(
                                                AdminActionWithErrorMessage().then(
                                                    RestartAction()
                                                )
                                            ),
                                            CommandAction("halt").then(
                                                AdminActionWithErrorMessage().then(
                                                    HaltAction()
                                                )
                                            ),
                                            CommandAction("eval").then(
                                                AdminActionWithErrorMessage().then(
                                                    EvalAction()
                                                )
                                            ),
                                            CommandAction("config").then(
                                                AdminActionWithErrorMessage().then(
                                                    ConfigAction()
                                                )
                                            ),

                                            CommandAction("settings").then(
                                                GroupAdminAction().then(
                                                    ChatSettingsAction()
                                                )
                                            ),

                                            CommandAction("silence").then(
                                                GroupAdminAction().then(
                                                    SilenceAction()
                                                )
                                            ),

                                            CommandAction("hashtags").then(
                                                ListHashtagsAction()
                                            ),

                                            CommandAction("feature").then(
                                                GetSetFeatureAction()
                                            ),

                                            CommandAction("polestzman").then(
                                                GroupAdminAction().then(
                                                    ManagePoleTimezonesAction()
                                                )
                                            ),

                                            CommandAction("poles").then(
                                                ListPoleAction("poles")
                                            ),

                                            CommandAction("subpoles").then(
                                                ListPoleAction("subpoles")
                                            ),

                                            CommandAction("subsubpoles").then(
                                                ListPoleAction("subsubpoles")
                                            ),

                                            CommandAction("messages").then(
                                                ListMessageAction()
                                            ),

                                            CommandAction("message").then(
                                                ShowMessageAction()
                                            ),

                                            CommandAction("audios").then(
                                                ListVoiceAction()
                                            ),

                                            CommandAction("random").then(
                                                RandomChoiceAction()
                                            )

                                        )

                                    )
                                )
                            )
                        ),

                        # # PENDING ACTIONS # #

                        PendingAction().then(
                            MessageAction().then(
                                PerChatAction().then(
                                    TextMessageAction().then(

                                        CommandAction("ping").then(
                                            AnswerAction("I'm back! Sorry for the delay...")
                                        ),

                                        AdminAction().then(
                                            CommandAction("restart").then(
                                                RestartAction()
                                            ),
                                            CommandAction("halt").then(
                                                HaltAction()
                                            )
                                        )

                                    )
                                )
                            )
                        )

                    )
                )
            )
        )

    def run(self):
        self.bot.run()
<|endoftext|>


<commit_before>import pieces, board, random

gray = (100, 100, 100)

class PieceBag:
    def __init__(self):
        self.bag=[]
        self.refill_bag()

    def refill_bag(self):
        for x in range(7):
            self.bag.append(random.randint(0, 6))

        self.remaining = 7
        pass

    def get_next_piece(self):
        self.remaining -= 1;
        nextPiece=self.bag.pop(0)
        return nextPiece

    def remaining_pieces(self):
        return self.remaining

class BoardModel:

    class CollisionTypeEnum:
        wall = 0
        pieceSide = 0
        floor = 1
        pieceBelow = 2

    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.pieceBag = PieceBag()

        self.boardSquares = []

        for i in range(height):
            self.boardSquares.append([])
            for j in range(width):
                self.boardSquares[i].append(board.Square(i, j, gray))

        print self.boardSquares

        self.activePiece = False
        self.currentPiece = None
        self.pieceRow = 0
        self.pieceCol = 0

    def get_square(self, x, y):
        return self.boardSquares[y][x]

    def new_piece(self):
        if not self.pieceBag.remaining:
            self.pieceBag.refill_bag()
        self.currentPiece = pieces.get_piece(self.pieceBag.get_next_piece())
        self.activePiece = True
        self.pieceCol = 3
        self.pieceRow = 0

    def rotate_piece(self):
        if self._will_collide(0,0):
            self.clear_piece() #Try a different way to do this
            self.currentPiece.blockArray = self.currentPiece.rotate()
            self.draw_piece()
        else:
            pass

    def _will_collide(self, dx, dy):
        for i in range(self.currentPiece.height):
            for j in range(self.currentPiece.width):
                if self.currentPiece.blockArray[i][j]:
                    if i + dy < self.currentPiece.height and i + dy > -1 and j + dx < self.currentPiece.width and j + dx >= -1 and not self.currentPiece.blockArray[i + dy][j + dx]:
                        print "i: " + str(i) + " j: " + str(j) + " dx: " + str(dx) + " dy: " + str(dy)
                        if j + self.pieceCol + dx < 0 or j + self.pieceCol + dx > self.width - 1:  #should be 'or', not 'and'?
                            return True, self.CollisionTypeEnum.wall
                        elif i + self.pieceRow + dy > self.height - 1:
                            return True, self.CollisionTypeEnum.floor
                        elif self.boardSquares[i + self.pieceRow + dy][j + self.pieceCol + dx].color != gray and dy == 1:
                            return True, self.CollisionTypeEnum.pieceBelow
                        elif self.boardSquares[i + self.pieceRow][j + self.pieceCol + dx].color != gray and abs(dx) == 1:
                            return True, self.CollisionTypeEnum.pieceSide
                    #These additional elif statements are used for the case in which there is a colored square on the edge
                    #piece's 3x3 or 4x4
                    elif i + dy == self.currentPiece.height and i + dy > -1:
                        if i + self.pieceRow + dy > self.height - 1:
                            return True, self.CollisionTypeEnum.floor
                        elif self.boardSquares[i + self.pieceRow + dy][j + self.pieceCol + dx].color != gray:
                            return True, self.CollisionTypeEnum.pieceBelow
                    # This elif statement checks for collisions on the leftmost and rightmost columns of blocks in a piece
                    elif j + dx == self.currentPiece.width or j + dx == -1:
                        if j + self.pieceCol + dx < 0 or j + self.pieceCol + dx > self.width - 1:  #should be 'or', not 'and'?
                            return True, self.CollisionTypeEnum.wall
                        elif self.boardSquares[i + self.pieceRow + dy][j + self.pieceCol + dx].color != gray:
                            return True, self.CollisionTypeEnum.pieceSide

        return False, None

    def act_on_piece(self, dx, dy):
        if self.activePiece:
            willCollide, collisionType = self._will_collide(dx, dy)
            if willCollide:
                if collisionType != self.CollisionTypeEnum.wall:
                    self.activePiece = False
                    lines=self.check_lines()
                    self.drop_lines(lines)
            else:
                self.clear_piece()
                self.pieceRow += dy
                self.pieceCol += dx
                self.draw_piece()

    def draw_piece(self):
        for i in range(self.currentPiece.height):
            for j in range(self.currentPiece.width):
                if self.currentPiece.blockArray[i][j]:
                    try:
                        self.boardSquares[i + self.pieceRow][j + self.pieceCol].set_color(self.currentPiece.color)
                    except IndexError:
                        print "X: " + str(j + self.pieceCol) + " Y: " + str(i + self.pieceRow)

    def clear_piece(self):
        for i in range(self.currentPiece.height):
            for j in range(self.currentPiece.width):
                if self.currentPiece.blockArray[i][j]:
                    self.boardSquares[i + self.pieceRow][j + self.pieceCol].set_color(gray)

    def check_lines(self):
        lines = []
        for i in range(self.height-1,0,-1):
            line = [i]
            colors = []
            for j in range(self.width):
                line.append(self.boardSquares[i][j])
                colors.append(self.boardSquares[i][j].color)
            if gray not in colors:
                lines.append(line)
            else:
                pass

        return lines

    def clear_line(self,line):
        for square in line[1:]:
            square.set_color(gray)

    def drop_lines(self,lines):
        for line in lines:
            self.clear_line(line)
            Row = line.pop(0) - 1
            if Row >= self.height - 1:
                pass
            else:
                for i in range(Row,0,-1):
                    for j in range(self.width):
                        self.boardSquares[i+1][j].set_color(self.boardSquares[i][j].color)
                        self.boardSquares[i][j].set_color(gray)

<commit_msg>Rotation bug fixed: Pieces do not rotate if rotation will cause an overlap with an existing colored square<commit_after>import pieces, board, random, copy

gray = (100, 100, 100)

class PieceBag:
    def __init__(self):
        self.bag=[]
        self.refill_bag()

    def refill_bag(self):
        for x in range(7):
            self.bag.append(random.randint(0, 6))

        self.remaining = 7
        pass

    def get_next_piece(self):
        self.remaining -= 1;
        nextPiece=self.bag.pop(0)
        return nextPiece

    def remaining_pieces(self):
        return self.remaining

class BoardModel:

    class CollisionTypeEnum:
        wall = 0
        pieceSide = 0
        floor = 1
        pieceBelow = 2

    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.pieceBag = PieceBag()

        self.boardSquares = []

        for i in range(height):
            self.boardSquares.append([])
            for j in range(width):
                self.boardSquares[i].append(board.Square(i, j, gray))

        print self.boardSquares

        self.activePiece = False
        self.currentPiece = None
        self.pieceRow = 0
        self.pieceCol = 0

    def get_square(self, x, y):
        return self.boardSquares[y][x]

    def new_piece(self):
        if not self.pieceBag.remaining:
            self.pieceBag.refill_bag()
        self.currentPiece = pieces.get_piece(self.pieceBag.get_next_piece())
        self.activePiece = True
        self.pieceCol = 3
        self.pieceRow = 0

    def check_rotate(self):
        #makes a copy of self.currentPiece so that changing rotatedPiece doesn't mess up self.currentPiece
        rotatedPiece = copy.deepcopy(self.currentPiece)
        #rotates rotatedPiece so that we have a copy of what spaces self.currentPiece will rotate into
        rotatedPiece.blockArray = self.currentPiece.rotate()
        #returns True if a block from the rotate piece will rotate into an existing colored block below it
        for i in range(rotatedPiece.height):
            for j in range(rotatedPiece.width):
                if rotatedPiece.blockArray[i][j] and self.boardSquares[i + self.pieceRow][j + self.pieceCol].color != gray and not self.currentPiece.blockArray[i][j]:
                    return True
        #returns False if there are only gray squares below the rotating piece
        return False

    def rotate_piece(self):
        #checks if rotating the piece will cause it to overlap with an existing colored square
        #if rotation will cause an overlap, then the piece does not rotate
        if not self.check_rotate():
            self.clear_piece() #Try a different way to do this
            self.currentPiece.blockArray = self.currentPiece.rotate()
            self.draw_piece()

    def _will_collide(self, dx, dy):
        for i in range(self.currentPiece.height):
            for j in range(self.currentPiece.width):
                if self.currentPiece.blockArray[i][j]:
                    if i + dy < self.currentPiece.height and i + dy > -1 and j + dx < self.currentPiece.width and j + dx >= -1 and not self.currentPiece.blockArray[i + dy][j + dx]:
                        #print "i: " + str(i) + " j: " + str(j) + " dy: " + str(dy) + " dx: " + str(dx)
                        if j + self.pieceCol + dx < 0 or j + self.pieceCol + dx > self.width - 1:  #should be 'or', not 'and'?
                            return True, self.CollisionTypeEnum.wall
                        elif i + self.pieceRow + dy > self.height - 1:
                            return True, self.CollisionTypeEnum.floor
                        elif self.boardSquares[i + self.pieceRow + dy][j + self.pieceCol + dx].color != gray and dy == 1:
                            return True, self.CollisionTypeEnum.pieceBelow
                        elif self.boardSquares[i + self.pieceRow][j + self.pieceCol + dx].color != gray and abs(dx) == 1:
                            return True, self.CollisionTypeEnum.pieceSide
                    #These additional elif statements are used for the case in which there is a colored square on the edge
                    #piece's 3x3 or 4x4
                    elif i + dy == self.currentPiece.height and i + dy > -1:
                        if i + self.pieceRow + dy > self.height - 1:
                            return True, self.CollisionTypeEnum.floor
                        elif self.boardSquares[i + self.pieceRow + dy][j + self.pieceCol + dx].color != gray:
                            return True, self.CollisionTypeEnum.pieceBelow
                    # This elif statement checks for collisions on the leftmost and rightmost columns of blocks in a piece
                    elif j + dx == self.currentPiece.width or j + dx == -1:
                        if j + self.pieceCol + dx < 0 or j + self.pieceCol + dx > self.width - 1:  #should be 'or', not 'and'?
                            return True, self.CollisionTypeEnum.wall
                        elif self.boardSquares[i + self.pieceRow + dy][j + self.pieceCol + dx].color != gray:
                            return True, self.CollisionTypeEnum.pieceSide

        return False, None

    def act_on_piece(self, dx, dy):
        if self.activePiece:
            willCollide, collisionType = self._will_collide(dx, dy)
            if willCollide:
                if collisionType != self.CollisionTypeEnum.wall:
                    self.activePiece = False
                    lines=self.check_lines()
                    self.drop_lines(lines)
            else:
                self.clear_piece()
                self.pieceRow += dy
                self.pieceCol += dx
                self.draw_piece()

    def draw_piece(self):
        for i in range(self.currentPiece.height):
            for j in range(self.currentPiece.width):
                if self.currentPiece.blockArray[i][j]:
                    try:
                        self.boardSquares[i + self.pieceRow][j + self.pieceCol].set_color(self.currentPiece.color)
                    except IndexError:
                        print "X: " + str(j + self.pieceCol) + " Y: " + str(i + self.pieceRow)

    def clear_piece(self):
        for i in range(self.currentPiece.height):
            for j in range(self.currentPiece.width):
                if self.currentPiece.blockArray[i][j]:
                    self.boardSquares[i + self.pieceRow][j + self.pieceCol].set_color(gray)

    def check_lines(self):
        lines = []
        for i in range(self.height-1,0,-1):
            line = [i]
            colors = []
            for j in range(self.width):
                line.append(self.boardSquares[i][j])
                colors.append(self.boardSquares[i][j].color)
            if gray not in colors:
                lines.append(line)
            else:
                pass

        return lines

    def clear_line(self,line):
        for square in line[1:]:
            square.set_color(gray)

    def drop_lines(self,lines):
        for line in lines:
            self.clear_line(line)
            Row = line.pop(0) - 1
            if Row >= self.height - 1:
                pass
            else:
                for i in range(Row,0,-1):
                    for j in range(self.width):
                        self.boardSquares[i+1][j].set_color(self.boardSquares[i][j].color)
                        self.boardSquares[i][j].set_color(gray)

<|endoftext|>


<commit_before>from bot import project_info
from bot.action.core.action import ActionGroup
from bot.action.core.command import CommandAction
from bot.action.core.filter import MessageAction, TextMessageAction, NoPendingAction, EditedMessageAction, \
    PendingAction, NoForwardedMessage, VoiceMessageAction
from bot.action.extra.audios import SaveVoiceAction, ListVoiceAction
from bot.action.extra.hashtags import SaveHashtagsAction, ListHashtagsAction
from bot.action.extra.legacypole import LegacyPoleAction
from bot.action.extra.message import ShowMessageAction
from bot.action.extra.messages import SaveMessageAction, ListMessageAction
from bot.action.extra.pole import SavePoleAction, ListPoleAction, ManagePoleTimezonesAction
from bot.action.extra.random import RandomChoiceAction
from bot.action.standard.about import AboutAction, VersionAction
from bot.action.standard.admin import RestartAction, EvalAction, AdminActionWithErrorMessage, AdminAction, HaltAction, \
    GroupAdminAction
from bot.action.standard.answer import AnswerAction
from bot.action.standard.asynchronous import AsynchronousAction
from bot.action.standard.benchmark import BenchmarkAction, WorkersAction
from bot.action.standard.chatsettings.action import ChatSettingsAction
from bot.action.standard.config import ConfigAction
from bot.action.standard.config_status import ConfigStatusAction
from bot.action.standard.enterexit import GreetAction, LeaveAction
from bot.action.standard.gapdetector import GlobalGapDetectorAction
from bot.action.standard.instance import InstanceAction
from bot.action.standard.internationalization import InternationalizationAction
from bot.action.standard.logger import LoggerAction
from bot.action.standard.perchat import PerChatAction
from bot.action.standard.silence import SilenceAction
from bot.action.standard.toggle import GetSetFeatureAction, ToggleableFeatureAction
from bot.action.standard.userinfo import SaveUserAction
from bot.bot import Bot

class BotManager:
    def __init__(self):
        self.bot = Bot()

    def setup_actions(self):
        self.bot.set_action(
            ActionGroup(
                LoggerAction().then(
                    GlobalGapDetectorAction().then(

                        # # ALWAYS (or SAVE) ACTIONS # #

                        MessageAction().then(
                            SaveUserAction(),

                            PerChatAction().then(
                                NoForwardedMessage().then(
                                    VoiceMessageAction().then(
                                        SaveVoiceAction()
                                    )
                                ),

                                SaveMessageAction(),
                                SavePoleAction(),

                                ToggleableFeatureAction("pole").then(
                                    LegacyPoleAction()
                                ),

                                TextMessageAction().then(
                                    SaveHashtagsAction()
                                )
                            )
                        ),

                        EditedMessageAction().then(
                            PerChatAction().then(
                                SaveMessageAction()
                            )
                        ),

                        # # INTERACTIVE ACTIONS # #

                        NoPendingAction().then(
                            MessageAction().then(
                                PerChatAction().then(
                                    InternationalizationAction().then(

                                        ToggleableFeatureAction("greet").then(
                                            GreetAction()
                                        ),
                                        ToggleableFeatureAction("leave").then(
                                            LeaveAction()
                                        ),

                                        TextMessageAction().then(

                                            CommandAction("start").then(
                                                AnswerAction(
                                                    "Hello! I am " + self.bot.cache.bot_info.first_name + " and I am here to serve you.")
                                            ),

                                            CommandAction("about").then(
                                                AboutAction(
                                                    project_info.name,
                                                    author_handle=project_info.author_handle,
                                                    is_open_source=True,
                                                    source_url=project_info.source_url,
                                                    license_name=project_info.license_name)
                                            ),

                                            CommandAction("version").then(
                                                VersionAction(
                                                    project_info.name,
                                                    project_info.source_url + "/releases"
                                                )
                                            ),

                                            CommandAction("benchmark").then(
                                                AsynchronousAction("benchmark").then(
                                                    BenchmarkAction()
                                                )
                                            ),

                                            CommandAction("ping").then(
                                                AnswerAction("Up and running, sir!")
                                            ),

                                            # ADMIN ACTIONS #

                                            CommandAction("restart").then(
                                                AdminActionWithErrorMessage().then(
                                                    RestartAction()
                                                )
                                            ),
                                            CommandAction("halt").then(
                                                AdminActionWithErrorMessage().then(
                                                    HaltAction()
                                                )
                                            ),
                                            CommandAction("eval").then(
                                                AdminActionWithErrorMessage().then(
                                                    EvalAction()
                                                )
                                            ),
                                            CommandAction("config").then(
                                                AdminActionWithErrorMessage().then(
                                                    ConfigAction()
                                                )
                                            ),
                                            CommandAction("configstatus").then(
                                                AdminActionWithErrorMessage().then(
                                                    ConfigStatusAction()
                                                )
                                            ),
                                            CommandAction("instance").then(
                                                AdminActionWithErrorMessage().then(
                                                    InstanceAction()
                                                )
                                            ),
                                            CommandAction("workers").then(
                                                AdminActionWithErrorMessage().then(
                                                    WorkersAction()
                                                )
                                            ),

                                            # FEATURES #

                                            CommandAction("settings").then(
                                                GroupAdminAction().then(
                                                    ChatSettingsAction()
                                                )
                                            ),

                                            CommandAction("silence").then(
                                                GroupAdminAction().then(
                                                    SilenceAction()
                                                )
                                            ),

                                            CommandAction("hashtags").then(
                                                ListHashtagsAction()
                                            ),

                                            CommandAction("feature").then(
                                                GetSetFeatureAction()
                                            ),

                                            CommandAction("polestzman").then(
                                                GroupAdminAction().then(
                                                    ManagePoleTimezonesAction()
                                                )
                                            ),

                                            CommandAction("poles").then(
                                                ListPoleAction("poles")
                                            ),

                                            CommandAction("subpoles").then(
                                                ListPoleAction("subpoles")
                                            ),

                                            CommandAction("subsubpoles").then(
                                                ListPoleAction("subsubpoles")
                                            ),

                                            CommandAction("messages").then(
                                                ListMessageAction()
                                            ),

                                            CommandAction("message").then(
                                                ShowMessageAction()
                                            ),

                                            CommandAction("audios").then(
                                                ListVoiceAction()
                                            ),

                                            CommandAction("random").then(
                                                RandomChoiceAction()
                                            )

                                        )

                                    )
                                )
                            )
                        ),

                        # # PENDING ACTIONS # #

                        PendingAction().then(
                            MessageAction().then(
                                PerChatAction().then(
                                    TextMessageAction().then(

                                        CommandAction("ping").then(
                                            AnswerAction("I'm back! Sorry for the delay...")
                                        ),

                                        AdminAction().then(
                                            CommandAction("restart").then(
                                                RestartAction()
                                            ),
                                            CommandAction("halt").then(
                                                HaltAction()
                                            )
                                        )

                                    )
                                )
                            )
                        )

                    )
                )
            )
        )

    def run(self):
        self.bot.run()
<commit_msg>Remove spurious line break in manager<commit_after>from bot import project_info
from bot.action.core.action import ActionGroup
from bot.action.core.command import CommandAction
from bot.action.core.filter import MessageAction, TextMessageAction, NoPendingAction, EditedMessageAction, \
    PendingAction, NoForwardedMessage, VoiceMessageAction
from bot.action.extra.audios import SaveVoiceAction, ListVoiceAction
from bot.action.extra.hashtags import SaveHashtagsAction, ListHashtagsAction
from bot.action.extra.legacypole import LegacyPoleAction
from bot.action.extra.message import ShowMessageAction
from bot.action.extra.messages import SaveMessageAction, ListMessageAction
from bot.action.extra.pole import SavePoleAction, ListPoleAction, ManagePoleTimezonesAction
from bot.action.extra.random import RandomChoiceAction
from bot.action.standard.about import AboutAction, VersionAction
from bot.action.standard.admin import RestartAction, EvalAction, AdminActionWithErrorMessage, AdminAction, HaltAction, \
    GroupAdminAction
from bot.action.standard.answer import AnswerAction
from bot.action.standard.asynchronous import AsynchronousAction
from bot.action.standard.benchmark import BenchmarkAction, WorkersAction
from bot.action.standard.chatsettings.action import ChatSettingsAction
from bot.action.standard.config import ConfigAction
from bot.action.standard.config_status import ConfigStatusAction
from bot.action.standard.enterexit import GreetAction, LeaveAction
from bot.action.standard.gapdetector import GlobalGapDetectorAction
from bot.action.standard.instance import InstanceAction
from bot.action.standard.internationalization import InternationalizationAction
from bot.action.standard.logger import LoggerAction
from bot.action.standard.perchat import PerChatAction
from bot.action.standard.silence import SilenceAction
from bot.action.standard.toggle import GetSetFeatureAction, ToggleableFeatureAction
from bot.action.standard.userinfo import SaveUserAction
from bot.bot import Bot

class BotManager:
    def __init__(self):
        self.bot = Bot()

    def setup_actions(self):
        self.bot.set_action(
            ActionGroup(
                LoggerAction().then(
                    GlobalGapDetectorAction().then(

                        # # ALWAYS (or SAVE) ACTIONS # #

                        MessageAction().then(
                            SaveUserAction(),

                            PerChatAction().then(
                                NoForwardedMessage().then(
                                    VoiceMessageAction().then(
                                        SaveVoiceAction()
                                    )
                                ),

                                SaveMessageAction(),
                                SavePoleAction(),

                                ToggleableFeatureAction("pole").then(
                                    LegacyPoleAction()
                                ),

                                TextMessageAction().then(
                                    SaveHashtagsAction()
                                )
                            )
                        ),

                        EditedMessageAction().then(
                            PerChatAction().then(
                                SaveMessageAction()
                            )
                        ),

                        # # INTERACTIVE ACTIONS # #

                        NoPendingAction().then(
                            MessageAction().then(
                                PerChatAction().then(
                                    InternationalizationAction().then(

                                        ToggleableFeatureAction("greet").then(
                                            GreetAction()
                                        ),
                                        ToggleableFeatureAction("leave").then(
                                            LeaveAction()
                                        ),

                                        TextMessageAction().then(

                                            CommandAction("start").then(
                                                AnswerAction("Hello! I am " + self.bot.cache.bot_info.first_name + " and I am here to serve you.")
                                            ),

                                            CommandAction("about").then(
                                                AboutAction(
                                                    project_info.name,
                                                    author_handle=project_info.author_handle,
                                                    is_open_source=True,
                                                    source_url=project_info.source_url,
                                                    license_name=project_info.license_name)
                                            ),

                                            CommandAction("version").then(
                                                VersionAction(
                                                    project_info.name,
                                                    project_info.source_url + "/releases"
                                                )
                                            ),

                                            CommandAction("benchmark").then(
                                                AsynchronousAction("benchmark").then(
                                                    BenchmarkAction()
                                                )
                                            ),

                                            CommandAction("ping").then(
                                                AnswerAction("Up and running, sir!")
                                            ),

                                            # ADMIN ACTIONS #

                                            CommandAction("restart").then(
                                                AdminActionWithErrorMessage().then(
                                                    RestartAction()
                                                )
                                            ),
                                            CommandAction("halt").then(
                                                AdminActionWithErrorMessage().then(
                                                    HaltAction()
                                                )
                                            ),
                                            CommandAction("eval").then(
                                                AdminActionWithErrorMessage().then(
                                                    EvalAction()
                                                )
                                            ),
                                            CommandAction("config").then(
                                                AdminActionWithErrorMessage().then(
                                                    ConfigAction()
                                                )
                                            ),
                                            CommandAction("configstatus").then(
                                                AdminActionWithErrorMessage().then(
                                                    ConfigStatusAction()
                                                )
                                            ),
                                            CommandAction("instance").then(
                                                AdminActionWithErrorMessage().then(
                                                    InstanceAction()
                                                )
                                            ),
                                            CommandAction("workers").then(
                                                AdminActionWithErrorMessage().then(
                                                    WorkersAction()
                                                )
                                            ),

                                            # FEATURES #

                                            CommandAction("settings").then(
                                                GroupAdminAction().then(
                                                    ChatSettingsAction()
                                                )
                                            ),

                                            CommandAction("silence").then(
                                                GroupAdminAction().then(
                                                    SilenceAction()
                                                )
                                            ),

                                            CommandAction("hashtags").then(
                                                ListHashtagsAction()
                                            ),

                                            CommandAction("feature").then(
                                                GetSetFeatureAction()
                                            ),

                                            CommandAction("polestzman").then(
                                                GroupAdminAction().then(
                                                    ManagePoleTimezonesAction()
                                                )
                                            ),

                                            CommandAction("poles").then(
                                                ListPoleAction("poles")
                                            ),

                                            CommandAction("subpoles").then(
                                                ListPoleAction("subpoles")
                                            ),

                                            CommandAction("subsubpoles").then(
                                                ListPoleAction("subsubpoles")
                                            ),

                                            CommandAction("messages").then(
                                                ListMessageAction()
                                            ),

                                            CommandAction("message").then(
                                                ShowMessageAction()
                                            ),

                                            CommandAction("audios").then(
                                                ListVoiceAction()
                                            ),

                                            CommandAction("random").then(
                                                RandomChoiceAction()
                                            )

                                        )

                                    )
                                )
                            )
                        ),

                        # # PENDING ACTIONS # #

                        PendingAction().then(
                            MessageAction().then(
                                PerChatAction().then(
                                    TextMessageAction().then(

                                        CommandAction("ping").then(
                                            AnswerAction("I'm back! Sorry for the delay...")
                                        ),

                                        AdminAction().then(
                                            CommandAction("restart").then(
                                                RestartAction()
                                            ),
                                            CommandAction("halt").then(
                                                HaltAction()
                                            )
                                        )

                                    )
                                )
                            )
                        )

                    )
                )
            )
        )

    def run(self):
        self.bot.run()
<|endoftext|>


<commit_before>import glob
import html,html.parser,urllib.parse
import re

# reads *.htm from hosting and extracts links to files
class Linker:
	def __init__(self,dir,dirsAndSuffixes):
		self.fileLinks=fileLinks={}
		class Parser(html.parser.HTMLParser):
			def handle_starttag(self,tag,attrs):
				nonlocal fileLinks
				if tag!='a':
					return
				for a,v in attrs:
					if a!='href':
						continue
					u=urllib.parse.unquote(v)
					for d,ss in dirsAndSuffixes.items():
						s='|'.join(ss)
						m=re.search(r'(?:'+d+')/.+\.(?:'+s+')$',u)
						if m:
							v=v.replace('https://www.dropbox.com/','https://dl.dropboxusercontent.com/',1) # dropbox special
							fileLinks[m.group(0)]=v
		for filename in glob.glob(dir+'/*.htm'):
			with open(filename,encoding='utf-8') as f:
				Parser().feed(f.read())
	def getLink(self,path):
		if path not in self.fileLinks:
			raise Exception(path+' not hosted')
		return self.fileLinks[path]
	def findAndProcessLinks(self,x):
		x=re.sub(
			"<a href='(?P<path>[^']*)' class='file'",
			lambda m: "<a href='"+html.escape(self.getLink(m.group('path')))+"' class='file'",
			x
		)
		x=re.sub(
			r"<a href='index.html([#'])",
			r"<a href='.\1",
			x
		)
		return x
<commit_msg>dropbox ?dl=0 fix<commit_after>import glob
import html,html.parser,urllib.parse
import re

# reads *.htm from hosting and extracts links to files
class Linker:
	def __init__(self,dir,dirsAndSuffixes):
		self.fileLinks=fileLinks={}
		class Parser(html.parser.HTMLParser):
			def handle_starttag(self,tag,attrs):
				nonlocal fileLinks
				if tag!='a':
					return
				for a,v in attrs:
					v=re.sub(r'\?dl=0$','',v) # dropbox special
					if a!='href':
						continue
					u=urllib.parse.unquote(v)
					for d,ss in dirsAndSuffixes.items():
						s='|'.join(ss)
						m=re.search(r'(?:'+d+')/.+\.(?:'+s+')$',u)
						if m:
							v=v.replace('https://www.dropbox.com/','https://dl.dropboxusercontent.com/',1) # dropbox special
							fileLinks[m.group(0)]=v
		for filename in glob.glob(dir+'/*.htm'):
			with open(filename,encoding='utf-8') as f:
				Parser().feed(f.read())
	def getLink(self,path):
		if path not in self.fileLinks:
			raise Exception(path+' not hosted')
		return self.fileLinks[path]
	def findAndProcessLinks(self,x):
		x=re.sub(
			"<a href='(?P<path>[^']*)' class='file'",
			lambda m: "<a href='"+html.escape(self.getLink(m.group('path')))+"' class='file'",
			x
		)
		x=re.sub(
			r"<a href='index.html([#'])",
			r"<a href='.\1",
			x
		)
		return x
<|endoftext|>