How to download programmatically a module?
Normally you want to use drush, e.g.

drush -y en module_name


which would download, install and enable your module of interest.

Check drush.api.php to use appropriate API hooks which could be useful.

If you don't want to use Drush, check how Update Manager does that in update/update.manager.inc, e.g.


update_manager_file_get
update_manager_archive_extract
etc.


To get the list of available files to download for specific project you've to fetch and parse the release history which is available at:

https://updates.drupal.org/release-history/project_name/7.x


the same as drush does that (check by drush -vd dl foo) and get the links from there.