Skip to content

Instantly share code, notes, and snippets.

@jamesr2323
Last active August 8, 2019 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesr2323/836899ea47f1fa0de7162a09e16410ca to your computer and use it in GitHub Desktop.
Save jamesr2323/836899ea47f1fa0de7162a09e16410ca to your computer and use it in GitHub Desktop.
Post experiment results, images etc. to Slack in an updating message
## Usage
## sp = SlackPost(token=app_token, channel='#random')
## await sp.post_update("Look at this cool graph", ['img1.png', 'img2.png'])
## await sp.post_update("The data has changed!", ['img3.png', 'img4.png'])
class SlackPost():
def __init__(self, token, channel):
self.channel = channel
self.client = client = slack.WebClient(
token=token,
run_async=True
)
self.ts = None
async def post_update(self, message, fnames = []):
attachments=[
{
'fallback': 'graph',
'image_url': await self.upload_image(f)
} for f in fnames
]
await self.send_message(
channel=self.channel,
text=message,
attachments=attachments
)
async def send_message(self, **kwargs):
if self.ts:
await (self.client.chat_update(ts=self.ts, **kwargs))
else:
response = await (self.client.chat_postMessage(**kwargs))
self.ts = response.data['ts']
self.channel = response.data['channel']
async def upload_image(self, fname):
img_response = await self.client.files_upload(
file=fname,
title="image"
)
file_response = await self.client.files_sharedPublicURL(
file=img_response.data['file']['id'],
)
return file_response.data['file']['permalink_public']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment