forked from rssnyder/discord-stock-ticker
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
412 lines (315 loc) · 14.4 KB
/
main.py
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
'''discord-stock-ticker'''
from os import getenv
import logging
import asyncio
import discord
from redis import Redis, exceptions
from utils.yahoo import get_stock_price
from utils.coin_gecko import get_crypto_price
CURRENCY = 'usd'
NAME_CHANGE_DELAY = 3600
class Ticker(discord.Client):
'''
Discord client for watching stock/crypto prices
'''
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
ticker = getenv("TICKER")
crypto_name = getenv('CRYPTO_NAME')
stock_name = getenv("STOCK_NAME", ticker)
# Check that at least a ticker is set
if not ticker:
logging.error('TICKER not set!')
return
# Use different updates based on security type
if crypto_name:
logging.info('crypo ticker')
if not getenv('SET_NICKNAME'):
self.sm_task = self.loop.create_task(
self.crypto_update_name(
ticker.upper(),
crypto_name
)
)
self.bg_task = self.loop.create_task(
self.crypto_update_activity(
ticker.upper(),
crypto_name,
getenv('SET_NICKNAME'),
getenv('SET_COLOR'),
getenv('FLASH_CHANGE'),
getenv('FREQUENCY', 60)
)
)
else:
logging.info('stock ticker')
if not getenv('SET_NICKNAME'):
self.sm_task = self.loop.create_task(
self.stock_update_name(
ticker.upper(),
stock_name.upper()
)
)
self.bg_task = self.loop.create_task(
self.stock_update_activity(
ticker.upper(),
stock_name.upper(),
getenv('SET_NICKNAME'),
getenv('SET_COLOR'),
getenv('FLASH_CHANGE'),
getenv('FREQUENCY', 60)
)
)
async def on_ready(self):
'''
Log that we have successfully connected
'''
logging.info('logged in')
# We want to know some stats
servers = [x.name for x in list(self.guilds)]
redis_server = getenv('REDIS_URL')
if redis_server:
# Use redis to store stats
r = Redis(host=redis_server, port=6379, db=0)
try:
for server in servers:
r.incr(server)
except exceptions.ConnectionError:
logging.info('No redis server found, not storing stats')
logging.info('servers: ' + str(servers))
async def stock_update_name(self, ticker: str, name: str):
'''
Update the bot name based on stock price
ticker = stock symbol
name = override for symbol as shown on bot
'''
await self.wait_until_ready()
logging.info(f'stock name update ready: {name}')
# Loop as long as the bot is running
while not self.is_closed():
logging.info('stock name update started')
# Grab the current price data
data = get_stock_price(ticker)
price_data = data.get('quoteSummary', {}).get('result', []).pop().get('price', {})
price = price_data.get('regularMarketPrice', {}).get('raw', 0.00)
logging.info(f'stock name price retrived {price}')
try:
await self.user.edit(
username=f'{name} - ${price}'
)
logging.info('name updated')
except discord.HTTPException as e:
logging.warning(f'updating name failed: {e.status}: {e.text}')
# Only update every hour
logging.info(f'stock name sleeping for {NAME_CHANGE_DELAY}s')
await asyncio.sleep(NAME_CHANGE_DELAY)
logging.info('stock name sleep ended')
async def stock_update_activity(self, ticker: str, name: str, change_nick: bool = False, change_color: bool = False, flash_change: bool = False, frequency: int = 60):
'''
Update the bot activity based on stock price
ticker = stock symbol
name = override for symbol as shown on bot
change_nick = flag for changing nickname
frequency = how often to update in seconds
'''
old_price = 0.0
change_up = True
await self.wait_until_ready()
logging.info(f'stock activity update ready: {name}')
# Loop as long as the bot is running
while not self.is_closed():
logging.info('stock activity update started')
# Grab the current price data w/ day difference
data = get_stock_price(ticker)
price_data = data.get('quoteSummary', {}).get('result', []).pop().get('price', {})
price = price_data.get('regularMarketPrice', {}).get('raw', 0.00)
# If after hours, get change
if price_data.get('postMarketChange'):
# Get difference or new price
if getenv('POST_MARKET_PRICE'):
post_market_target = 'postMarketPrice'
else:
post_market_target = 'postMarketChange'
raw_diff = price_data.get(post_market_target, {}).get('raw', 0.00)
diff = round(raw_diff, 2)
if not getenv('POST_MARKET_PRICE'):
if diff >= 0.0:
change_up = True
diff = '+' + str(diff)
else:
change_up = False
activity_content = f'After Hours: {diff}'
logging.info(f'{name} stock activity after hours price retrived: {activity_content}')
else:
raw_diff = price_data.get('regularMarketChange', {}).get('raw', 0.00)
diff = round(raw_diff, 2)
if diff >= 0.0:
diff = '+' + str(diff)
else:
change_up = False
activity_content = f'${price} / {diff}'
logging.info(f'{name} stock activity price retrived: {activity_content}')
# Change name via nickname if set
if change_nick:
for server in self.guilds:
green = discord.utils.get(server.roles, name="tickers-green")
red = discord.utils.get(server.roles, name="tickers-red")
try:
await server.me.edit(
nick=f'{name} - ${price}'
)
if change_color:
if flash_change:
# Flash price change
if price >= old_price:
await server.me.add_roles(green)
await server.me.remove_roles(red)
else:
await server.me.add_roles(red)
await server.me.remove_roles(green)
# Stay on day change
if change_up:
await server.me.add_roles(green)
await server.me.remove_roles(red)
else:
await server.me.add_roles(red)
await server.me.remove_roles(green)
except discord.HTTPException as e:
logging.error(f'updating nick failed: {e.status}: {e.text}')
except discord.Forbidden as f:
logging.error(f'lacking perms for chaning nick: {f.status}: {f.text}')
logging.info(f'{name} stock updated nick in {server.name}')
# Check what price we are displaying
if price_data.get('postMarketChange'):
activity_content_header = 'After Hours'
else:
activity_content_header = 'Day Diff'
activity_content = f'{activity_content_header}: {diff}'
# Change activity
try:
await self.change_presence(
activity=discord.Activity(
type=discord.ActivityType.watching,
name=activity_content
)
)
logging.info('activity updated')
except discord.InvalidArgument as e:
logging.error(f'updating activity failed: {e.status}: {e.text}')
old_price = price
# Only update every min
logging.info(f'stock activity sleeping for {frequency}s')
await asyncio.sleep(int(frequency))
logging.info('stock activity sleep ended')
async def crypto_update_name(self, ticker: str, crypto_name: str):
'''
Update the bot name based on crypto price
ticker = symbol to display on bot
name = crypto name for CG api
'''
await self.wait_until_ready()
logging.info(f'crypto name update ready: {crypto_name}')
# Loop as long as the bot is running
while not self.is_closed():
logging.info('crypto name started')
# Grab the current price data
data = get_crypto_price(crypto_name)
price = data.get('market_data', {}).get('current_price', {}).get(CURRENCY, 0.0)
logging.info(f'crypto name price retrived {price}')
try:
await self.user.edit(
username=f'{ticker} - ${price}'
)
logging.info('crypto name updated')
except discord.HTTPException as e:
logging.warning(f'updating name failed: {e.status}: {e.text}')
# Only update every hour
logging.info(f'crypto name sleeping for {NAME_CHANGE_DELAY}s')
await asyncio.sleep(NAME_CHANGE_DELAY)
logging.info('crypto name sleep ended')
async def crypto_update_activity(self, ticker: str, crypto_name: str, change_nick: bool = False, change_color: bool = False, flash_change: bool = False, frequency: int = 60):
'''
Update the bot activity based on crypto price
ticker = symbol to display on bot
name = crypto name for CG api
change_nick = flag for changing nickname
frequency = how often to update in seconds
'''
old_price = 0.00
change_up = True
await self.wait_until_ready()
logging.info(f'crypto activity update ready: {crypto_name}')
# Loop as long as the bot is running
while not self.is_closed():
logging.info('crypto activity started')
# Grab the current price data
data = get_crypto_price(crypto_name)
price = data.get('market_data', {}).get('current_price', {}).get(CURRENCY, 0.0)
change = data.get('market_data', {}).get('price_change_24h', 0)
change_header = ''
if change >= 0.0:
change_header = '+'
else:
change_up = False
logging.info(f'crypto activity price retrived {price}')
activity_content = f'${price} / {change_header}{change}'
# Change name via nickname if set
if change_nick:
for server in self.guilds:
green = discord.utils.get(server.roles, name="tickers-green")
red = discord.utils.get(server.roles, name="tickers-red")
try:
await server.me.edit(
nick=f'{ticker} - ${price}'
)
if change_color:
if flash_change:
# Flash price change
if price >= old_price:
await server.me.add_roles(green)
await server.me.remove_roles(red)
else:
await server.me.add_roles(red)
await server.me.remove_roles(green)
# Stay on day change
if change_up:
await server.me.add_roles(green)
await server.me.remove_roles(red)
else:
await server.me.add_roles(red)
await server.me.remove_roles(green)
except discord.HTTPException as e:
logging.error(f'updating nick failed: {e.status}: {e.text}')
except discord.Forbidden as f:
logging.error(f'lacking perms for chaning nick: {f.status}: {f.text}')
logging.info(f'{crypto_name} updated nick in {server.name}')
# Use activity for other fun stuff
activity_content = f'24hr Diff: {change_header}{change}'
# Change activity
try:
await self.change_presence(
activity=discord.Activity(
type=discord.ActivityType.watching,
name=activity_content
)
)
old_price = price
logging.info(f'{crypto_name} crypto activity updated {activity_content}')
except discord.InvalidArgument as e:
logging.error(f'updating activity failed: {e.status}: {e.text}')
# Only update every min
logging.info(f'crypto sleeping for {frequency}s')
await asyncio.sleep(int(frequency))
logging.info('crypto activity sleep ended')
if __name__ == "__main__":
logging.basicConfig(
filename=getenv('LOG_FILE'),
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S',
format='%(asctime)s %(levelname)-8s %(message)s',
)
token = getenv('DISCORD_BOT_TOKEN')
if not token:
print('DISCORD_BOT_TOKEN not set!')
client = Ticker()
client.run(token)