|
| 1 | +import disnake |
| 2 | +from disnake.ext import tasks |
| 3 | +from requests_html import HTMLSession |
| 4 | + |
| 5 | +import os |
| 6 | +import json |
| 7 | + |
| 8 | +class Scheduler(disnake.Client): |
| 9 | + def __init__(self, *args, **kwargs): |
| 10 | + super().__init__(*args, **kwargs) |
| 11 | + self.last_price = None |
| 12 | + self.interval = os.getenv('INTERVAL') or 15 |
| 13 | + self.short_code = os.getenv('SHORT_CODE') |
| 14 | + |
| 15 | + async def on_ready(self): |
| 16 | + print(f"Logged in as {self.user} (ID: {self.user.id})") |
| 17 | + print(f"SHORT_CODE: {self.short_code}") |
| 18 | + print(f"INTERVAL: {self.interval}") |
| 19 | + print("------") |
| 20 | + |
| 21 | + async def on_connect(self): |
| 22 | + self.fetch_price.start() |
| 23 | + |
| 24 | + @tasks.loop(seconds=int(os.getenv('INTERVAL') or 15)) |
| 25 | + async def fetch_price(self): |
| 26 | + await self.wait_until_ready() |
| 27 | + |
| 28 | + session = HTMLSession() |
| 29 | + r = session.get(f"https://www.ustockplus.com/stock/_-{self.short_code}") |
| 30 | + |
| 31 | + try: |
| 32 | + next_data = r.html.find('#__NEXT_DATA__', first=True).text |
| 33 | + data = json.loads(next_data)['props']['pageProps']['stockDetail'] |
| 34 | + display_name = data['name'] |
| 35 | + |
| 36 | + trade_price = data['prevClosingPrice'] |
| 37 | + |
| 38 | + price_detail = f"({round(data['changeRate'], 2)}%)" |
| 39 | + |
| 40 | + if self.user.display_name != display_name: |
| 41 | + await self.user.edit(username=display_name) |
| 42 | + |
| 43 | + if self.last_price != trade_price: |
| 44 | + await self.change_presence(activity=disnake.Game(name=f"💰 {trade_price} {price_detail}")) |
| 45 | + self.last_price = trade_price |
| 46 | + |
| 47 | + except Exception as e: |
| 48 | + print(e) |
| 49 | + pass |
| 50 | + |
| 51 | +scheduler = Scheduler() |
| 52 | +scheduler.run(os.environ.get('DISCORD_BOT_TOKEN')) |
0 commit comments