Advertisement
Guest User

Untitled

a guest
Apr 19th, 2023
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. # pipedream add-package google-cloud-storage
  2.  
  3. from google.cloud import storage
  4. import json
  5. from google.oauth2 import service_account
  6. import os
  7. import time
  8.  
  9.  
  10. def get_poll_blob(blob_name):
  11. json_acct_info = json.loads(os.environ['creds'])
  12. credentials = service_account.Credentials.from_service_account_info(
  13. json_acct_info)
  14. storage_client = storage.Client(credentials=credentials)
  15. bucket_name = 'poll_updates'
  16. bucket = storage_client.bucket(bucket_name)
  17. blob = bucket.blob(blob_name)
  18. return blob
  19.  
  20. def get_name(user):
  21. if 'username' in user:
  22. return user['username']
  23. return user.get('first_name', '') + ' ' + user.get('last_name', '')
  24.  
  25. def get_poll_answer(event):
  26. print(event)
  27. pa = event['poll_answer']
  28. print(pa['option_ids'])
  29. vote = {
  30. 'id': pa['user']['id'],
  31. 'user': get_name(pa['user']),
  32. 'vote': '-1' if not pa['option_ids'] else ",".join(map(lambda v: str(v), pa['option_ids'])),
  33. 'update_id': event['update_id'],
  34. }
  35. print('vote=', vote)
  36. return pa['poll_id'], vote
  37.  
  38. def append_new_vote(blob, vote):
  39. contents = blob.download_as_string().decode('utf-8') if blob.exists() else '{}'
  40. cd = json.loads(contents)
  41. print(cd)
  42. old_vote = cd.get(str(vote['id']))
  43. print('old_vote=', vote['id'], old_vote)
  44. if not old_vote or old_vote['update_id'] <= vote['update_id']:
  45. cd[vote['id']] = vote
  46. blob.upload_from_string(json.dumps(cd))
  47. return cd
  48.  
  49. def handlerExcept(pd: "pipedream"):
  50. poll, user_vote = get_poll_answer(pd.steps['trigger']['event'])
  51. blob = get_poll_blob(poll)
  52. contents = append_new_vote(blob, user_vote)
  53. return {"contents": contents}
  54.  
  55. def handler(pd: "pipedream"):
  56. for i in range(10):
  57. try:
  58. handlerExcept(pd)
  59. return
  60. except Exception as e:
  61. print(e)
  62. time.sleep(15)
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement