Example #1
0
async def cog_reload(ctx, cog):
    bot.unload_extension(f'{cog}.src.{cog}')
    bot.load_extension(f'{cog}.src.{cog}')
    length = functions.get_length(f"{cog}/src/{cog}.py")
    await ctx.send(f'`{cog.upper()} cog was reloaded. ({length} lines)`',
                   delete_after=5.0)
    functions.log(f'({length} lines) {cog} был перезагружен.', 'm', 'COG')
Example #2
0
async def cog_load(ctx, cog):
    try:
        bot.load_extension(f'{cog}.src.{cog}')
    except commands.errors.ExtensionAlreadyLoaded:
        await ctx.send(f'`{cog.upper()} is already loaded.`', delete_after=5.0)
        return
    length = functions.get_length(f"{cog}/src/{cog}.py")
    await ctx.send(f'`{cog.upper()} cog was loaded. ({length} lines)`',
                   delete_after=5.0)
    functions.log(f'({length} lines) {cog} был загружен.', 'm', 'COG')
Example #3
0
def init_server_connection():
    # create socket for connection
    try:
        server = socket.socket()
    except socket.error as e:
        log(e)
        sys.exit(-1)

    # assign port that is not in use
    port = constants.port
    server.bind(('', port))

    return server, port
Example #4
0
def client_connection(db, conn, host, port, listen_port):
    log(f'Client connected from {host}:{port}')

    # add user to database
    db.AddUser(host, port, listen_port)

    while True:
        # get action from client
        message = conn.recv(1024).decode()

        # if user wants to see files
        if message == Action.get:
            # get all files that dont belong to user
            files = {'files': db.GetFiles(host, port)}
            conn.send(f'{json.dumps(files)}\0'.encode())

        # if user wants to share his files
        if message == Action.share:
            conn.send('ok'.encode())
            # get path that stores files
            path = conn.recv(1024).decode()
            conn.send('Path Saved'.encode())

            # get all files that are not in provided folder
            buffer = ''
            while '\0' not in buffer:
                buffer += conn.recv(4096).decode()

            files = json.loads(buffer[0:buffer.index('\0')])['files']
            conn.send('SAVED'.encode())

            # save path in database
            db.AssignFolderPath(host, port, path, files)

        # if user wants to download file
        if message == Action.download:
            conn.send('ok'.encode())
            # get file name
            file = conn.recv(4096).decode()

            # find user that has this file and return info about it
            data = json.dumps(db.GetFileInfo(host, port, file))
            conn.send(data.encode())

        # if user wants to exit
        if message == Action.exit:
            # remove him from database
            db.DeleteUser(host, port)
            break
    log(f'Connection closed with {host}:{port}')
    conn.close()
Example #5
0
 async def on_voice_state_update(self, member, before, after):
     voice_client = self.voice_client
     if (member != self.bot.user):
         if (after.channel):
             if (after.channel.id == variables.SAY_CHANNEL):
                 await asyncio.sleep(0.5)
                 audio = randomorg.element(variables.FILES)
                 try:
                     voice_client.play(discord.FFmpegPCMAudio(f'voice\\{audio}'))
                 except discord.errors.ClientException:
                     functions.log(f'{member.nick if member.nick else member} не получит кик с канала.', 'y')
                 voice_client.source = discord.PCMVolumeTransformer(voice_client.source)
                 voice_client.source.volume = 0.50
                 DURATION = functions.get_duration(f'voice\\{audio}')
                 await asyncio.sleep(DURATION)
                 await member.move_to(None)
Example #6
0
async def dbpurge(ctx):
    channel = ctx.message.channel
    roles = ''
    for role in ctx.message.author.roles:
        roles += str(role)
    roles = roles.lower()
    if ('креатор' not in roles):
        async with channel.typing():
            if not (ctx.message.content.lower().startswith('as')):
                await channel.send('**ДА КАК ТЫ ПОСМЕЛ, СМЕРТНЫЙ?!**')
            else:
                await channel.send('**HOW DARE YOU?!**')
        return
    else:
        variables.db.purge()
        variables.tags.purge()
        functions.log('Базы данных были очищены!', 'y')
Example #7
0
def init_server_connection():
    # create socket for connection
    try:
        server = socket.socket()
    except socket.error as e:
        log(e)
        sys.exit(-1)

    # assign port that is not in use
    while True:
        port = random.randint(0, 65535)
        try:
            server.bind(('', port))
            break
        except socket.error as e:
            continue
    return server, port
Example #8
0
    async def on_message(self, message):

        channel = message.channel
        author = str(message.author)
        cantent = str(message.content)

        #if (str(message.author) == "Гошасс#8787" and str(message.content) == "СУЙ" or str(message.author) == "ΤχεΑμμιΡ#6109"and message.content == "СУЙ"):
        if (str(message.content) == "СУЙ"):
            if (author[len(author) - 4:len(author)] in ["8787", "6109"]):
                async with channel.typing():
                    await channel.send(file=discord.File('a1.jpg'))
        elif (cantent.lower().startswith(
            ('ъуъ', 'ъyъ', 'ъγъ', 'iyi', 'iуi', 'iγi'))
              or cantent.lower().endswith(
                  ('ъуъ', 'ъyъ', 'ъγъ', 'iyi', 'iуi', 'iγi'))):
            await channel.send(file=discord.File('a2.jpg'))

        elif (str(message.content) in ["цвет пакажы", 'gimmie the color']):
            while (1 == 1):
                await message.author.roles[len(message.author.roles) - 1].edit(
                    colour=discord.Colour.from_rgb(randomorg.integer(0, 255),
                                                   randomorg.integer(0, 255),
                                                   randomorg.integer(0, 255)),
                    reason=None)
                await asyncio.sleep(5)

        elif (message.content.startswith(';')):
            cantent = cantent[1:]

            async def evaluate(ctn, _message=message):
                _bot = self.bot
                return eval(ctn)

            try:
                await channel.send(await evaluate(cantent))
            except Exception as e:
                functions.log(e, 'r', 'EVL')
        elif (message.content
              in ('<@!672115782439927840>', '<@!670692900593598530>')):
            ctx = await self.bot.get_context(message)
            await ctx.send('**Есть, сэр!**')
            if (message.author != self.bot.get_user(343001477133893632)):
                helpcog = self.bot.get_cog('HelpCommandCog')
                await helpcog.help(ctx)
Example #9
0
async def on_ready():
    channel = bot.get_channel(693112638275584260)
    message = await channel.fetch_message(693112703492816898)
    ctx = await bot.get_context(message)

    await bot.change_presence(activity=discord.Game(name='"асхелп"/"ashelp"'))

    guild = bot.get_guild(671432722236964884)

    def changecolor(id, guild=guild):
        role = guild.get_role(id)
        colour = discord.Colour.from_rgb(randomorg.integer(0, 255),
                                         randomorg.integer(0, 255),
                                         randomorg.integer(0, 255))
        return role.edit(colour=colour)

    await changecolor(673966918281199616)
    await changecolor(685813138301780027)
    await changecolor(676388955985412116)
    await changecolor(676389164727402517)
    functions.log('Цвета ролей обновлены.')

    print()
    sum = 0
    for i in os.listdir():
        if ('.' not in i):
            if (i not in ['Procfile', 'utils', 'LICENSE']):
                bot.load_extension(f'{i}.src.{i}')
                length = functions.get_length(f"{i}/src/{i}.py")
                functions.log(f'({length} lines) {i} был загружен.', 'm',
                              'COG')
                sum += length
    sum += functions.get_length('main.py')
    for i in os.listdir('utils'):
        sum += functions.get_length(f'utils/{i}')
    bot.unload_extension('voice.src.voice')

    functions.log(f'Всего строк: {sum}.', 'm', 'LEN')
    print()

    await recover(ctx=ctx)
    functions.log('Базы данных восстановлены.')

    functions.log('Бот готов к работе.')
Example #10
0
def main():
    # create socket for connection
    server, port = init_server_connection()
    log(f'Server is running on port {port}')

    # listen for incoming connections
    server.listen(50)  # Accepts up to 50 connections.

    # start database
    db = DB(constants.db_name)

    while True:
        # accept connection
        conn, address = server.accept()

        # get client listening port
        port = conn.recv(1024).decode()
        conn.send('LISTEN PORT received'.encode())

        # run thread to handle connection
        _thread.start_new_thread(ThreadConnection.client_connection,
                                 (db, conn, address[0], address[1], port))
Example #11
0
def listen_to_other_clients(server, port):
    log(port)
    log(f'Wait for connections on port {port}')

    # wait for connection from another clients that want to download file
    while True:
        conn, address = server.accept()
        log(f'Accept connection from {address[0]}:{address[1]}')
        data = json.loads(conn.recv(4096).decode())
        path = join(data['folder'], data['filename'])

        # to be sure that file exists
        if os.path.exists(path):
            file = open(path, 'rb')
            conn.send(file.read())
        else:
            conn.send('No such file'.encode())

        conn.close()
Example #12
0
        'АС',
        'аС',
        'ass',
        'Ass',
        'ASS',
        'aSS',
        'asS',
        'as',
        'As',
        'aS',
        'AS',
    ]


bot = commands.Bot(command_prefix=get_pre, case_insensitive=True)
functions.log('Обьект бота инициализирован.')

bot.remove_command('help')
functions.reset(variables.db)


@bot.event
async def on_ready():
    channel = bot.get_channel(693112638275584260)
    message = await channel.fetch_message(693112703492816898)
    ctx = await bot.get_context(message)

    await bot.change_presence(activity=discord.Game(name='"асхелп"/"ashelp"'))

    guild = bot.get_guild(671432722236964884)
Example #13
0
def main():

    listening_server, listening_port = init_server_connection()
    listening_server.listen(5)

    _thread.start_new_thread(listen_to_other_clients,
                             (listening_server, listening_port))

    s = socket.socket()

    # Define the port on which you want to connect
    server_host = constants.host
    server_port = constants.port

    # connect to the server on local computer
    s.connect((server_host, server_port))

    # send port on which client will listen other clients
    s.send(str(listening_port).encode())
    s.recv(1024)

    while True:
        # get action from user
        action = input(
            '1) Get list\n2) Share folder\n3) Download file\n4) Exit\n')
        if action.lower() in ['1', 'get']:
            # send action
            s.send(f'GET'.encode())

            # receive list of files
            buffer = ''
            while '\0' not in buffer:
                buffer += s.recv(4096).decode()
            files = json.loads(buffer[0:buffer.index('\0')])['files']

            # display in cli
            print()
            for i, file in enumerate(files):
                log(f'{i + 1}. name: {file[0]}, size: {convert_size(int(file[1]))}'
                    )
            print()

        elif action.lower() in ['2', 'share']:
            # make sure path exists
            while True:
                path = input('Please enter absolute path of sharing folder\n')
                if os.path.exists(path):
                    break

            # send command
            s.send(f'SHARE'.encode())
            s.recv(1024).decode()

            # send path to store
            s.send(f'{path}'.encode())
            s.recv(1024).decode()

            # get all files in directory and store in list
            files = []
            for f in listdir(path):
                if isfile(join(path, f)):
                    files.append([f, os.path.getsize(join(path, f))])
            data = {'files': files}

            # send array through socket to server
            s.send(f'{json.dumps(data)}\0'.encode())
            log(s.recv(1024).decode())

        elif action.lower() in ['3', 'download']:
            # get filename
            filename = input('Please enter filename\n')

            # send command
            s.send(f'DOWNLOAD'.encode())
            s.recv(1024)

            # send filename
            s.send(f'{filename}'.encode())

            # get info about client that has given file
            user = json.loads(s.recv(4096).decode())

            # initiate another client socket to download file
            file_socket = socket.socket()
            file_socket.connect((user['host'], int(user['port'])))

            # send to filename to client that has given file
            data = {'filename': filename, 'folder': user['folder']}
            file_socket.send(json.dumps(data).encode())

            # initiate progress bar
            buffer_size = 1024
            progress = tqdm(range(int(user['size'])),
                            f'Receiving {filename}',
                            unit='B',
                            unit_scale=True,
                            unit_divisor=buffer_size)

            # create folder that will store file
            if not os.path.exists('./Downloads'):
                os.mkdir('./Downloads')

            # start download
            with open(f'./Downloads/{filename}', 'wb') as file:
                while True:
                    # read 1024 bytes from the socket (receive)
                    bytes_read = file_socket.recv(buffer_size)
                    if not bytes_read:
                        # nothing is received
                        # file transmitting is done
                        break
                    # write to the file the bytes we just received
                    file.write(bytes_read)

                    # update progress bar
                    progress.update(len(bytes_read))

            # after download, close connection
            file_socket.close()

        elif action.lower() in ['4', 'exit']:
            break
    s.close()