Spaces:
Paused
Paused
File size: 11,380 Bytes
24b805a | 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 | import os
import logging
import requests
import yfinance as yf
import json
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO
)
logger = logging.getLogger(__name__)
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
if not TOKEN:
raise ValueError("No TELEGRAM_BOT_TOKEN found")
try:
from upstash_redis import Redis
redis = Redis(
url=os.getenv("UPSTASH_REDIS_REST_URL"),
token=os.getenv("UPSTASH_REDIS_REST_TOKEN")
)
logger.info("Redis connected successfully")
except Exception as e:
logger.error(f"Redis connection failed: {e}")
redis = None
def get_price(ticker):
ticker = ticker.upper().strip()
crypto_ids = {
"BTC": "bitcoin", "ETH": "ethereum", "SOL": "solana", "XRP": "ripple",
"DOGE": "dogecoin", "ADA": "cardano", "AVAX": "avalanche-2",
"LINK": "chainlink", "BNB": "binancecoin", "DOT": "polkadot",
"MATIC": "matic-network", "SHIB": "shiba-inu"
}
if ticker in crypto_ids:
try:
coin = crypto_ids[ticker]
url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin}&vs_currencies=usd"
r = requests.get(url, timeout=10)
return r.json()[coin]["usd"]
except:
return None
try:
hist = yf.Ticker(ticker).history(period="1d")
if hist.empty:
return None
return float(hist["Close"].iloc[-1])
except:
return None
def get_data(ticker):
ticker = ticker.upper().strip()
crypto_ids = {
"BTC": "bitcoin", "ETH": "ethereum", "SOL": "solana", "XRP": "ripple",
"DOGE": "dogecoin", "ADA": "cardano", "AVAX": "avalanche-2",
"LINK": "chainlink", "BNB": "binancecoin", "DOT": "polkadot",
"MATIC": "matic-network", "SHIB": "shiba-inu"
}
if ticker in crypto_ids:
try:
coin = crypto_ids[ticker]
url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin}&vs_currencies=usd&include_24hr_change=true"
r = requests.get(url, timeout=10)
data = r.json()
if coin not in data:
return f"β No data found for {ticker}"
price = data[coin]["usd"]
change = data[coin].get("usd_24h_change", 0)
if change > 2:
trend = "Strong bullish π"
elif change > 0.5:
trend = "Mildly bullish π"
elif change < -2:
trend = "Strong bearish π"
elif change < -0.5:
trend = "Mildly bearish π"
else:
trend = "Sideways βοΈ"
return (
f"π¦ *Big Brain Ape Analysis*\n\n"
f"*{ticker}*\n"
f"π° Price: `${price:,.2f}`\n"
f"π 24h Change: `{change:+.2f}%`\n"
f"π Trend: {trend}"
)
except Exception as e:
logger.error(e)
return f"β Error fetching crypto data for {ticker}"
try:
hist = yf.Ticker(ticker).history(period="5d")
if hist.empty:
return f"β No data found for {ticker}"
price = float(hist["Close"].iloc[-1])
prev = float(hist["Close"].iloc[-2]) if len(hist) > 1 else price
change = price - prev
pct = (change / prev) * 100 if prev != 0 else 0
if pct > 2:
trend = "Strong bullish π"
elif pct > 0.5:
trend = "Mildly bullish π"
elif pct < -2:
trend = "Strong bearish π"
elif pct < -0.5:
trend = "Mildly bearish π"
else:
trend = "Sideways βοΈ"
return (
f"π¦ *Big Brain Ape Analysis*\n\n"
f"*{ticker}*\n"
f"π° Price: `${price:,.2f}`\n"
f"π Change: `{change:+.2f}` (`{pct:+.2f}%`)\n"
f"π Trend: {trend}"
)
except Exception as e:
logger.error(e)
return f"β Error fetching data for {ticker}"
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.effective_user
text = (
f"π¦ Welcome to *Big Brain Ape*, {user.first_name}!\n\n"
"Your AI-powered market analysis assistant.\n\n"
"β’ /free TICKER β Free analysis\n"
"β’ /alert TICKER PRICE β Set price alert\n"
"β’ /alerts β View your alerts\n"
"β’ /delalert NUMBER β Remove an alert\n"
"β’ /paid β Deeper analysis\n"
"β’ /hire β Hire the bot\n"
"β’ /help β All commands"
)
await update.message.reply_text(text, parse_mode="Markdown")
async def free_analysis(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not context.args:
await update.message.reply_text(
"Please provide a ticker.\n\nExamples:\n`/free BTC`\n`/free NVDA`\n`/free ETH`",
parse_mode="Markdown"
)
return
await update.message.reply_text("π Fetching live data...")
result = get_data(context.args[0])
await update.message.reply_text(result, parse_mode="Markdown")
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
text = (
"π¦ *Big Brain Ape Commands*\n\n"
"/free TICKER β Free analysis\n"
"/alert TICKER PRICE β Set alert\n"
"/alerts β List your alerts\n"
"/delalert NUMBER β Delete an alert\n"
"/paid β Paid deep analysis\n"
"/hire β Hire the bot\n"
"/help β Show this message"
)
await update.message.reply_text(text, parse_mode="Markdown")
async def paid_analysis(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"π Paid analysis coming soon.\nFor now use `/free TICKER`.",
parse_mode="Markdown"
)
async def hire(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"π€ *Hire Big Brain Ape*\n\n"
"Performance-only model β free to start.\n"
"You only pay when the bot makes you profit.\n\n"
"Coming soon.",
parse_mode="Markdown"
)
async def set_alert(update: Update, context: ContextTypes.DEFAULT_TYPE):
if redis is None:
await update.message.reply_text("β Alerts are temporarily unavailable.")
return
if not context.args or len(context.args) < 2:
await update.message.reply_text(
"Usage:\n`/alert BTC 95000`\n`/alert SOL 8%`",
parse_mode="Markdown"
)
return
ticker = context.args[0].upper()
target = context.args[1]
user_id = update.effective_user.id
alert = {"ticker": ticker, "target": target, "user_id": user_id}
key = f"alerts:{user_id}"
alerts = redis.get(key)
alerts = json.loads(alerts) if alerts else []
alerts.append(alert)
redis.set(key, json.dumps(alerts))
await update.message.reply_text(
f"β
Alert set: *{ticker}* β `{target}`",
parse_mode="Markdown"
)
async def list_alerts(update: Update, context: ContextTypes.DEFAULT_TYPE):
if redis is None:
await update.message.reply_text("β Alerts are temporarily unavailable.")
return
user_id = update.effective_user.id
key = f"alerts:{user_id}"
alerts = redis.get(key)
if not alerts:
await update.message.reply_text("You have no active alerts.")
return
alerts = json.loads(alerts)
text = "π *Your Alerts:*\n\n"
for i, a in enumerate(alerts, 1):
text += f"{i}. *{a['ticker']}* β `{a['target']}`\n"
await update.message.reply_text(text, parse_mode="Markdown")
async def delete_alert(update: Update, context: ContextTypes.DEFAULT_TYPE):
if redis is None:
await update.message.reply_text("β Alerts are temporarily unavailable.")
return
if not context.args:
await update.message.reply_text("Usage: `/delalert 1`", parse_mode="Markdown")
return
try:
index = int(context.args[0]) - 1
except:
await update.message.reply_text("Please give a number, example: `/delalert 1`", parse_mode="Markdown")
return
user_id = update.effective_user.id
key = f"alerts:{user_id}"
alerts = redis.get(key)
if not alerts:
await update.message.reply_text("You have no alerts.")
return
alerts = json.loads(alerts)
if index < 0 or index >= len(alerts):
await update.message.reply_text("Invalid number.")
return
removed = alerts.pop(index)
redis.set(key, json.dumps(alerts))
await update.message.reply_text(
f"π Removed: *{removed['ticker']}* β `{removed['target']}`",
parse_mode="Markdown"
)
async def check_alerts(context: ContextTypes.DEFAULT_TYPE):
if redis is None:
return
try:
keys = redis.keys("alerts:*")
if not keys:
return
for key in keys:
alerts_data = redis.get(key)
if not alerts_data:
continue
alerts = json.loads(alerts_data)
user_id = int(key.split(":")[1])
remaining = []
for alert in alerts:
ticker = alert["ticker"]
target = alert["target"]
price = get_price(ticker)
if price is None:
remaining.append(alert)
continue
triggered = False
if "%" not in str(target):
try:
if price >= float(target):
triggered = True
except:
remaining.append(alert)
continue
else:
remaining.append(alert)
continue
if triggered:
try:
await context.bot.send_message(
chat_id=user_id,
text=f"π¨ *ALERT*\n\n*{ticker}* hit `${price:,.2f}`\nTarget: `{target}`",
parse_mode="Markdown"
)
except Exception as e:
logger.error(e)
else:
remaining.append(alert)
if remaining:
redis.set(key, json.dumps(remaining))
else:
redis.delete(key)
except Exception as e:
logger.error(f"check_alerts error: {e}")
def main():
app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("free", free_analysis))
app.add_handler(CommandHandler("help", help_command))
app.add_handler(CommandHandler("paid", paid_analysis))
app.add_handler(CommandHandler("hire", hire))
app.add_handler(CommandHandler("alert", set_alert))
app.add_handler(CommandHandler("alerts", list_alerts))
app.add_handler(CommandHandler("delalert", delete_alert))
if app.job_queue:
app.job_queue.run_repeating(check_alerts, interval=60, first=10)
logger.info("Bot starting...")
app.run_polling()
if __name__ == "__main__":
main() |