Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. ## Usage
  2. ## sp = SlackPost(token=app_token, channel='#random')
  3. ## await sp.post_update("Look at this cool graph", ['img1.png', 'img2.png'])
  4. ## await sp.post_update("The data has changed!", ['img3.png', 'img4.png'])
  5.  
  6. class SlackPost():
  7. def __init__(self, token, channel):
  8. self.channel = channel
  9. self.client = client = slack.WebClient(
  10. token=token,
  11. run_async=True
  12. )
  13. self.ts = None
  14.  
  15.  
  16. async def post_update(self, message, fnames = []):
  17. attachments=[
  18. {
  19. 'fallback': 'graph',
  20. 'image_url': await self.upload_image(f)
  21. } for f in fnames
  22. ]
  23.  
  24. await self.send_message(
  25. channel=self.channel,
  26. text=message,
  27. attachments=attachments
  28. )
  29.  
  30. async def send_message(self, **kwargs):
  31. if self.ts:
  32. await (self.client.chat_update(ts=self.ts, **kwargs))
  33. else:
  34. response = await (self.client.chat_postMessage(**kwargs))
  35. self.ts = response.data['ts']
  36. self.channel = response.data['channel']
  37.  
  38. async def upload_image(self, fname):
  39. img_response = await self.client.files_upload(
  40. file=fname,
  41. title="image"
  42. )
  43.  
  44. file_response = await self.client.files_sharedPublicURL(
  45. file=img_response.data['file']['id'],
  46. )
  47.  
  48. return file_response.data['file']['permalink_public']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement