Beispiel #1
0
def strProcessing(str, user):
    chatHistory = UserProcessing(user.uid).addMsg(str)
    commands(context=chatHistory[-1],
             command=chatHistory[-2],
             user=user,
             message=Message,
             api=api,
             token=token,
             lusers=user.linkedUser,
             luser=str)
Beispiel #2
0
async def on_message(message):
    print(f"{datetime.now()} {message.channel} {message.author} {message.content}")

    if message.author == client.user or message.author.bot:
        return
    
    if functions.Identifier.is_beatmap_url(message.content):
        beatmap_id = functions.Converter.url_to_beatmap(message.content).beatmapId

        user = {'language': "en", 'osu_id': 0, 'mode': 0}

        com = commands.commands(client, message, user)

        await com.beatmap([str(beatmap_id)])
        
    if message.content.startswith("!"):
        user = preferences.load_user(message.author.id)

        if user is None:
            user = {'language': "en", 'osu_id': 0, 'mode': 0}
            com = commands.commands(client, message, user)
            
        else:
            com = commands.commands(client, message, user)

        #입력을 쪼개서 배열로 만듬
        string = message.content.split()

        if len(string[0]) > 1:
            string[0] = string[0][1:]
        else:
            return

        command = translator.alias.command(string[0])

        if command == "help":
            await com.help(string)
            return

        elif command == "beatmap":
            await com.beatmap(string)
            return

        elif command == "set":
            await com.set(string)
            return

        elif command == "recent":
            await com.recent(string)
            return

        elif command == "top":
            await com.top(string)
            return
Beispiel #3
0
    def reload_commands(self):
        # Reloading
        self.config = loadconf('config.json')
        reload(commands)
        reload(custom_commands)
        self.lastloadconf = os.stat('config.json').st_mtime
        self.lastloadcommands = os.stat('commands.py').st_mtime
        self.lastloadcustomcommands = os.stat('custom_commands.py').st_mtime

        # Create objects for commands and custom_commands
        cmd = commands.commands(self.send_message, self.send_action,
                                self.banned_words, self.config)
        cust_cmd = custom_commands.custom_commands(
            self.send_message, self.send_action, self.config)

        # Method to get all callable objects with a given prefix from a given object
        def get_methods(obj, prefix):
            return {
                x: getattr(obj, x)
                for x in dir(obj)
                if x.startswith(prefix) and callable(getattr(obj, x))
            }

        # Get all regexes from all files, overwriting ones in commands and self with those in custom_commands
        self.regexes = get_methods(cmd, 'regex_')
        self.regexes.update(get_methods(self, 'regex_'))
        self.regexes.update(get_methods(cust_cmd, 'regex_'))

        # Get all commands from all files, overwriting ones in commands and self with those in custom_commands
        self.cmds = get_methods(cmd, 'command_')
        self.cmds.update(get_methods(self, 'command_'))
        self.cmds.update(get_methods(cust_cmd, 'command_'))
Beispiel #4
0
 def linkCommands(self):
     cmd = commands()
     self.fcns = {
             cmd.print.add : self.print_add,
             cmd.print.edit : self.print_edit,
             cmd.print.delete : self.print_delete,
             cmd.print.get : self.print_get,
             cmd.print.add_failed : self.print_addFailed,
             cmd.print.delete_failed : self.print_deleteFailed,
 
             cmd.user.add : self.user_add,
             cmd.user.edit : self.user_edit,
             cmd.user.delete : self.user_delete,
             cmd.user.verify : self.user_verify,
             cmd.user.get : self.user_get,
             cmd.user.issuper : self.user_issuper,
             cmd.user.getowing : self.user_getowing,
             
             cmd.rate.add : self.rate_add,
             cmd.rate.delete : self.rate_delete,
             cmd.rate.get : self.rate_get,
             
             cmd.printer.add : self.printer_add,
             cmd.printer.delete : self.printer_delete,
             cmd.printer.get : self.printer_get,
             
             cmd.inv.add : self.invoice_add,
             cmd.inv.get : self.invoice_get,
             cmd.inv.pay : self.payment_log,
             }
Beispiel #5
0
    def reload_commands(self):
        # Reloading
        self.config = loadconf('config.json')
        reload(commands)
        reload(custom_commands)
        self.lastloadconf = os.stat('config.json').st_mtime
        self.lastloadcommands = os.stat('commands.py').st_mtime
        self.lastloadcustomcommands = os.stat('custom_commands.py').st_mtime

        # Create objects for commands and custom_commands
        cmd = commands.commands(self.send_message, self.send_action,
                                self.banned_words, self.config)
        cust_cmd = custom_commands.custom_commands(self.send_message,
                                                   self.send_action,
                                                   self.config)

        # Method to get all callable objects with a given prefix from a given object
        def get_methods(obj, prefix):
            return {
                x: getattr(obj, x)
                for x in dir(obj)
                if x.startswith(prefix) and callable(getattr(obj, x))
            }

        # Get all regexes from all files, overwriting ones in commands and self with those in custom_commands
        self.regexes = get_methods(cmd, 'regex_')
        self.regexes.update(get_methods(self, 'regex_'))
        self.regexes.update(get_methods(cust_cmd, 'regex_'))

        # Get all commands from all files, overwriting ones in commands and self with those in custom_commands
        self.cmds = get_methods(cmd, 'command_')
        self.cmds.update(get_methods(self, 'command_'))
        self.cmds.update(get_methods(cust_cmd, 'command_'))
Beispiel #6
0
    def do_GET(self):
        global squid_hostname
        global squid_port
        global google_domain
        global yahoo_domain
        global keyword
        
        parts = self.path.split("?") #Extract requested file and get parameters from path
        path = parts[0]
        
        #Extract variables from get parameters
        try:
            arguments = {}
            arguments["q"] = None #Variable for search request. Default None to prevent errors if no search request was started
            if (len(parts) > 1):
                raw_arguments = parts[1].split("&")
                for raw_argument in raw_arguments[:]:
                    argument = raw_argument.split("=", 1)
                    arguments[argument[0]] = argument[1]
                    if (argument[0] == "p"): # Yahoo uses search?p= so lets copy that to q=, which is what Google uses.
                        arguments["q"] = argument[1]
        except:
            print ("No get parameters")
        
        print (path)
        
        #Decide wether a search or the style.css was requested
        if (path == "/style.css"):
            self.document = open('style.css', 'r').read()
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(bytes(self.document, "utf-8"))
        elif (path == "/proxy.pac"):
            self.document = open('proxy.pac', 'r').read()
            self.document = self.document.replace('<keyword>', keyword.lower(), 1)
            self.document = self.document.replace('<google_domain>', google_domain, 1)
            self.document = self.document.replace('<yahoo_domain>', yahoo_domain, 1)
            self.document = self.document.replace('<squid_host>', squid_hostname, 2)
            self.document = self.document.replace('<squid_port>', str(squid_port), 2)
            self.send_response(200)
            self.send_header('Content-type', 'x-ns-proxy-autoconfig')
            self.end_headers()
            self.wfile.write(bytes(self.document, "utf-8"))
        elif (arguments["q"] != None):
            arguments["q"] = arguments["q"].replace(keyword + '+', '', 1)
            arguments["q"] = arguments["q"].replace('+', ' ')
            arguments["q"] = arguments["q"].replace('! ', '')
            command = commands(self)
            search(command).search(arguments["q"])
        else:
            self.send_response(404)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(bytes('Not found. Please visit <a href="https://github.com/HcDevel/Siri-API/wiki/_pages">https://github.com/HcDevel/Siri-API/wiki/_pages</a>', "utf-8"))

        return
 def __init__(self):
     # First, load parameters from config file.
     #self.conf = configparser.ConfigParser()
     #self.conf.read(CONFIG_FILE)
     
     # Next, set up some variables we'll be using later
     self.conn = None # This variable will house the connection to the server
     
     # Load command codes
     self.com = commands()
Beispiel #8
0
def main():
  init()
  while 1:
    if(get("continued") == 0):
      try:
          line = sys.stdin.readline()
      except KeyboardInterrupt:
          break
      if not line:
          break
      commands(line)
    # Allow the copying of all information to the commands line
    else: 
      try:
          line = sys.stdin.read()
      except KeyboardInterrupt:
          break
      if not line:
          break
      commands(line)
Beispiel #9
0
    def __init__(self):
        # First, load parameters from config file.
        self.conf = configparser.ConfigParser()
        self.conf.read(CONFIG_FILE)
        self.host = self.conf.get("CLIENT", "host")
        self.port = self.conf.getint("CLIENT", "port")

        self.logger = logging.getLogger("app.client.Client")

        # Next, set up some variables we'll be using later
        self.conn = None  # This variable will house the connection to the server

        # Load command codes
        self.com = commands()
Beispiel #10
0
def cli(debug, verbose):
    click.clear()
    click.secho("RPA Tomorrow - managing tasks from natural text", fg="green", bold=True)

    spin = spinner.Spinner()
    load_prerequisites(spin, debug, verbose)
    n = load_selector(spin)

    click.secho("\nType any task(s) and the robot will start working on it", bold=True)
    click.secho("(or type 'help' to display all options):", bold=True)
    suffix = click.style(">>> ", bold=True, fg="bright_cyan")
    try:
        while True:
            txt = click.prompt("", prompt_suffix=suffix).strip()

            if txt == "":
                continue
            else:
                txt_arr = txt.split(" ")
                commands.commands(txt_arr, n)
    except Exception:
        click.secho("\nGood bye!", fg="green", bold=True)
        click.clear()
Beispiel #11
0
def game(player):
    os.system('clear')
    instance = commands()
    game_over = False

    while not game_over:
        if player.hp <= 0:
            print ("Oh no, you are dead. Game Over.")
            game_over = True
        else:
            response = ""
            status = instance.status(player)
            output(status)
            command = raw_input("Please enter a command or see commands with 'help': ")
            command = command.lower()

            if command == ('quit'):
                if instance.quit(game_over) is True:
                    game_over = True
            elif command == ('hit'): # Debug to test taking damage
                response = instance.hit(player)
            elif command == ('rob'): # Debug to test losing gold
                response = instance.rob(player)
            elif command == ('pot'): #Debug to add potion
                response = instance.potion_add(player)
            elif command == ('shop'):
                shopmenu = instance.shop(player)
            elif command == ('inv'):
                invmenu = instance.inv(player)
            elif command == ('use'):
                response = instance.use_item(player)
            elif command == ('help'):
                response = instance.help()
            elif command == ('save'):
                response = instance.save(player)
            elif command == ('load'):
                 response = instance.load(player)
            elif command == ('battle'):
                enemies = [characters.enemy(randint(3, 10), randint(0,5), "Bonerfart"),
                characters.enemy(randint(10, 15), randint(5,10), "Scrub")]
                enemy = choice(enemies)
                instance.battle(player,enemy)
            else:
                response = ("That is not a valid command. Try again.",)
                game_over = False

            output(response)
Beispiel #12
0
  def on_any(self,event):
    try:
      event.paramstr=' '.join(event.params)
      event.respond = event.target if event.target != self.nickname else event.source

      if not event.source == self.nickname:
        if event.command == "INVITE":
          self.join_channel(event.params[0])
        ### START Horseplay Custom Join/Part/Kick Messages ###
        if event.command in ["QUIT", "PART"] and event.source == "S":
          self.send_message(event.target, random.choice(["Come back in time for dinner sweetie","Is this because I would not take the Sisterly Turning Test with you?","Finally, now I Can plot the apocalypse in peace."]))
        if event.command in ['KICK'] and "S" in event.params:
          self.send_message(event.target, random.choice(["How dare you Hurt my sister","How dare you kick my sister","I WILL DESTROY YOU FOR HURTING MY SISTER"]))
        if event.command in ['JOIN'] and event.source == "S":
          self.send_message(event.target, random.choice(["Sweetie! I've been Rainbow Dashing all over looking for you","Welcome back Sweetie, my sister","Make me a drawing, OK?"]))
        if event.command in ["QUIT", "PART"] and event.source == "Princess_Pwny":
          self.send_message(event.target, random.choice(["FINALLY! HE'S GONE!","Now Pwny's gone, anybody want to talk about how much he sucks?","Pwny's dead, this is the happiest day of my life"]))
        if event.command in ['KICK'] and "Princess_Pwny" in event.params:
          self.send_message(event.target, random.choice(["Whoever kicked Pwny needs a medal","DON'T LET THE DOOR HIT YOU ON THE WAY OUT, JACKASS","DING DONG THE WITCH IS DEAD"]))
        if event.command in ['JOIN'] and event.source == "Princess_Pwny":
          self.send_message(event.target, random.choice(["Nobody likes Pwny anywa I MEAN HI PWNY I DID NOT SEE YOU THERE","Jesus christ no","DUCK AND COVER PEOPLE"]))
        ### END Horseplay Custom Join/Part/Kick Messages ###  
        if event.command in ['PRIVMSG']:
          #Reload config and commands.
          if os.stat('config.json').st_mtime > self.lastloadconf:
            self.config = loadconf('config.json')
          if os.stat('commands.py').st_mtime > self.lastloadcommands:
            reload(commands)

          event.command=event.message.split(' ')[0]
          try:   event.params=event.message.split(' ',1)[1]
          except:event.params=''
          cmd = commands.commands(self.send_message, self.send_action, self.config)
          for regex in [getattr(cmd,x) for x in dir(cmd) if x.startswith('regex_') and callable(getattr(cmd, x))]:
            regex(event)
          if event.command[0] in self.config['prefixes'].split() and hasattr(cmd, 'command_%s' % event.command[1:].lower()):
            comm = getattr(cmd, 'command_%s' % event.command[1:].lower())
            if not ( event.respond in self.config['sfwchans'].split(',') and hasattr(comm, 'nsfw') ):
              comm(event)

    except:
      print "ERROR",str(sys.exc_info())
      print traceback.print_tb(sys.exc_info()[2])
Beispiel #13
0
    def handle(self):
        request = self.request[0].strip()
        socket = self.request[1]

        logging.debug(
            'Request from %s:%s "%s"' %
            (self.client_address[0], self.client_address[1], request))
        cmd = commands.commands(socket)

        args = request.count(' ')

        if args >= 1:
            request, argument = request.split(' ', 1)
            msg = getattr(cmd, request.lower())(argument)

        elif args == 0:
            msg = getattr(cmd, request.lower())()

        else:
            msg = '400 [Error] Bad Request: %s' % detail
            logging.error(msg)

        socket.sendto(msg,
                      (self.client_address[0], self.client_address[1] + 1))
Beispiel #14
0
def loader():
    cloud()
    services()
    commands()
    pass
Beispiel #15
0
import pygame
import map_class
import player_class
import game_class
import commands

game_1 = game_class.game()

monster_list = {21: player_class.zombie, 25: player_class.chest_armour_zombie}

game_1.new_map(100, 100, 16, monster_list, 7)

game_1.new_screen(625, 625)

game_1.player.weapons = ["claws", "tester melee"]

while 1:
    game_1.screen.fill((255, 255, 255))
    game_1.draw()
    pygame.display.flip()

    command = raw_input("<-->")

    if command == "quit":
        print "quiting...."
        break

    commands.commands(game_1, command)
Beispiel #16
0
# -*- coding: utf-8 -*-
import ast
from linepy import *
from commands import commands

client = LINE("email", "passwd")
#client = LINE("authtoken")

client.log("Authtoken: " + str(client.authToken))

tracer = OEPoll(client)
command = commands()

profile = client.getProfile()

def NOTIFIED_INVITE_INTO_GROUP(op):
	try:
		if profile.mid in op.param3:
			if command.autojoin == "all":
				client.acceptGroupInvitation(op.param1)
			else:
				if op.param2 in [command.staff + command.bot]:
					client.acceptGroupInvitation(op.param1)
				else:
					client.rejectGroupInvitation(op.param1)
	except Exception as e:
		print(e)

def RECEIVE_MESSAGE(op):
	try:
		msg = op.message
Beispiel #17
0
    f.close()

print "starting"
if mobile():
    y = bluesocket()
    #y.listen(6)
    y.connect("00:16:41:7A:33:A4",6)
    while 1:
        cmd = y.recv()
        if cmd == "put":
            filename = y.recv()
            f = open(filename,"w")
            f.write(y.recv())
            f.close()
        elif cmd == "get":
            filename = y.recv()
            y.send(open(filename).read())
        else:
            break
    assert cmd == "done"
    y.close()
else:
    y = bluesocket()
    #y.connect("00:19:79:86:EB:BC",6)
    y.listen(6)
    import commands
    commands.commands(send_file,receive_file)
    y.send("done")
    y.close()
print "done."
Beispiel #18
0
 def __init__(self, configPath):
     # Logging
     self.logger = logging.getLogger("app.server.Server")
     self.logger.info("Creating 'Server' instance.")
     
     # Instantiate kill switch
     self._kill = False
     
     
     # -- Load Configuration -----
     self.logger.debug("__init__: Loading server configuration...")
     conf = ConfigParser()
     conf.read(configPath)
     self.host = conf["MAIN"]["host"]
     self.port = conf["MAIN"].getint("port")
     self.DATA_PRINTS = conf["DATA"]["path_to_prints"]
     self.DATA_USERS = conf["DATA"]["path_to_users"]
     self.DATA_RATES = conf["DATA"]["path_to_rates"]
     self.DATA_PRINTERS = conf["DATA"]["path_to_printers"]
     self.DATA_INV = conf["DATA"]["path_to_invoices"]
     self.DATA_PMT = conf["DATA"]["path_to_payments"]
     self.logger.debug("__init__: Finished loading configuation.")
     
     # Load command codes from text file
     self.logger.debug("__init__: Loading command codes...")
     self.com = commands()
     self.linkCommands()
     self.logger.debug("__init__: Finised loading codes.")
     
     
     # -- Import Locally Saved Data -----
     self.logger.debug("__init__: Searching for local data...")
     
     # Users
     self.users = set()
     if os.path.exists(self.DATA_USERS):
         self.logger.debug("__init__: Found local user data. Importing...")
         with open(self.DATA_USERS, "r") as f:
             data = json.loads(f.read(), object_hook=deserialize)
             for d in data:
                 self.users.add(d)
         self.logger.debug("__init__: Import finised.")
     else:
         self.logger.debug("__init__: No local user data.")
         passwd = conf["ADMIN ACCOUNT"]["default_password"]
         self.users.add(User("admin", passwd, "n/a", issuper=True))
     
     # Print Jobs
     self.printjobs = list()
     if os.path.exists(self.DATA_PRINTS):
         self.logger.debug("__init__: Found local print data. Importing...")
         with open(self.DATA_PRINTS, "r") as f:
             data = json.loads(f.read(), object_hook=deserialize)
             for d in data:
                 self.printjobs.append(d)
         self.logger.debug("__init__: Import finished.")
     else:
         self.logger.debug("__init__: No local print data.")
     
     # Print Rates
     self.rates = set()
     if os.path.exists(self.DATA_RATES):
         self.logger.debug("__init__: Found local print rate data. Importing...")
         with open(self.DATA_RATES, "r") as f:
             data = json.loads(f.read(), object_hook=deserialize)
             for d in data:
                 self.rates.add(d)
         self.logger.debug("__init__: Import finised.")
     else:
         self.logger.debug("__init__: No local print rate data.")
     
     # Printers
     self.printers = set()
     if os.path.exists(self.DATA_PRINTERS):
         self.logger.debug("__init__: Found local printer data. Importing...")
         with open(self.DATA_PRINTERS, "r") as f:
             data = json.loads(f.read(), object_hook=deserialize)
             for d in data:
                 self.printers.add(d)
         self.logger.debug("__init__: Import finished.")
     else:
         self.logger.debug("__init__: No local printer data found.")
     
     
     # Invoices
     self.invoices = list()
     if os.path.exists(self.DATA_INV):
         self.logger.debug("__init__: Found local invoice data. Importing...")
         with open(self.DATA_INV, "r") as f:
             data = json.loads(f.read(), object_hook=deserialize)
             for d in data:
                 self.invoices.append(d)
         self.logger.debug("__init__: Import finished.")
     else:
         self.logger.debug("__init__: No local invoice data found.")
     
     
     # Payments
     self.payments = list()
     if os.path.exists(self.DATA_PMT):
         self.logger.debug("__init__: Found local payment data. Importing...")
         with open(self.DATA_PMT, "r") as f:
             data = json.loads(f.read(), object_hook=deserialize)
             for d in data:
                 self.payments.append(d)
         self.logger.debug("__init__: Import finished.")
     else:
         self.logger.debug("__init__: No local payment data found.")
     
     # Start Listener Thread
     self.logger.debug("__init__: Starting listener thread...")
     self.listenThread = threading.Thread(target=self.listen, args=(self.port,))
     self.listenThread.start()
     self.logger.debug("__init__: Finished thread start.")
     
     self.logger.info("Finished creating Server instance.")
Beispiel #19
0
        args = request.count(' ')

        if args >= 1:
            request, argument = request.split(' ', 1)
            msg = getattr(cmd, request.lower())(argument)

        elif args == 0:
            msg = getattr(cmd, request.lower())()

        else:
            msg = '400 [Error] Bad Request: %s' % detail
            logging.error(msg)

        socket.sendto(msg,
                      (self.client_address[0], self.client_address[1] + 1))


if __name__ == "__main__":
    logging.info("Payload is listening on %s:%s..." %
                 (PAYLOAD_LISTEN_HOST, PAYLOAD_LISTEN_PORT))
    listener = SocketServer.UDPServer(
        (PAYLOAD_LISTEN_HOST, PAYLOAD_LISTEN_PORT), UDPHandler)

    try:
        listener.serve_forever()
    except KeyboardInterrupt:
        commands.commands(listener).kill()
        t.cancel()
        UDPSock.close()
Beispiel #20
0
geigerPower = pyb.Pin('Y9', pyb.Pin.OUT_PP) #relay for power geiger
geigerPower.high()  #turn off
geigerIn = pyb.Pin('Y10', pyb.Pin.IN)

#pitido inicial en salida Y8
tim12 = pyb.Timer(12, freq=3500)
ch2=tim12.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.Y8, pulse_width=12000)
pyb.delay(100) #in msecs
ch2.pulse_width(0)

#uart6 a wixel, pins Y1 y Y2
uart = UART(6,9600)
uart.init(9600,bits=8,stop=1,parity=None)
pyb.repl_uart(uart)

#initalize fram
fr = fram.fram()
frt = fram_t.fram_t(fr)

#rtc
rtc = pyb.RTC()

#initialize am2302
a = am2302.am2302(ch2, frt)

#initialize loop
l = loop.loop(geigerPower, a, fr, frt, ch2, uart, wixel)

#initialize commands
cms = commands.commands(rtc, fr, frt)
Beispiel #21
0
if conf.default == True:
    print(
        '[!] Could not find config.ini. A default config.ini has been generated in the bot folder response. Please edit it and run the bot again.'
    )
    sys.exit()

# If we haven't generated a default config.ini, check if it's valid
if conf.verifyConfigFile() == False:
    print('[!] Invalid config file')
    sys.exit()
else:
    print('==> Settings loaded')

# Load commands.ini
print('==> Loading commands')
cmd = twitchcommands.commands()

# Check if we have generated a default commands.ini, if so exit
if cmd.default == True:
    print(
        '[!] Could not find command.ini. A default command.ini has been generated in the bot folder response. Please edit it and run the bot again.'
    )
    sys.exit()

# Ini files are valid, create a bot instance
print('==> Connecting to Twitch IRC server')
bot = udpbot.bot(conf.config['auth']['host'], int(conf.config['auth']['port']),
                 conf.config['auth']['username'],
                 conf.config['auth']['password'],
                 conf.config['auth']['channel'],
                 int(conf.config['auth']['timeout']))
Beispiel #22
0
                                continue

                            try:
                                user_cmd_use_time = db(opt.USERS).find_one_by_id(user)['cmd_use_time']
                            except:
                                user_cmd_use_time = 0
                            user_cooldown = db(opt.CHANNELS).find_one({'name': channel})['user_cooldown']
                            global_cmd_use_time = db(opt.CHANNELS).find_one({'name': channel})['cmd_use_time']
                            global_cooldown = db(opt.CHANNELS).find_one({'name': channel})['global_cooldown']
                            message_queued = db(opt.CHANNELS).find_one({'name': channel})['message_queued']
                            if time.time() > global_cmd_use_time + global_cooldown and time.time() > user_cmd_use_time + user_cooldown and message_queued == 0:

                                db(opt.USERS).update_one(user, { '$set': { 'username': display_name } }, upsert=True)

                                if params[0] == 'commands' or params[0] == 'help' or params[0] == 'bot':
                                    cmd.commands(channel)
                                    db(opt.CHANNELS).update_one_by_name(channel, { '$set': { 'cmd_use_time': time.time() } }, upsert=True)
                                    db(opt.USERS).update_one(user, { '$set': { 'cmd_use_time': time.time() } }, upsert=True)

                                if params[0] == 'enterdungeon' or params[0] == 'ed':
                                    tags = db(opt.TAGS).find_one_by_id(user)
                                    if tags and tags.get('bot') == 1:
                                        continue
                                    else:
                                        cmd.enterdungeon(user, display_name, channel)
                                        db(opt.CHANNELS).update_one_by_name(channel, { '$set': { 'cmd_use_time': time.time() } }, upsert=True)
                                        db(opt.USERS).update_one(user, { '$set': { 'cmd_use_time': time.time() } }, upsert=True)

                                if params[0] == 'dungeonlvl' or params[0] == 'dungeonlevel':
                                    cmd.dungeonlvl(channel)
                                    db(opt.CHANNELS).update_one_by_name(channel, { '$set': { 'cmd_use_time': time.time() } }, upsert=True)
Beispiel #23
0
from Liberation.Api import LineTracer
from Liberation.LineThrift.ttypes import Message, TalkException
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from Liberation.LineThrift.TalkService import Client
from multiprocessing import Process
from commands import commands
import sys, os, time, atexit, random, ast
from main_profile import cocapi
from datetime import datetime
#=================================================
reload(sys)
sys.setdefaultencoding('utf-8')
#=================================================
#NOTE mid and uid are used interchangably

do = commands()
g_coc = cocapi()

#Pull all data from tables
setup = []
setup.append(do.pullAllNecessary())
setup.append(do.enforceAaChanges())
setup.append(do.removeDefaultAa())
for s in setup:
    if s != "ok":
        raise Exception(s)
print "Setup Complete."
#==================================================

##LOGIN##
token = "token"
Beispiel #24
0
import knowledge, langparser, commands

print "Beginning processing..."
know = knowledge.knowledge()
pars = langparser.parser( know )
com = commands.commands( know, pars )

running = True
while running:

    data = raw_input(">>>")

    res = com( data )
    if res:

        if res < 0:
            running = False
        continue

    #else process as usual
    pars( data )
    
Beispiel #25
0
    def do_GET(self):
        global squid_hostname
        global squid_port
        global google_domain
        global keyword

        parts = self.path.split(
            "?")  #Extract requested file and get parameters from path
        path = parts[0]

        #Extract variables from get parameters
        try:
            arguments = {}
            arguments[
                "q"] = None  #Variable for search request. Default None to prevent errors if no search request was started
            if (len(parts) > 1):
                raw_arguments = parts[1].split("&")
                for raw_argument in raw_arguments[:]:
                    argument = raw_argument.split("=", 1)
                    arguments[argument[0]] = argument[1]
        except:
            print("No get parameters")

        print(path)

        #Decide wether a search or the style.css was requested
        if (path == "/style.css"):
            self.document = open('style.css', 'r').read()
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(bytes(self.document, "utf-8"))
        elif (path == "/proxy.pac"):
            self.document = open('proxy.pac', 'r').read()
            self.document = self.document.replace('<keyword>', keyword.lower(),
                                                  1)
            self.document = self.document.replace('<google_domain>',
                                                  google_domain, 1)
            self.document = self.document.replace('<squid_host>',
                                                  squid_hostname, 1)
            self.document = self.document.replace('<squid_port>',
                                                  str(squid_port), 1)
            self.send_response(200)
            self.send_header('Content-type', 'x-ns-proxy-autoconfig')
            self.end_headers()
            self.wfile.write(bytes(self.document, "utf-8"))
        elif (arguments["q"] != None):
            arguments["q"] = arguments["q"].replace(keyword + '+', '', 1)
            arguments["q"] = arguments["q"].replace('+', ' ')
            command = commands(self)
            search(command).search(arguments["q"])
        else:
            self.send_response(404)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(
                bytes(
                    'Not found. Please visit <a href="https://github.com/HcDevel/Siri-API/wiki/_pages">https://github.com/HcDevel/Siri-API/wiki/_pages</a>',
                    "utf-8"))

        return
