Skip to content

Instantly share code, notes, and snippets.

@minrk
Created January 23, 2018 12:28
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 minrk/b79363d0468b00ee7edb7c089874f998 to your computer and use it in GitHub Desktop.
Save minrk/b79363d0468b00ee7edb7c089874f998 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
Collect gitter messages that start with "!log" and log them in markdown bullet list with dates
"""
from datetime import datetime, timezone, timedelta
import json
import os
import sys
from dateutil.parser import parse as parse_date
import requests_cache
token = os.environ['GITTER_API_TOKEN']
GITTER = "https://api.gitter.im/v1"
DEBUG = 0
def datefmt(dt):
dt = dt.astimezone(timezone.utc)
return dt.strftime("%Y-%m-%d %H:%M (UTC)")
def main(room, limit):
s = requests_cache.CachedSession(expire_after=timedelta(hours=1))
s.trust_env = False
s.headers.update({
"Authorization": f"Bearer {token}",
"Accept": "application/json",
"Content-Type": "application/json",
})
# get room id
r = s.post(f"{GITTER}/rooms", data=json.dumps({'uri': 'jupyterhub/binder'}), allow_redirects=False)
r.raise_for_status()
room_id = r.json()['id']
if DEBUG:
print(f"room id for {room} is {room_id}", file=sys.stderr)
# fetch messages
query = {'limit': 100}
now = datetime.now().astimezone(timezone.utc)
oldest = now
logs = []
# collect logs going back in time
while now - oldest < limit:
r = s.get(f"{GITTER}/rooms/{room_id}/chatMessages", params=query)
r.raise_for_status()
# messages are forward-ordered. We want to step back
messages = r.json()[::-1]
for msg in messages:
text = msg['text'].lstrip()
date = parse_date(msg['sent'])
if not text.startswith('!log'):
continue
# trim !log
text = text.split(None, 1)[1].strip().replace('\n', '\n ')
logs.append(f"- {datefmt(date)} @{msg['fromUser']['username']}: {text}")
oldest = date
query['beforeId'] = msg['id']
if DEBUG:
print(f"collected {len(logs)} log msgs since to {oldest}", file=sys.stderr)
print(f"\nGitter log events since {datefmt(oldest)}:")
for log in logs[::-1]:
print(log)
if __name__ == '__main__':
main("jupyterhub/binder", limit=timedelta(days=7))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment