Skip to content

Commit bbe872b

Browse files
Fixed tweets to going to correct channel
1 parent 55bd54a commit bbe872b

File tree

3 files changed

+72
-37
lines changed

3 files changed

+72
-37
lines changed

src/cogs/loops/overview.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import util.vars
88
from api.http_client import get_json_data
99
from constants.config import config
10+
from constants.logger import logger
1011
from util.disc import get_channel, get_guild, loop_error_catcher
1112
from util.formatting import format_change
1213

@@ -181,10 +182,16 @@ async def make_overview(self, category: str, tickers: list, last_sentiment: str)
181182

182183
if category == "crypto":
183184
# Delete previous message
184-
await self.crypto_channel.purge(limit=1)
185+
try:
186+
await self.crypto_channel.purge(limit=1)
187+
except discord.errors.NotFound:
188+
logger.warn("Could not delete previous crypto overview message.")
185189
await self.crypto_channel.send(embed=e)
186190
else:
187-
await self.stocks_channel.purge(limit=1)
191+
try:
192+
await self.stocks_channel.purge(limit=1)
193+
except discord.errors.NotFound:
194+
logger.warn("Could not delete previous stock overview message.")
188195
await self.stocks_channel.send(embed=e)
189196

190197

src/cogs/loops/timeline.py

+23-19
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import asyncio
34
import datetime
45
import traceback
56
from typing import List, Optional
@@ -136,25 +137,27 @@ async def get_latest_tweet(self) -> None:
136137
tweets = await get_tweet()
137138
logger.debug(f"Got {len(tweets)} tweets.")
138139

140+
# Process tweets concurrently
141+
tasks = []
142+
139143
# Loop from oldest to newest tweet
140-
for tweet in reversed(tweets):
141-
tweet = tweet["content"]
142-
143-
# Skip if the tweet is not a timeline item
144-
if "entryType" in tweet:
145-
if tweet["entryType"] != "TimelineTimelineItem":
146-
continue
147-
# Ignore popups about X Premium
148-
else:
149-
if "itemContent" in tweet:
150-
if "itemType" in tweet["itemContent"]:
151-
if (
152-
tweet["itemContent"]["itemType"]
153-
== "TimelineMessagePrompt"
154-
):
155-
continue
156-
157-
await self.on_data(tweet, update_tweet_id=True)
144+
for tweet_data in reversed(tweets):
145+
tweet = tweet_data["content"]
146+
147+
# Skip tweets that are not timeline items
148+
if not (
149+
tweet.get("entryType") == "TimelineTimelineItem"
150+
and tweet.get("itemContent", {}).get("itemType")
151+
!= "TimelineMessagePrompt"
152+
):
153+
continue
154+
155+
# Collect tasks for concurrent processing
156+
tasks.append(self.on_data(tweet, update_tweet_id=True))
157+
158+
# Run tasks concurrently for faster processing
159+
if tasks:
160+
await asyncio.gather(*tasks)
158161

159162
async def on_data(self, tweet: dict, update_tweet_id: bool = False) -> None:
160163
"""This method is called whenever data is received from the stream.
@@ -195,7 +198,8 @@ async def on_data(self, tweet: dict, update_tweet_id: bool = False) -> None:
195198
self.bot,
196199
)
197200

198-
# Upload the tweet to the Discord.
201+
# Upload the tweet to the Discord..
202+
logger.debug(f"Uploading {user_screen_name}'s tweet to {category}")
199203
await self.upload_tweet(e, category, media, user_screen_name, base_symbols)
200204

201205
async def upload_tweet(

src/util/tweet_embed.py

+40-16
Original file line numberDiff line numberDiff line change
@@ -89,13 +89,27 @@ async def make_tweet_embed(
8989
# Ensure the tickers are unique
9090
symbols = get_clean_symbols(tickers, hashtags)[:24]
9191

92-
e = make_embed(symbols, url, text, profile_pic, images, e_title, media_types)
92+
# Check for difference
93+
if symbols != tickers + hashtags:
94+
logger.debug(
95+
f"Removed following symbols: {set(tickers + hashtags) - set(symbols)}"
96+
)
97+
98+
e = make_embed(
99+
symbols=symbols,
100+
url=url,
101+
text=text,
102+
profile_pic=profile_pic,
103+
images=images,
104+
e_title=e_title,
105+
media_types=media_types,
106+
)
93107

94108
# Max 25 fields
95109
if symbols:
96-
logger.debug("Adding financials to tweet embed...")
110+
logger.debug(f"Adding financials for symbols: {symbols}")
97111
e, category, base_symbols = await add_financials(
98-
e, symbols, tickers, text, user_name, bot
112+
e=e, symbols=symbols, tickers=tickers, text=text, user=user_name, bot=bot
99113
)
100114

101115
return e, category, base_symbols
@@ -185,6 +199,9 @@ async def add_financials(
185199
The base symbols of the tickers.
186200
"""
187201
global tweet_overview
202+
logger.debug(
203+
f"Adding financials to the embed. For symbols: {symbols}, tickers: {tickers}"
204+
)
188205

189206
# In case multiple tickers get send
190207
crypto = stocks = forex = 0
@@ -200,7 +217,8 @@ async def add_financials(
200217
util.vars.classified_tickers = remove_old_rows(util.vars.classified_tickers, 3)
201218
classified_tickers = util.vars.classified_tickers["ticker"].tolist()
202219

203-
for ticker in symbols[24:]:
220+
for symbol in symbols:
221+
logger.debug(f"Symbol: {symbol}")
204222
if crypto > stocks and crypto > forex:
205223
majority = "crypto"
206224
elif stocks > crypto and stocks > forex:
@@ -211,8 +229,10 @@ async def add_financials(
211229
majority = "Unknown"
212230

213231
# Get the information about the ticker
214-
if ticker not in classified_tickers:
215-
ticker_info = await classify_ticker(ticker, majority)
232+
if symbol not in classified_tickers:
233+
logger.debug(f"Classifying ticker: {symbol} with majority: {majority}")
234+
ticker_info = await classify_ticker(symbol, majority)
235+
216236
if ticker_info:
217237
(
218238
_,
@@ -224,20 +244,23 @@ async def add_financials(
224244
one_d_ta,
225245
base_symbol,
226246
) = ticker_info
247+
logger.debug(
248+
f"Classified ticker: {symbol} as {base_symbol}. Website: {website}"
249+
)
227250

228251
# Skip if this ticker has been done before, for instance in tweets containing Solana and SOL
229252
if base_symbol in base_symbols:
230253
continue
231254

232255
if exchanges is None:
233256
exchanges = []
234-
logger.warn("No exchanges found for", ticker)
257+
logger.warn(f"No exchanges found for ticker: {symbol}")
235258

236259
# Convert info to a dataframe
237260
df = pd.DataFrame(
238261
[
239262
{
240-
"ticker": ticker,
263+
"ticker": symbol,
241264
"website": website,
242265
# Db cannot handle lists, so we convert them to strings
243266
"exchanges": (
@@ -255,17 +278,18 @@ async def add_financials(
255278
)
256279

257280
else:
258-
if ticker in tickers:
259-
e.add_field(name=f"${ticker}", value=majority)
260-
logger.debug(
261-
f"No crypto or stock match found for ${ticker} in {user}'s tweet at {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}"
262-
)
281+
if symbol in tickers:
282+
e.add_field(name=f"${symbol}", value=majority)
283+
logger.debug(
284+
f"No crypto or stock match found for ${symbol} in {user}'s tweet at {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}"
285+
)
263286

264287
# Go to next in symbols
265288
continue
266289
else:
290+
logger.debug(f"Found ticker {symbol} in previously classified tickers.")
267291
ticker_info = util.vars.classified_tickers[
268-
util.vars.classified_tickers["ticker"] == ticker
292+
util.vars.classified_tickers["ticker"] == symbol
269293
]
270294
website = ticker_info["website"].values[0]
271295
exchanges = ticker_info["exchanges"].values[0]
@@ -274,9 +298,9 @@ async def add_financials(
274298
base_symbol = ticker_info["base_symbol"].values[0]
275299

276300
# Still need the price, change, TA info
277-
price, change, four_h_ta, one_d_ta = await get_financials(ticker, website)
301+
price, change, four_h_ta, one_d_ta = await get_financials(symbol, website)
278302

279-
title = f"${ticker}"
303+
title = f"${symbol}"
280304

281305
# Add to base symbol list to prevent duplicates
282306
base_symbols.append(base_symbol)

0 commit comments

Comments
 (0)