Skip to content

Instantly share code, notes, and snippets.

Last active November 12, 2019 08:40
What would you like to do?
Post Nifty movers to Mastodon
"""A Mastodon bot that collects the Nifty data and creates a post"""
import json
import urllib.request
import urllib.parse
import os
from datetime import datetime
def build_request(url):
"""Builds a request with appropriate headers for NSE"""
headers = {
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.5',
'Host': '',
'Referer': "\
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0',
'X-Requested-With': 'XMLHttpRequest'
request = urllib.request.Request(url, {}, headers)
return request
def toot(message):
host_instance = os.getenv("HOST_INSTANCE")
if not host_instance:
return {"status": "error", "message": "Access Token Not Available"}
token = os.getenv("ACCESS_TOKEN")
if not token:
return {"status": "error", "message": "Access Token Not Available"}
headers = {
"Authorization": f"Bearer {token}"
data = {
"status": message,
"visibility": "public"
request = urllib.request.Request(
with urllib.request.urlopen(request) as res:
toot_status = json.loads(
return toot_status
def lambda_handler(event, context):
# Let us load the JSONs
index_url = ""
gainers_url = ""
losers_url = ""
with urllib.request.urlopen(build_request(index_url)) as response:
index = json.loads(
date_string = index["time"]
file_date = datetime.strptime(date_string, "%b %d, %Y").date()
today =
if file_date != today:
return {"status": "skipped", "message": "Market data is not from today"}
with urllib.request.urlopen(build_request(gainers_url)) as response:
gainers = json.loads(
with urllib.request.urlopen(build_request(losers_url)) as response:
losers = json.loads(
lines = ['#Nifty Closing Report']
for entry in index["data"]:
if entry["name"] == "NIFTY 50":
lines.append(f"NIFTY 50\nIndex: {entry['lastPrice']} Change: {entry['change']} {entry['pChange']}%")
lines.append("\n⬆️ Gainers")
for scrip in gainers["data"]:
lines.append(f"{scrip['symbol']} {scrip['netPrice']}%")
lines.append("\n⬇️ Losers")
for scrip in losers["data"]:
lines.append(f"{scrip['symbol']} {scrip['netPrice']}%")
return toot("\n".join(lines))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment