Advertisement
Guest User

Untitled

a guest
Jul 13th, 2017
582
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.40 KB | None | 0 0
  1. import json
  2. from snapp_email import ApiClient
  3. from snapp_email.datacontract import classes
  4. import examples.config as config
  5. import datetime
  6. import examples.create_post as create_post
  7. import requests
  8. import schedule
  9. import time
  10.  
  11. integration_key = "36f8055c-173a-4d3a-a7af-88c5c0a4b3c1@4thoffice.com"
  12. integration_secret = "1f031a3d-9b95-d738-fbc7-1ab7125a9dc4"
  13.  
  14. mylist=["Trip","Travel","trip","travel","flight","Flight","vacation","Vacation","tour","Tour","Outing"
  15. ,"outing","weekend","Weekend","expedition","Expedition","roundabout","Roundabout","break","Break","Layoff","Rest"
  16. ,"layoff","rest","lay off","Lay off","leisure","Leisure","day off","Day off","arrival", "Arrival","Departure","Ride","Swing","Cruise"
  17. ,"departure","ride", "swing","cruise","holiday","Holiday"]
  18.  
  19. #,"izak1996@gmail.com",
  20. #"luka.todorovic.boznar@gmail.com"
  21. #"masa.petan@gmail.com",
  22. #"vehovecnina@gmail.com"
  23. email_addresses=["luka.todorovic.boznar@gmail.com"]
  24. api_client = ApiClient(integration_key, integration_secret, 7, client_codename="THE 1st Of 4O", api_url="https://clean-sprint-app.4thoffice.com/api")
  25.  
  26.  
  27. def get_agenda_sdk(api_client,start_datetime, end_datetime=None, size=100, offset=0, impersonate_user_id=None):
  28.     agenda = api_client.appointment.ListOfAgendaPage_22.get(None, start_datetime, size, offset, end_datetime, impersonate_user_id)
  29.     return agenda
  30.  
  31.  
  32. def user_id_for_email_sdk(email_address):
  33.     api_client = ApiClient(username=config.INTEGRATION_KEY,
  34.                            password=config.INTEGRATION_SECRET,
  35.                            auth_type=7,
  36.                            api_url=config.API_URL)
  37.  
  38.     user = create_post.create_user_object_from_email(email_address)
  39.     stream_user = classes.StreamUser_22(User=user)
  40.  
  41.     response = api_client.stream.StreamUser_22.create(stream_user)
  42.     return response.User.Id
  43.  
  44. def create_card_html_sdk(api_client, to_user_email, title, content, attachment_names_ids=None):
  45.  
  46.     share_list = []
  47.     share_list.append(create_post.create_user_object_from_email(to_user_email))
  48.     share_list = classes.ListOfResources_13(share_list)
  49.  
  50.     post_obj = classes.Post_22(BodyHtml=content, ShareList=share_list)
  51.     if attachment_names_ids:
  52.         files = []
  53.         for attachment_id in attachment_names_ids:
  54.             file = classes.File_14()
  55.             file.set_Id(attachment_id)
  56.             files.append(file)
  57.         post_obj.set_Files(classes.ListOfFiles_14(files))
  58.     post_obj.set_Name(title)
  59.     created_post = api_client.post.Post_22.create(post_obj)
  60.  
  61.     return created_post
  62.  
  63.  
  64. def exists(path):
  65.     r = requests.head(path)
  66.     return r.status_code == requests.codes.ok
  67.  
  68.  
  69. def get_accommodation_email_string(location, json):
  70.     text = '''<span style="font-weight: bold; font-size: 18px;">Hi there!</span><br>
  71.           <span>Seems like you are planning a trip to ''' + location + '''</span><br><br>
  72.           <span>Here is a super easy way to focus on your work instead of spending lots of time searching for the right accommodation.</span><br><br>
  73.           <span>In the description below are 3 hotels, based on the ratings from previous guests.
  74.           I think one of them will definitely suit your needs, so check them out. ;)</span>
  75.           <table style="width: 100%; margin-bottom: 20px;" cellspacing="10">
  76.               <tr>
  77.           '''
  78.  
  79.     for i in range(3):
  80.         j = 0
  81.         for j in range(len(json['results'][i]['images'])):
  82.             if exists(json['results'][i]['images'][j]['source_url']):
  83.                 img_url = json['results'][i]['images'][j]['source_url']
  84.                 break
  85.             elif j == len(json['results'][i]['images']) - 1:
  86.                 img_url = 'http://drkeyurparmar.com/wp-content/uploads/2015/02/dummy-article-img.jpg'
  87.  
  88.         if len(json['results'][i]['images']) == 0:
  89.             img_url = 'http://drkeyurparmar.com/wp-content/uploads/2015/02/dummy-article-img.jpg'
  90.  
  91.         text += '''
  92.           <td style="width: 33.33%; height: 100px; margin: 20px; text-align: center; padding: 5px; vertical-align: top;">
  93.               <h4>{}</h4>
  94.               <img src="{}" style="max-width: 100%;">
  95.               <span>{}</span>
  96.               <a href="{}" style="margin-top: 10px; display: block;">Read more...</a>
  97.           </td>
  98.           '''.format(json['results'][i]['name'], img_url,
  99.                       json['results'][i]['snippet'], json['results'][i]['booking_info']['vendor_object_url'])
  100.  
  101.     text += '''</tr></table>
  102.           <span>I hope that these recommendations were of help and that you managed to find your perfect stay.</span><br><br>
  103.  
  104.           <span>Have a great time in ''' + location + '''!</span><br>
  105.           4th Office - your best friend in email management.'''
  106.  
  107.     return text
  108.  
  109.  
  110. def get_sightseeing_email_string(location, json):
  111.     text = '''<span style="font-weight: bold; font-size: 18px;">Hi there!</span><br><br>
  112.           <span>There are a lot of great attractions waiting for you in ''' + location + '''.</span>
  113.  
  114.           <span>In case you find some free time as your schedule is probably filled with work I found 9 great places you should visit.
  115.               They are chosen depending on the rating and recommendations from previous tourists so they should fit your needs.</span>
  116.           <table style="width: 100%; margin-bottom: 20px;" cellspacing="10">
  117.           '''
  118.  
  119.     for i in range(3):
  120.         text += '<tr>'
  121.         for j in range(3):
  122.             k = 0
  123.             for k in range(len(json['results'][i * 3 + j]['images'])):
  124.                 if exists(json['results'][i * 3 + j]['images'][k]['source_url']):
  125.                     img_url = json['results'][i * 3 + j]['images'][k]['source_url']
  126.                     break
  127.                 elif k == len(json['results'][i * 3 + j]['images']) - 1:
  128.                     img_url = 'http://drkeyurparmar.com/wp-content/uploads/2015/02/dummy-article-img.jpg'
  129.  
  130.             if len(json['results'][i * 3 + j]['images']) == 0:
  131.                 img_url = 'http://drkeyurparmar.com/wp-content/uploads/2015/02/dummy-article-img.jpg'
  132.  
  133.             snippet = (json['results'][i * 3 + j]['snippet'][:120] + '...') if len(
  134.                 json['results'][i * 3 + j]['snippet']) > 120 else json['results'][i * 3 + j]['snippet']
  135.             text += '''
  136.           <td style="width: 33.33%;margin: 20px; text-align: center; padding: 5px; vertical-align: top;">
  137.               <h4>{}</h4>
  138.               <img src="{}" style="max-width: 100%;">
  139.               <span>{}</span>
  140.               <a href="{}" style="margin-top: 10px; display: block;">Read more...</a>
  141.           </td>
  142.           '''.format(json['results'][i * 3 + j]['name'], img_url,
  143.                       snippet, json['results'][i * 3 + j]['attribution'][0]['url'])
  144.  
  145.         text += '</tr>'
  146.  
  147.     text += '''</table><span>Hope you like them!</span><br>
  148.           4th Office - your best friend in email management.'''
  149.  
  150.     return text
  151.  
  152.  
  153. def get_location_url(lat, long):
  154.     latstr = "{:.6f}".format(lat)
  155.     longstr = "{:.6f}".format(long)
  156.     link_to_location = 'http://maps.google.com/maps?q=loc:' + latstr + ',' + longstr
  157.     return link_to_location
  158.  
  159.  
  160. def get_restaurant_email_string(location, json):
  161.     text = '''<span style="font-weight: bold; font-size: 18px;">Hi there!</span><br><br>
  162.           <span>Your trip to {} is approaching. There are only two days left until exploring that place.</span><br><br>
  163.  
  164.           <span>Here are {} restaurants and cafes, so you won`t go hungry while working abroad.</span><br>
  165.           <ul>'''.format(location, len(json['results']))
  166.  
  167.     for i in range(len(json['results'])):
  168.         text += '<li><a href="' + get_location_url(json['results'][i]['coordinates']['latitude'],
  169.                                                    json['results'][i]['coordinates']['longitude']) + '">' + \
  170.                 json['results'][i]['name'] + '</a></li>\n'
  171.  
  172.     text += '''</ul><br>There is nothing better than a good meal so I hope you like these suggestions! :)<br><br>
  173.   Enjoy local specialities in ''' + location + '''.<br>
  174.   4th Office - your best friend in email management.
  175.   '''
  176.  
  177.     return text
  178.  
  179. def api_information_hotels(location,email):
  180.     title = " Your accommodation for "+location
  181.     category = "hotels"
  182.     r = requests.get('https://www.triposo.com/api/v2/poi.json?location_id=' + location + '&tag_labels=' + category + '&order_by=-score&count=3&fields=name,coordinates,booking_info,snippet,images&account=R7M1ZPHW&token=vm563syh3v72rujab3csnhtfanwl15ak')
  183.     json = r.json()
  184.  
  185.     #link_to_location=
  186.     string= get_accommodation_email_string(location,json)
  187.  
  188.     create_card_html_sdk(api_client, email, title, string)
  189.  
  190. def api_information_sightseeing(location, email):
  191.     title = "Places to visit in " + location
  192.     category = "sightseeing"
  193.  
  194.     r = requests.get(
  195.             'https://www.triposo.com/api/v2/poi.json?location_id=' + location + '&tag_labels=' + category + '&order_by=-sightseeing_score&count=9&fields=name,snippet,coordinates,score,images,attribution&account=R7M1ZPHW&token=vm563syh3v72rujab3csnhtfanwl15ak')
  196.     json = r.json()
  197.  
  198.     string=get_sightseeing_email_string(location,json)
  199.     create_card_html_sdk(api_client, email, title, string)
  200.  
  201. def api_information_restaurants(location, email):
  202.     title = "Where to dine in " + location
  203.     category = "eatingout"
  204.     r = requests.get(
  205.             "https://www.triposo.com/api/v2/poi.json?location_id=" + location + "&tag_labels=" + category + "&order_by=-eatingout_score&count=10&fields=id,name,snippet,coordinates,images&account=R7M1ZPHW&token=vm563syh3v72rujab3csnhtfanwl15ak")
  206.     json = r.json()
  207.     string=get_restaurant_email_string(location,json)
  208.     create_card_html_sdk(api_client, email, title, string)
  209.  
  210.  
  211. def job():
  212.     for k in range(len(email_addresses)):
  213.         print(email_addresses[k])
  214.         agenda = api_client.appointment.ListOfAgendaPage_22.get(None, datetime.datetime.today(), 100, 0,
  215.                                                                 datetime.datetime.today() + datetime.timedelta(30),
  216.                                                                 user_id_for_email_sdk(email_addresses[k]))
  217.  
  218.         for i in range(len(agenda.AgendaList.Resource)):
  219.             todaydate = datetime.datetime.today().strftime("%Y-%m-%d")
  220.             name = agenda.AgendaList.Resource[i].AgendaItem.Parent.Name
  221.             locat = agenda.AgendaList.Resource[i].AgendaItem.Location
  222.  
  223.             if(locat is None):
  224.                 continue
  225.  
  226.             locationtown = locat.split(",")
  227.             loc=locationtown[0].replace(" ", "_")
  228.             if (todaydate in agenda.AgendaList.Resource[i].AgendaItem.Created):
  229.                 for j in range(len(mylist)):
  230.                     if (mylist[j] in name):
  231.                         api_information_hotels(loc,email_addresses[k])
  232.                         print(loc)
  233.  
  234.             date = datetime.datetime.strptime(todaydate, "%Y-%m-%d")
  235.             date_2 = date + datetime.timedelta(days=2)
  236.             if (date_2.strftime("%Y-%m-%d") in agenda.AgendaList.Resource[i].DueDate):
  237.                 for j in range(len(mylist)):
  238.                     if (mylist[j] in name):
  239.  
  240.                         api_information_restaurants(loc,email_addresses[k])
  241.                         api_information_sightseeing(loc, email_addresses[k])
  242.                         print(loc)
  243.  
  244. schedule.every(0.1).minutes.do(job)
  245. #schedule.every().day.at("19:51").do(job)
  246.  
  247. while True:
  248.     schedule.run_pending()
  249.     time.sleep(10)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement