-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbot.py
More file actions
176 lines (161 loc) · 6.53 KB
/
bot.py
File metadata and controls
176 lines (161 loc) · 6.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/env python
'''
Slack bot to query price/details of a stock symbol
Author: Omar Busto Santos
Date created: 02/13/2021
'''
import os
import logging
import re
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from slackeventsapi import SlackEventAdapter
from flask import Flask
import stock
# Initialize a Flask app to host the events adapter
app = Flask(__name__)
slack_events_adapter = SlackEventAdapter(os.environ['SLACK_SIGNING_SECRET'], "/slack/events", app)
# Initialize a Web API client
client = WebClient(token=os.environ['SLACK_BOT_TOKEN'])
# Timestamp of the latest message processed
# NOTE: Mainly for heroku since the service dies after 1h on the free tier and when waking up it sometimes it gets older messages
last_processed = 0
def check_processed(ts):
"""Checks if a timestamp of a message is newer than the last processed"""
global last_processed
if ts > last_processed:
last_processed = ts
return True
return False
def get_message_payload(channel_id, msg):
"""Gets the message payload to be sent in the post message api"""
return {
"ts": "",
"channel": channel_id,
"username": "Market Bot",
"attachments": [
msg
]
}
def sanitize_message(msg):
"""Sanitizes the message removing possible http link formating"""
http_prefix = "$<http://"
words = msg.split()
for i, word in enumerate(words):
if word.startswith(http_prefix):
index = word.find("|")
words[i] = "$" + word[len(http_prefix):index]
return " ".join(words)
def format_message(format, state, quoteType):
"""Modifies the formatting for the slack message based on the market state and thee quote type"""
# Override color, emojis and some text if we are in pre/post market
if quoteType == stock.QUOTE_TYPE_ETF or quoteType == stock.QUOTE_TYPE_INDEX or quoteType == stock.QUOTE_TYPE_CRYPTO:
format['current_text'] = "Market price"
format['previous_text'] = "Previous close price"
if state != stock.MARKET_STATE_REG:
format['color'] = "#777777"
format['indicator'] = ":sleeping:"
else:
if state == stock.MARKET_STATE_PRE:
format['color'] = "#FFFF00"
format['indicator'] = ":hatching_chick:"
format['current_text'] = "Pre-Market price"
format['previous_text'] = "Market close price"
elif state == stock.MARKET_STATE_POST:
format['color'] = "#777777"
format['indicator'] = ":new_moon_with_face:"
format['current_text'] = "After Hours price"
format['previous_text'] = "Market close price"
elif state == stock.MARKET_STATE_NIGHT or state == stock.MARKET_STATE_CLOSED:
format['color'] = "#777777"
format['indicator'] = ":sleeping:"
format['current_text'] = "After Hours close price"
format['previous_text'] = "Market close price"
else:
format['current_text'] = "Market price"
format['previous_text'] = "Previous close price"
def send_price_msg(channel_id, details):
"""Sends price message to the channel"""
format = {}
if details['price']['change'].startswith('-'):
format['trend'] = ":chart_with_downwards_trend:"
format['indicator'] = ":red_circle:"
format['color'] = "#FF0000"
details['price']['change'] = details['price']['change'].replace("-", "-$")
else:
format['trend'] = ":chart_with_upwards_trend:"
format['indicator'] = ":large_green_circle:"
format['color'] = "#00FF00"
details['price']['change'] = "+$" + details['price']['change']
format_message(format, details['state'], details['quoteType'])
msg = {
"color": format['color'],
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "{0} ({1}) {2}".format(details['name'], details['symbol'].upper(), format['indicator']),
"emoji": True
}
},
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*{0}:*".format(format['current_text'])
},
{
"type": "plain_text",
"text": "${0}".format(details['price']['current'])
},
{
"type": "mrkdwn",
"text": "*{0}:*".format(format['previous_text'])
},
{
"type": "plain_text",
"text": "${0}".format(details['price']['previous'])
},
{
"type": "mrkdwn",
"text": "*Change:*"
},
{
"type": "plain_text",
"text": "{0} ({1}) {2}".format(details['price']['change'], details['price']['percent'], format['trend'])
}
]
},
{
"type": "context",
"elements": [
{
"type": "mrkdwn",
"text": "More information <https://finance.yahoo.com/quote/{0}|here>".format(details['symbol'])
}
]
}
]
}
payload = get_message_payload(channel_id, msg)
client.chat_postMessage(**payload)
@slack_events_adapter.on("message")
def message(payload):
"""Parse channel messages looking for stock symbols"""
event = payload.get("event", {})
text = sanitize_message(event.get("text"))
channel_id = event.get("channel")
ts = payload.get("event_time")
if check_processed(ts) and text:
symbols = re.findall(r'\$\^?\b[a-zA-Z.-]+\b', text)
for symbol in symbols:
details = stock.query_symbol_details(symbol[1:])
send_price_msg(channel_id, details)
if __name__ == "__main__":
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)