示例#1
0
async def on_message(message: discord.Message):
    if not await check_message(
            client, message
    ):  # check basic conditions like length and not responding to himself
        return

    if message.channel.id in cfg.get("channel_ids",
                                     dict()).get("suggestions", []):
        await message.delete()
        info = InfoEmbed(f"Suggestion by {message.author.display_name}")
        info.description = message.content
        info.set_author(name=message.author.display_name,
                        icon_url=message.author.avatar_url_as(format="webp"))
        info.set_footer(text=f"UserID: {message.author.id}")
        new_message = await message.channel.send(embed=info)
        await new_message.add_reaction('👍')
        await new_message.add_reaction('👎')
        return

    if message.content.lower().startswith(
            str(cfg.options["invoke_normal"]).lower()):
        params = commands.parse(message.content, False)
        if params:
            if params[0].lower() in commands.commands.keys():
                await commands.commands[params[0].lower()](client, message,
                                                           params[1:])

    elif message.content.lower().startswith(
            str(cfg.options["invoke_mod"]).lower()):
        params = commands.parse(message.content, True)
        if params:
            if params[0].lower() in commands.mod_commands.keys():
                await commands.mod_commands[params[0].lower()](client, message,
                                                               params[1:])
示例#2
0
def read_messages(channel = None, lastId = None):
  channel_info = config.rocket.channels_info(room_id = channel).json()
  currentId = channel_info['channel']['_updatedAt']
  if currentId != lastId:
    new_message = config.rocket.channels_history(room_id = channel, count=1).json()
    pprint(new_message)
    commands.parse(new_message)
  return currentId
示例#3
0
文件: privmsg.py 项目: ihptru/Ubot
def parse(self, recv):
    irc_user_nick = recv.split ( '!' ) [ 0 ] . split ( ":")[1]
    irc_user_host = recv.split ( '@' ) [ 1 ] . split ( ' ' ) [ 0 ]
    irc_user_message = self.data_to_message(recv)
    chan = recv.split()[2]  #channel
    
    print ( ( "[%s] %s: %s" ) % (self.irc_host, irc_user_nick, irc_user_message) )
    # Message starts with command prefix?
    if ( irc_user_message != '' ):
        if ( irc_user_message[0] == config.prefix ):
            self.command = irc_user_message[1:].replace("'","''")
            commands.parse(self, irc_user_nick, chan)
示例#4
0
async def on_message(message):
    if not await check_message(client, message):  # check basic conditions like length and not responding to himself
        return 0

    if message.content.lower().startswith(str(cfg.options["invoke_normal"]).lower()):
        params = commands.parse(message.content, False)
        if params[0].lower() in commands.commands.keys():
            await commands.commands[params[0].lower()](client, message, params[1:])

    elif message.content.lower().startswith(str(cfg.options["invoke_mod"]).lower()):
        params = commands.parse(message.content, True)
        if params[0].lower() in commands.mod_commands.keys():
            await commands.mod_commands[params[0].lower()](client, message, params[1:])
示例#5
0
 def _receive(self, buff_size=2048):
     try:
         msg = self._socket.recv(buff_size).decode()
         self._file.write(cmd.drop_commands_for_ts(msg) + '\n')
         if cmd.got_server(msg):                             # save the ip_addr:port of the client's server
             client_addr.append(cmd.parse(msg))
             client_thread.append(self)
         if cmd.wants_peers(msg):                            # send the list of peers for the client to connect
             self._socket.sendall(bytes(cmd.client_to_str(client_addr), 'UTF-8'))
     except socket.error:
         pass
 def on_message(self, message):
     print 'message received %s' % message
     print "self: "+str(self)
     if "@" in message:
         self.write_message("Unacceptable input")
     else:
         if (clients[str(self)]["state"] == "unknown"):
             clients[str(self)]["username"] = message
             clients[str(self)]["state"] = "gave_username"
             self.write_message("Please give a password: "******"state"] == "gave_username"):
             clients[str(self)]["password"] = message
             self.write_message("Pleaes confirm your password: "******"state"] = "confirm_password"
         elif (clients[str(self)]["state"] == "confirm_password"):
             if (clients[str(self)]["password"] == message):
                 clients[str(self)]["state"] = "logged_in"
                 print parse("@make_character")
                 self.write_message("Welcome to Haeckel!")
                 self.write_message(parse("look"))
                 self.write_message(parse("prompt"))
             else:
                 self.write_message("Password did not match.")
                 clients[str(self)]["password"] = ""
                 self.write_message("Please give a password: "******"state"] = "gave_username"
         elif (clients[str(self)]["state"] == "logged_in"):
             self.write_message(parse(message))
             self.write_message(parse("prompt"))
示例#7
0
    async def handle_socket(self, reader, writer):
        writer.write(b'>> ')

        while True:
            line = await reader.readline()
            if line == b'':
                break
            command = line.decode('utf8').strip().lower()
            try:
                self.robot.enqueue(commands.parse(command, self.robot))
            except SyntaxError as e:
                print('<telnet> Not queued due to error:', command)
                writer.write(b'Error: %s\r\n' % str(e).encode('ascii'))
            else:
                print('<telnet> Queued:', command)
            writer.write(b'>> ')
def parse(
    prompt='> '
):  # Can change this prompt from default by using: parse('my_prompt')
    text = input(prompt).strip().lower()  # Remove whitespace, lowercase
    if not text:
        return  # No input

    words = text.split()  # Split by whitespace
    command = words[0]
    args = words[1:]

    try:
        return commands.parse(command, args)
    except InvalidCommandException as e:
        print(e)
        return False
示例#9
0
while running:
    inputready,outputready,exceptready = select.select(input,[],[])     # The server uses the .select() call to multiplex multiple clients
    for s in inputready:

        if s == server:
                                                                        # handle the server socket
            client, address = server.accept()
            input.append(client)
            print "[+] New thread started for %s"% str(address) 
        elif s == sys.stdin:
                                                                        # handle standard input
            junk = sys.stdin.readline()
            print "Server disconnected..."
            running = 0

        else:
                                                                        # handle all other sockets
            data = s.recv(size)
            if data:
                print "data rcv: "+data
                data = parse(data)
                print "data snd: "+data
                s.send(data)                                            # The parse command is run from the commands.py file
            else:
                print "%s disconnected improperly."% s                  # Indicates if a client disconnected properly
                s.close()
                input.remove(s)
server.close()


 def test_buy(self):
     self.assertEqual(commands.parse("buy sword"), "Example output needed")
示例#11
0
import commands

if __name__ == "__main__":
    commands.parse()
示例#12
0
 def command(self, cmd):
     command = commands.parse(cmd)
     command.start(self, self.game)
 def test_drop_without_argument(self):
     self.assertEqual(commands.parse("drop"), "Arguments needed")
 def test_east(self):
     self.assertEqual(commands.parse("east"), "You go east")
 def test_dice(self):
     self.assertEqual(commands.parse("dice 1d6"), range(6))
 def test_dice_with_messy_argument(self):
     self.assertEqual(commands.parse("dice waaaghh"), "Problem with input")
 def test_desc(self):
     self.assertEqual(commands.parse("desc"), "Example description needed")
 def test_consider(self):
     self.assertEqual(commands.parse("consider thargrugrog"), "Example output needed")
 def test_deposit_bad_arguments(self):
     self.assertEqual(commands.parse("deposit waaaghh"), "Problem with input")
 def test_browse(self):
     self.assertEqual(commands.parse("browse"), "Example output needed")
 def test_areas(self):
     self.assertEqual(commands.parse("areas"), "Example area listing needed")
 def test_config(self):
     self.assertEqual(commands.parse("config"), "Example output needed")
 def test_buy_item_doesnt_exist(self):
     self.assertEqual(commands.parse("buy sword"), "Item does not exist")
 def test_delete(self):
     self.assertEqual(commands.parse("delete"), "Delete successful!")
 def test_buy_merchant_doesnt_exist(self):
     self.assertEqual(commands.parse("buy sword"), "Merchant doesnt exist")
 def test_desc_with_argument(self):
     self.assertEqual(commands.parse("desc You look like a beautiful mermaid!"), "Example output needed")
 def test_buy_check_wealth_deducted(self):
     self.assertEqual(commands.parse("buy sword"), "Wealth deducted")
 def test_dice_without_argument(self):
     self.assertEqual(commands.parse("dice"), "No arguments provided")
 def test_sell(self):
     self.assertEqual(commands.parse("sell sword"), "Example output needed")
 def test_drop(self):
     self.assertEqual(commands.parse("drop longsword"), "You drop a longsword")
 def test_sell_check_wealth_added(self):
     self.assertEqual(commands.parse("sell sword"), "Wealth deducted")
 def test_drop_item_not_in_inventory(self):
     self.assertEqual(commands.parse("drop frogsword"), "You cannot find that item")
 def test_balance_where_bank_exists(self):
     self.assertEqual(commands.parse("balance"), "Example output needed")
 def test_east_is_locked(self):
     self.assertEqual(commands.parse("east"), "East is locked.")
 def test_balance_where_bank_does_not_exist(self):
     self.assertEqual(commands.parse("balance"), "There is no bank here")
示例#36
0
def handle_client(connection, address):
    client = Client(connection, address)
    try:
        while True:
            client.send_message(enums.MessageType.INFO,
                                "Can you please indicate your username?")
            client_username = client.receive_message()
            if client_username == "/exit":
                commands.general_exit(client, None, None)
                client.get_connection().shutdown(socket.SHUT_RDWR)
                client.get_connection().close()
                print("[%s] Client from IP address %s disconnected!" %
                      (datetime.now().strftime(
                          settings.DATETIME_FORMAT), client.get_address()))
                return True

            if len(client_username) < 3:
                client.send_message(
                    enums.MessageType.ERROR,
                    "Your username must be at least 3 characters long!")
                continue

            # Check if client username is banned
            client_banned = persistence.users.is_banned(client_username)
            if isinstance(client_banned, bool) and client_banned:
                client.send_message(
                    enums.MessageType.ERROR,
                    "Your username is permanently banned from the server!")
                client.get_connection().shutdown(socket.SHUT_RDWR)
                client.get_connection().close()
                print("[%s] Client with username %s is permanently banned!" %
                      (datetime.now().strftime(
                          settings.DATETIME_FORMAT), client_username))
                return True
            elif client_banned > 0:
                client.send_message(
                    enums.MessageType.ERROR,
                    "Your username is banned from the server for %d more hours!"
                    % client_banned)
                client.get_connection().shutdown(socket.SHUT_RDWR)
                client.get_connection().close()
                print(
                    "[%s] Client with username %s is banned for %d more hours!"
                    % (datetime.now().strftime(settings.DATETIME_FORMAT),
                       client_username, client_banned))
                return True

            if client_username in globals.client_list:
                client.send_message(
                    enums.MessageType.ERROR,
                    "The indicated username is already connected!")
            elif persistence.users.client_exists(client_username):
                client.send_message(
                    enums.MessageType.INFO,
                    "This username is registered, please indicate your password!"
                )
                client_password = client.receive_message()
                if persistence.users.get_client(client_username,
                                                client_password):
                    client.set_logged(True)
                    client.set_level(
                        persistence.users.get_level(client_username))
                    client.send_message(enums.MessageType.INFO,
                                        "You are now logged in!")
                    break
                else:
                    client.send_message(
                        enums.MessageType.ERROR,
                        "The typed password is wrong, please try again!")
            else:
                break

        client.set_username(client_username)
        globals.client_list[client.get_username()] = client
        client.send_message(
            enums.MessageType.INFO,
            "You are now connected, %s!" % client.get_username())
        for channel_client in globals.channel_list["general"].get_clients():
            if channel_client in globals.client_list:
                globals.client_list[channel_client].send_message(
                    enums.MessageType.INFO,
                    "Client @%s connected from the server!" %
                    client.get_username())
        print("[%s] Client connected with username %s" %
              (datetime.now().strftime(
                  settings.DATETIME_FORMAT), client.get_username()))

        # Join 'general' channel by default
        commands.channel_join(client, "general", None)

        if not client.is_logged():
            client.send_message(
                enums.MessageType.INFO,
                "In order to use this chat you do need to register your username."
                "\nFor that just type '/register <password>'.")

        while True:
            try:
                message = client.receive_message()
                rmx = datetime.now()

                if not message:
                    print(
                        "[%s] Communication with the client on  IP address %s has been terminated..."
                        % (datetime.now().strftime(
                            settings.DATETIME_FORMAT), client.get_address()))
                    break
            except OSError:
                break

            print("[%s] Received from @%s on #%s: %s" %
                  (datetime.now().strftime(settings.DATETIME_FORMAT),
                   client.get_username(), client.get_channel(), message))
            if not commands.parse(client, message, rmx):
                break

        # Close client connection
        for channel in globals.channel_list.values():
            channel.remove_client(client.get_username())
        for channel_client in globals.channel_list["general"].get_clients():
            if channel_client in globals.client_list:
                globals.client_list[channel_client].send_message(
                    enums.MessageType.INFO,
                    "Client @%s disconnected from the server!" %
                    client.get_username())
        if client.get_username() in globals.client_list:
            globals.client_list.pop(client.get_username())
        client.get_connection().shutdown(socket.SHUT_RDWR)
        client.get_connection().close()
        print("[%s] Client %s disconnected!" % (datetime.now().strftime(
            settings.DATETIME_FORMAT), client.get_username()))
    except socket.error as error:
        client.get_connection().shutdown(socket.SHUT_RDWR)
        client.get_connection().close()
        if client.get_username() is not None:
            for channel in globals.channel_list.values():
                channel.remove_client(client.get_username())
            for channel_client in globals.channel_list["general"].get_clients(
            ):
                if channel_client in globals.client_list:
                    globals.client_list[channel_client].send_message(
                        enums.MessageType.INFO,
                        "Client @%s disconnected from the server!" %
                        client.get_username())
            if client.get_username() in globals.client_list:
                globals.client_list.pop(client.get_username())
        print("[%s] Client from IP address %s connection error! error: %s" %
              (datetime.now().strftime(
                  settings.DATETIME_FORMAT), address, error))
 def test_deposit_where_bank_exists(self):
     self.assertEqual(commands.parse("deposit 1000"), "Example output needed")
示例#38
0
                }
                instagram_following = {
                    '@' + x[0]
                    for x in db.get_following('instagram')
                }

                send_privmsg(message_author,
                             'Twitter: ' + str(twitter_following))
                send_privmsg(message_author,
                             'Instagram: ' + str(instagram_following))

            elif message_contents.startswith(
                ("%s: ") % NICK) and not is_privmsg:
                logger.info('Got command')

                parsed_command = commands.parse(message_contents)
                send_message_to_channel(message_channel, parsed_command)
                logger.info('Returned: ' + parsed_command)

            elif is_privmsg:
                logger.info('Got command as PM')

                parsed_command = commands.parse(message_contents)
                send_privmsg(message_author, parsed_command)
                logger.info('Returned: ' + parsed_command)

    for row in db.get_post_queue():

        # Assembles and sends the IRC message
        # Platform-specific formatting
        if row[1] == 'Instagram' or row[1] == 'Twitter':
 def test_deposit_where_bank_does_not_exist(self):
     self.assertEqual(commands.parse("deposit 1000"), "There is no bank here")
示例#40
0
 def command_on_enter(self,value):
     command = value.text
     self.commandField.text = ""
     commands.parse(command)
 def test_deposit_no_arguments(self):
     self.assertEqual(commands.parse("deposit"), "No arguments found")