Spaces:
Paused
Paused
File size: 6,259 Bytes
5116a2e |
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 |
#!/usr/bin/env python3
"""
Test Telegram Integration for All Alert Types
"""
import os
import requests
from dotenv import load_dotenv
from services.telegram import send_telegram
load_dotenv()
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
def test_telegram_direct():
"""Test telegram API directly"""
print("π Testing Telegram API directly...")
if not BOT_TOKEN or not CHAT_ID:
print("β Telegram credentials not found in .env")
return False
try:
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
data = {
"chat_id": CHAT_ID,
"text": "π€ Telegram Integration Test - Direct API call"
}
response = requests.post(url, data=data, timeout=10)
if response.status_code == 200:
result = response.json()
if result.get('ok'):
print("β
Direct API call successful")
return True
else:
print(f"β API returned error: {result}")
return False
else:
print(f"β HTTP error: {response.status_code} - {response.text}")
return False
except Exception as e:
print(f"β Direct API call failed: {e}")
return False
def test_service_function():
"""Test the telegram service function"""
print("\nπ Testing Telegram service function...")
try:
send_telegram("π€ Telegram Integration Test - Service function")
print("β
Service function called (check Telegram for message)")
return True
except Exception as e:
print(f"β Service function failed: {e}")
return False
def test_all_alert_types():
"""Test all types of alerts that the bot sends"""
print("\nπ¨ Testing all alert types...")
alerts = [
# Trading session alerts
("π BTCUSDT LONG @ $84,200", "Trade entry alert"),
("π― TP: $86,355 (+2.5%)", "Take profit alert"),
("π‘οΈ SL: $83,258 (-1%)", "Stop loss alert"),
# Trade execution alerts
("π° BTCUSDT TP HIT @ $86,355", "Take profit hit"),
("πΈ BTCUSDT SL HIT @ $83,258", "Stop loss hit"),
("π BTCUSDT position closed", "Position closure"),
# Session management alerts
("βΆοΈ Started trading session for BTCUSDT (18h duration)", "Session start"),
("βΉοΈ Stopped trading session for BTCUSDT", "Session stop"),
# System alerts
("π¨ EMERGENCY STOP activated - All trading halted", "Emergency stop"),
("π Daily P&L: -$45.67 (Limit: -$100)", "Daily P&L report"),
# Session reports
("π TRADING SESSION REPORT - BTCUSDT\nβ’ Duration: 18 hours\nβ’ Total Trades: 45\nβ’ Win Rate: 71.1%\nβ’ Total P&L: $15.23", "Session report"),
# Analysis alerts
("π― TRADE SIGNAL READY - BTCUSDT", "Signal detection"),
("π EMA 9: 84120.45, EMA 21: 84095.23", "Technical analysis"),
("π RSI 14: 67.8", "RSI reading"),
("π₯ Volume spike detected", "Volume alert"),
]
sent_count = 0
for message, alert_type in alerts:
try:
send_telegram(f"π§ͺ TEST ALERT - {alert_type}\n{message}")
sent_count += 1
print(f"β
Sent: {alert_type}")
except Exception as e:
print(f"β Failed to send {alert_type}: {e}")
print(f"\nπ Sent {sent_count}/{len(alerts)} test alerts")
return sent_count == len(alerts)
def get_bot_info():
"""Get telegram bot information"""
print("\nπ€ Checking Telegram bot info...")
if not BOT_TOKEN:
print("β Bot token not configured")
return False
try:
url = f"https://api.telegram.org/bot{BOT_TOKEN}/getMe"
response = requests.get(url, timeout=10)
if response.status_code == 200:
result = response.json()
if result.get('ok'):
bot = result['result']
print("β
Bot connected successfully")
print(f" Name: {bot.get('first_name', 'Unknown')}")
print(f" Username: @{bot.get('username', 'Unknown')}")
print(f" Can read messages: {bot.get('can_read_all_group_messages', False)}")
return True
else:
print(f"β Bot info error: {result}")
return False
else:
print(f"β HTTP error: {response.status_code}")
return False
except Exception as e:
print(f"β Failed to get bot info: {e}")
return False
def main():
print("π Telegram Integration Test Suite")
print("=" * 50)
# Test bot connection
bot_ok = get_bot_info()
if not bot_ok:
print("\nβ Cannot proceed without bot connection")
return
# Test direct API
direct_ok = test_telegram_direct()
# Test service function
service_ok = test_service_function()
# Test all alert types
alerts_ok = test_all_alert_types()
# Summary
print("\n" + "=" * 50)
print("π TELEGRAM INTEGRATION TEST RESULTS:")
print(f"π€ Bot Connection: {'β
PASS' if bot_ok else 'β FAIL'}")
print(f"π Direct API: {'β
PASS' if direct_ok else 'β FAIL'}")
print(f"βοΈ Service Function: {'β
PASS' if service_ok else 'β FAIL'}")
print(f"π¨ All Alerts: {'β
PASS' if alerts_ok else 'β FAIL'}")
all_pass = bot_ok and direct_ok and service_ok and alerts_ok
if all_pass:
print("\nπ ALL TESTS PASSED!")
print("π± Check your Telegram for test messages")
print("β
Telegram integration is fully working")
else:
print("\nβ οΈ Some tests failed. Check your configuration:")
print("1. Verify TELEGRAM_BOT_TOKEN in .env")
print("2. Verify TELEGRAM_CHAT_ID in .env")
print("3. Send a message to your bot and run get_chat_id.py")
print("4. Check internet connection")
print("\nπ§ Current Configuration:")
print(f" Bot Token: {BOT_TOKEN[:20]}..." if BOT_TOKEN else " Bot Token: Not set")
print(f" Chat ID: {CHAT_ID}" if CHAT_ID else " Chat ID: Not set")
if __name__ == "__main__":
main()
|