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()