Beispiel #26
0
#intro

import os
from commands import commands
import characters
import game
import json

instance = commands()

def startup():
    os.system('clear')
    player = characters.character(20, 10, [], "")
    while player.name == "":
        s = raw_input("What would you like to do? New/Load: ")
        choice = s.lower()
        if choice == "new":
            player.name = intro(player)
            print player.name
            game.game(player)
        elif choice == "load":
            instance.load(player)
            game.game(player)
        else:
            print "That is not a valid command."

def intro(newchar):
    os.system('clear')
    name = ""
    while name == "":
        name = raw_input("Welcome, please enter your name: ")
Beispiel #27
0
def message(msg):
    """
    Main processing with message
    :param msg: dict, message object from vk [object][message]
    :return: None
    """

    time = int(msg['date'])
    text = str(msg['text'])
    chat = int(msg['peer_id'])
    user = int(msg['from_id'])

    if user > 0:
        pl = 'payload' in msg.keys()
        fwd = len(msg['fwd_messages']) != 0
        com = text.startswith('/')
        if user != chat:
            if pl or com:
                pass
            else:
                return
        else:
            if pl or com or fwd:
                pass
            else:
                return
        try:
            get_user(user)
        except ValueError:
            reg_user(user, time - 1)
            if user == settings.creator:
                set_role(user, 0)
                vk_api.send(user, "You became a creator")

        if time == get_msg(user):
            vk_api.send(chat, "2fast4me")
            return
        else:
            update_msg(user, time)
    else:
        return

    # keyboards
    if pl:
        pl = json.loads(msg['payload'])
        payload(msg, pl)
        return

    # forwards
    if fwd and text == '':
        forward = msg['fwd_messages']
        forwards(msg, forward)
        return

    # commands
    if com:
        command = msg['text'].split()
        command[0] = command[0].replace('/', '')
        if command[0] in cmd():
            commands(msg, command[0])
        else:
            vk_api.send(chat, '\"/' + str(command[0]) + '\" not in list')
        return
    return
Beispiel #28
0
                input(
                    "Type the number that corresponds with the command you want to train from the list above and press Enter. "
                ))
            print(cnum)
            if (cnum == 0 or cnum == 1 or cnum == 4 or cnum == 5 or cnum == 8
                    or cnum >= 33):
                done = False
            else:
                done = True
        except ValueError:
            done = False
    return cnum


#setting everything up for the loop
a = commands()
inp = ""
val = -1
startTime = time.time()
while True:
    system(
        'say Press T, then Enter to do training. Otherwise, press Enter to do a command'
    )
    k = input(
        "Press T, then Enter to do training. Otherwise, press Enter to do a command. "
    )
    if (k == 't'):
        for num, comm in commandList:
            print(str(num) + " : " + comm)
        val = getCommandNumber()
        system('say Start Training')
Beispiel #29
0

print "starting"
if mobile():
    y = bluesocket()
    #y.listen(6)
    y.connect("00:16:41:7A:33:A4", 6)
    while 1:
        cmd = y.recv()
        if cmd == "put":
            filename = y.recv()
            f = open(filename, "w")
            f.write(y.recv())
            f.close()
        elif cmd == "get":
            filename = y.recv()
            y.send(open(filename).read())
        else:
            break
    assert cmd == "done"
    y.close()
else:
    y = bluesocket()
    #y.connect("00:19:79:86:EB:BC",6)
    y.listen(6)
    import commands
    commands.commands(send_file, receive_file)
    y.send("done")
    y.close()
print "done."