vanzuera commited on
Commit
b28ce06
Β·
verified Β·
1 Parent(s): f04345e

Upload 14 files

Browse files
Files changed (14) hide show
  1. .env +11 -0
  2. .env.example +16 -0
  3. .gitattributes +35 -35
  4. .gitignore +156 -0
  5. Dockerfile +23 -0
  6. LICENSE +21 -0
  7. Procfile +1 -0
  8. alive.py +50 -0
  9. command.py +197 -0
  10. docker-compose.yml +27 -0
  11. main.py +173 -0
  12. ngrok_api.py +243 -0
  13. requirements.txt +13 -0
  14. test_deployment.py +64 -0
.env ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Telegram API credentials
2
+ API_ID=2589472
3
+ API_HASH=5243628014db9798d6775b330e542602
4
+ BOT_TOKEN=2031162197:AAFAgHl3cIegJPia9jnIfT6tHj2HNgCLkCA
5
+
6
+ # Optional: Logging level
7
+ LOG_LEVEL=INFO
8
+
9
+ # Auto-alive configuration for HuggingFace Spaces
10
+ BASE_URL=https://deploy199-readme.hf.space
11
+ HF_TOKEN=your_hf_token_here
.env.example ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Telegram API credentials
2
+ # Get these from https://my.telegram.org/apps
3
+ API_ID=your_api_id_here
4
+ API_HASH=your_api_hash_here
5
+
6
+ # Telegram Bot Token
7
+ # Get this from @BotFather on Telegram
8
+ BOT_TOKEN=your_bot_token_here
9
+
10
+ # Optional: Ngrok API Key for tunnel monitoring
11
+ # Get this from https://dashboard.ngrok.com/get-started/your-authtoken
12
+ # Format: NGROK_API_KEY_<user_id>=your_ngrok_api_key
13
+ # Example: NGROK_API_KEY_123456789=2abc...xyz
14
+
15
+ # Optional: Logging level (DEBUG, INFO, WARNING, ERROR)
16
+ LOG_LEVEL=INFO
.gitattributes CHANGED
@@ -1,35 +1,35 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ target/
76
+
77
+ # Jupyter Notebook
78
+ .ipynb_checkpoints
79
+
80
+ # IPython
81
+ profile_default/
82
+ ipython_config.py
83
+
84
+ # pyenv
85
+ .python-version
86
+
87
+ # pipenv
88
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
90
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
91
+ # install all needed dependencies.
92
+ #Pipfile.lock
93
+
94
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95
+ __pypackages__/
96
+
97
+ # Celery stuff
98
+ celerybeat-schedule
99
+ celerybeat.pid
100
+
101
+ # SageMath parsed files
102
+ *.sage.py
103
+
104
+ # Environments
105
+ .venv
106
+ env/
107
+ venv/
108
+ ENV/
109
+ env.bak/
110
+ venv.bak/
111
+
112
+ # Spyder project settings
113
+ .spyderproject
114
+ .spyproject
115
+
116
+ # Rope project settings
117
+ .ropeproject
118
+
119
+ # mkdocs documentation
120
+ /site
121
+
122
+ # mypy
123
+ .mypy_cache/
124
+ .dmypy.json
125
+ dmypy.json
126
+
127
+ # Pyre type checker
128
+ .pyre/
129
+
130
+ # Pyrogram session files
131
+ *.session
132
+ *.session-journal
133
+
134
+ # IDE files
135
+ .vscode/
136
+ .idea/
137
+ *.swp
138
+ *.swo
139
+ *~
140
+
141
+ # OS files
142
+ .DS_Store
143
+ .DS_Store?
144
+ ._*
145
+ .Spotlight-V100
146
+ .Trashes
147
+ ehthumbs.db
148
+ Thumbs.db
149
+
150
+ # Logs
151
+ *.log
152
+ logs/
153
+
154
+ # Temporary files
155
+ *.tmp
156
+ *.temp
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Production Docker setup for FastAPI + Telegram Bot
2
+ FROM python:3.9-slim
3
+
4
+ # Create non-root user for security
5
+ RUN useradd -m -u 1000 user
6
+ USER user
7
+ ENV PATH="/home/user/.local/bin:$PATH"
8
+
9
+ # Set working directory
10
+ WORKDIR /app
11
+
12
+ # Copy and install Python dependencies
13
+ COPY --chown=user ./requirements.txt requirements.txt
14
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
15
+
16
+ # Copy application code
17
+ COPY --chown=user . /app
18
+
19
+ # Expose the application port
20
+ EXPOSE 7860
21
+
22
+ # Start the application (both FastAPI and Telegram bot)
23
+ CMD ["python", "main.py"]
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Pranav Ajay
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
Procfile ADDED
@@ -0,0 +1 @@
 
 
1
+ web: uvicorn main:app --host=0.0.0.0 --port=${PORT:-5000}
alive.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from http.client import responses
2
+ from logging import (
3
+ basicConfig,
4
+ getLogger,
5
+ INFO,
6
+ )
7
+ from os import environ
8
+ from requests import get
9
+ from time import sleep
10
+
11
+ basicConfig(
12
+ format="{asctime} - [{levelname[0]}] {name} [{module}:{lineno}] - {message}",
13
+ datefmt="%Y-%m-%d %H:%M:%S",
14
+ style="{",
15
+ level=INFO,
16
+ )
17
+
18
+ LOGGER = getLogger("Alive")
19
+
20
+ def sendRequest(url: str, header: dict) -> None:
21
+ request = get(
22
+ url=url,
23
+ headers=header,
24
+ timeout=10,
25
+ allow_redirects=True,
26
+ )
27
+
28
+ if not request.ok:
29
+ raise Exception(f"[{request.status_code}] - {responses[request.status_code]}")
30
+
31
+ try:
32
+ HEADER = dict()
33
+ BASE_URL = None
34
+
35
+ if BASE_URL := environ.get("BASE_URL"):
36
+ if "hf.sp" in BASE_URL:
37
+ if HF_TOKEN := environ.get("HF_TOKEN"):
38
+ HEADER["Authorization"] = f"Bearer {HF_TOKEN}"
39
+
40
+ HEADER["User-Agent"] = "Not a RoBot"
41
+
42
+ while True:
43
+ sendRequest(
44
+ url=BASE_URL,
45
+ header=HEADER,
46
+ )
47
+ sleep(300)
48
+
49
+ except Exception as error:
50
+ LOGGER.error(error)
command.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pyrogram import Client, filters
2
+ from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
3
+ import logging
4
+ import os
5
+ from ngrok_api import NgrokAPI
6
+
7
+ # Configure logging
8
+ logging.basicConfig(level=logging.INFO)
9
+ logger = logging.getLogger(__name__)
10
+
11
+ # Store user states for API key setting
12
+ user_states = {}
13
+
14
+ def setup_handlers(bot: Client):
15
+ """Setup command handlers for the bot"""
16
+
17
+ @bot.on_message(filters.command("start"))
18
+ async def start_command(client, message):
19
+ """Handle /start command"""
20
+ try:
21
+ user_name = message.from_user.first_name if message.from_user.first_name else "User"
22
+ welcome_text = f"Hello {user_name}! πŸ‘‹\n\nWelcome to the FastAPI Telegram Bot with Ngrok integration!\n\n"
23
+ welcome_text += "**Available Commands:**\n"
24
+ welcome_text += "β€’ `/ngrok` - Check ngrok tunnels and edges\n"
25
+ welcome_text += "β€’ `/setapi` - Set your ngrok API key\n"
26
+ welcome_text += "β€’ Any text message will be echoed back\n\n"
27
+ welcome_text += "Get started by setting your ngrok API key with `/setapi`"
28
+
29
+ await message.reply_text(welcome_text)
30
+ logger.info(f"Handled /start command from user: {message.from_user.id}")
31
+
32
+ except Exception as e:
33
+ logger.error(f"Error in start_command handler: {e}")
34
+ await message.reply_text("Sorry, something went wrong. Please try again later.")
35
+
36
+ @bot.on_message(filters.command("ngrok"))
37
+ async def ngrok_command(client, message):
38
+ """Handle /ngrok command to show tunnel information"""
39
+ try:
40
+ user_id = message.from_user.id
41
+
42
+ # Check if user has API key set
43
+ ngrok_api_key = os.environ.get(f"NGROK_API_KEY_{user_id}")
44
+ if not ngrok_api_key:
45
+ keyboard = InlineKeyboardMarkup([
46
+ [InlineKeyboardButton("Set API Key", callback_data="set_api_key")]
47
+ ])
48
+ await message.reply_text(
49
+ "❌ **Ngrok API Key not configured**\n\n"
50
+ "Please set your ngrok API key first to use this feature.\n"
51
+ "You can get your API key from: https://dashboard.ngrok.com/get-started/your-authtoken",
52
+ reply_markup=keyboard
53
+ )
54
+ return
55
+
56
+ # Show loading message
57
+ loading_msg = await message.reply_text("πŸ”„ Fetching ngrok information...")
58
+
59
+ # Initialize ngrok API
60
+ ngrok = NgrokAPI(ngrok_api_key)
61
+
62
+ # Fetch data
63
+ tunnels = await ngrok.get_tunnels()
64
+ edges = await ngrok.get_edges()
65
+ endpoints = await ngrok.get_endpoints()
66
+
67
+ # Format and send response
68
+ info_text = ngrok.format_tunnel_info(tunnels, edges, endpoints)
69
+
70
+ keyboard = InlineKeyboardMarkup([
71
+ [InlineKeyboardButton("πŸ”„ Refresh", callback_data="refresh_ngrok")],
72
+ [InlineKeyboardButton("βš™οΈ Change API Key", callback_data="set_api_key")]
73
+ ])
74
+
75
+ await loading_msg.edit_text(info_text, reply_markup=keyboard)
76
+ logger.info(f"Handled /ngrok command from user: {user_id}")
77
+
78
+ except Exception as e:
79
+ logger.error(f"Error in ngrok_command handler: {e}")
80
+ await message.reply_text("❌ Error fetching ngrok information. Please check your API key and try again.")
81
+
82
+ @bot.on_message(filters.command("setapi"))
83
+ async def setapi_command(client, message):
84
+ """Handle /setapi command to set ngrok API key"""
85
+ try:
86
+ user_id = message.from_user.id
87
+ user_states[user_id] = "waiting_for_api_key"
88
+
89
+ await message.reply_text(
90
+ "πŸ”‘ **Set Ngrok API Key**\n\n"
91
+ "Please reply to this message with your ngrok API key.\n\n"
92
+ "You can find your API key at:\n"
93
+ "https://dashboard.ngrok.com/get-started/your-authtoken\n\n"
94
+ "⚠️ **Security Note:** Your API key will be stored securely and only used for ngrok API calls."
95
+ )
96
+ logger.info(f"User {user_id} initiated API key setup")
97
+
98
+ except Exception as e:
99
+ logger.error(f"Error in setapi_command handler: {e}")
100
+ await message.reply_text("Sorry, something went wrong. Please try again later.")
101
+
102
+ @bot.on_callback_query()
103
+ async def callback_handler(client, callback_query: CallbackQuery):
104
+ """Handle callback queries from inline keyboards"""
105
+ try:
106
+ data = callback_query.data
107
+ user_id = callback_query.from_user.id
108
+
109
+ if data == "set_api_key":
110
+ user_states[user_id] = "waiting_for_api_key"
111
+ await callback_query.message.reply_text(
112
+ "πŸ”‘ **Set Ngrok API Key**\n\n"
113
+ "Please reply to this message with your ngrok API key.\n\n"
114
+ "You can find your API key at:\n"
115
+ "https://dashboard.ngrok.com/get-started/your-authtoken\n\n"
116
+ "⚠️ **Security Note:** Your API key will be stored securely and only used for ngrok API calls."
117
+ )
118
+ await callback_query.answer("Please send your API key")
119
+
120
+ elif data == "refresh_ngrok":
121
+ # Check if user has API key set
122
+ ngrok_api_key = os.environ.get(f"NGROK_API_KEY_{user_id}")
123
+ if not ngrok_api_key:
124
+ await callback_query.answer("❌ API key not configured", show_alert=True)
125
+ return
126
+
127
+ await callback_query.answer("πŸ”„ Refreshing...")
128
+
129
+ # Initialize ngrok API and fetch data
130
+ ngrok = NgrokAPI(ngrok_api_key)
131
+ tunnels = await ngrok.get_tunnels()
132
+ edges = await ngrok.get_edges()
133
+ endpoints = await ngrok.get_endpoints()
134
+
135
+ # Format and update message
136
+ info_text = ngrok.format_tunnel_info(tunnels, edges, endpoints)
137
+
138
+ keyboard = InlineKeyboardMarkup([
139
+ [InlineKeyboardButton("πŸ”„ Refresh", callback_data="refresh_ngrok")],
140
+ [InlineKeyboardButton("βš™οΈ Change API Key", callback_data="set_api_key")]
141
+ ])
142
+
143
+ # Always try to edit the message since we now include timestamp to make it unique
144
+ try:
145
+ await callback_query.message.edit_text(info_text, reply_markup=keyboard)
146
+ await callback_query.answer("βœ… Refreshed")
147
+ except Exception as edit_error:
148
+ # If edit still fails, delete the old message and send a new one
149
+ logger.warning(f"Failed to edit message, replacing with new one: {edit_error}")
150
+ try:
151
+ await callback_query.message.delete()
152
+ except:
153
+ pass # Ignore delete errors
154
+
155
+ await callback_query.message.reply_text(info_text, reply_markup=keyboard)
156
+ await callback_query.answer("βœ… Updated")
157
+
158
+ except Exception as e:
159
+ logger.error(f"Error in callback_handler: {e}")
160
+ await callback_query.answer("❌ Error occurred", show_alert=True)
161
+
162
+ @bot.on_message(filters.text & ~filters.command(["start", "ngrok", "setapi"]))
163
+ async def text_message_handler(client, message):
164
+ """Handle text messages - either API key input or echo"""
165
+ try:
166
+ user_id = message.from_user.id
167
+
168
+ # Check if user is setting API key
169
+ if user_states.get(user_id) == "waiting_for_api_key":
170
+ api_key = message.text.strip()
171
+
172
+ # Basic validation
173
+ if len(api_key) < 10:
174
+ await message.reply_text("❌ Invalid API key format. Please try again.")
175
+ return
176
+
177
+ # Store API key (in production, use secure storage)
178
+ os.environ[f"NGROK_API_KEY_{user_id}"] = api_key
179
+ user_states.pop(user_id, None)
180
+
181
+ await message.reply_text(
182
+ "βœ… **API Key Set Successfully!**\n\n"
183
+ "You can now use `/ngrok` to check your tunnels and edges.\n\n"
184
+ "πŸ”’ Your API key is stored securely and will only be used for ngrok API calls."
185
+ )
186
+ logger.info(f"API key set for user: {user_id}")
187
+ return
188
+
189
+ # Echo message if not setting API key
190
+ await message.reply_text(f"Echo: {message.text}")
191
+ logger.info(f"Echoed message to user: {user_id}")
192
+
193
+ except Exception as e:
194
+ logger.error(f"Error in text_message_handler: {e}")
195
+ await message.reply_text("Sorry, I couldn't process your message.")
196
+
197
+ logger.info("Command handlers setup completed")
docker-compose.yml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ fastapi-telegram-bot:
5
+ build: .
6
+ container_name: fastapi-telegram-bot
7
+ ports:
8
+ - "7860:7860"
9
+ environment:
10
+ - API_ID=${API_ID}
11
+ - API_HASH=${API_HASH}
12
+ - BOT_TOKEN=${BOT_TOKEN}
13
+ restart: unless-stopped
14
+ healthcheck:
15
+ test: ["CMD", "python", "-c", "import httpx; httpx.get('http://localhost:7860/health')"]
16
+ interval: 30s
17
+ timeout: 10s
18
+ retries: 3
19
+ start_period: 40s
20
+ volumes:
21
+ - ./logs:/app/logs
22
+ networks:
23
+ - bot-network
24
+
25
+ networks:
26
+ bot-network:
27
+ driver: bridge
main.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from fastapi import FastAPI, HTTPException
3
+ from pyrogram import Client, idle
4
+ import uvicorn
5
+ import os
6
+ import logging
7
+ from dotenv import load_dotenv
8
+ from command import setup_handlers
9
+ import httpx
10
+ from time import sleep
11
+ import threading
12
+
13
+ # Load environment variables
14
+ load_dotenv()
15
+
16
+ # Configure logging
17
+ logging.basicConfig(level=logging.INFO)
18
+ logger = logging.getLogger(__name__)
19
+
20
+ app = FastAPI(title="FastAPI Telegram Bot Integration")
21
+
22
+ # Get environment variables
23
+ API_ID = os.environ.get("API_ID")
24
+ API_HASH = os.environ.get("API_HASH")
25
+ BOT_TOKEN = os.environ.get("BOT_TOKEN")
26
+
27
+ # Validate environment variables
28
+ if not (API_ID and API_HASH and BOT_TOKEN):
29
+ raise Exception("Missing one or more required environment variables: API_ID, API_HASH, BOT_TOKEN")
30
+
31
+ # Global bot instance for API endpoints
32
+ running_bot = None
33
+
34
+ # Auto-alive functionality to keep HuggingFace Space active
35
+ def keep_alive():
36
+ """Keep the app alive by pinging itself every 5 minutes"""
37
+ base_url = os.environ.get("BASE_URL")
38
+ hf_token = os.environ.get("HF_TOKEN")
39
+
40
+ if not base_url:
41
+ logger.info("BASE_URL not set, auto-alive disabled")
42
+ return
43
+
44
+ headers = {"User-Agent": "FastAPI-Telegram-Bot-KeepAlive"}
45
+
46
+ # Add HuggingFace token if available and URL contains hf.space
47
+ if "huggingface.co" in base_url and hf_token:
48
+ headers["Authorization"] = f"Bearer {hf_token}"
49
+
50
+ logger.info(f"Auto-alive enabled for: {base_url}")
51
+
52
+ while True:
53
+ try:
54
+ # Ping the health endpoint to keep the app alive
55
+ ping_url = f"{base_url.rstrip('/')}/health"
56
+ response = httpx.get(ping_url, headers=headers, timeout=10)
57
+
58
+ if response.status_code == 200:
59
+ logger.info(f"βœ… Keep-alive ping successful: {response.status_code}")
60
+ else:
61
+ logger.warning(f"⚠️ Keep-alive ping returned: {response.status_code}")
62
+
63
+ except Exception as e:
64
+ logger.error(f"❌ Keep-alive ping failed: {e}")
65
+
66
+ # Wait 5 minutes before next ping
67
+ sleep(300)
68
+
69
+ def start_keep_alive():
70
+ """Start the keep-alive functionality in a separate thread"""
71
+ keep_alive_thread = threading.Thread(target=keep_alive, daemon=True)
72
+ keep_alive_thread.start()
73
+ logger.info("Keep-alive thread started")
74
+
75
+ @app.get("/")
76
+ async def root():
77
+ """Root endpoint - Main page for HuggingFace Spaces"""
78
+ return {
79
+ "title": "FastAPI Telegram Bot Integration",
80
+ "description": "A production-ready FastAPI application integrated with a Telegram bot using Pyrogram",
81
+ "status": "running",
82
+ "endpoints": {
83
+ "health": "/health",
84
+ "send_message": "/sendmessage?log={chat_id}&msg={message}",
85
+ "docs": "/docs",
86
+ "redoc": "/redoc"
87
+ },
88
+ "telegram_bot": {
89
+ "status": "active" if running_bot else "inactive",
90
+ "commands": ["/start", "/ngrok", "/setapi"]
91
+ },
92
+ "auto_alive": {
93
+ "status": "enabled" if os.environ.get("BASE_URL") else "disabled",
94
+ "base_url": os.environ.get("BASE_URL", "not_set")
95
+ }
96
+ }
97
+
98
+ @app.get("/health")
99
+ async def health_check():
100
+ """Health check endpoint"""
101
+ return {"status": "ok", "message": "FastAPI Telegram Bot is running"}
102
+
103
+ @app.get('/sendmessage')
104
+ async def send_message(log: str, msg: str):
105
+ """Send message endpoint"""
106
+ try:
107
+ if running_bot is None:
108
+ raise HTTPException(status_code=500, detail="Bot not initialized")
109
+
110
+ await running_bot.send_message(chat_id=log, text=str(msg))
111
+ logger.info(f"Message sent to chat {log}: {msg}")
112
+ return {'message': "Done πŸ‘"}
113
+ except Exception as e:
114
+ logger.error(f"Error sending message: {e}")
115
+ raise HTTPException(status_code=500, detail=str(e))
116
+
117
+ async def main():
118
+ """Main function following Pyrogram docs pattern"""
119
+ global running_bot
120
+
121
+ try:
122
+ # Start keep-alive functionality first
123
+ start_keep_alive()
124
+
125
+ # Create bot client (using one client as requested)
126
+ app_client = Client(
127
+ ':memory:',
128
+ api_id=int(API_ID),
129
+ api_hash=API_HASH,
130
+ bot_token=BOT_TOKEN
131
+ )
132
+
133
+ # Set up handlers
134
+ setup_handlers(app_client)
135
+
136
+ # Start the client
137
+ await app_client.start()
138
+ logger.info("Telegram bot started successfully")
139
+
140
+ # Store reference for API endpoints
141
+ running_bot = app_client
142
+
143
+ # Configure and start FastAPI server concurrently
144
+ config = uvicorn.Config(
145
+ app,
146
+ host="0.0.0.0",
147
+ port=7860,
148
+ log_level="info",
149
+ loop="asyncio"
150
+ )
151
+ server = uvicorn.Server(config)
152
+
153
+ # Start FastAPI server as background task
154
+ server_task = asyncio.create_task(server.serve())
155
+
156
+ logger.info("FastAPI server and Telegram bot are running...")
157
+ logger.info("Auto-alive functionality is active to prevent HuggingFace Space sleep")
158
+
159
+ # Wait for termination signal (following Pyrogram docs pattern)
160
+ await idle()
161
+
162
+ # Stop the client (following Pyrogram docs pattern)
163
+ await app_client.stop()
164
+ logger.info("Telegram bot stopped")
165
+
166
+ # Stop FastAPI server
167
+ server.should_exit = True
168
+
169
+ except Exception as e:
170
+ logger.error(f"Error in main execution: {e}")
171
+
172
+ if __name__ == '__main__':
173
+ asyncio.run(main())
ngrok_api.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import httpx
2
+ import logging
3
+ import os
4
+ import time
5
+ from datetime import datetime, timedelta
6
+ from typing import Dict, List, Optional
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ class NgrokAPI:
11
+ def __init__(self, api_key: str = None):
12
+ self.api_key = api_key or os.environ.get("NGROK_API_KEY")
13
+ self.base_url = "https://api.ngrok.com"
14
+ self.headers = {
15
+ "Authorization": f"Bearer {self.api_key}",
16
+ "Ngrok-Version": "2"
17
+ }
18
+ self._last_message_hash = None
19
+ self._last_refresh_time = None
20
+
21
+ async def get_tunnels(self) -> List[Dict]:
22
+ """Get all active tunnels"""
23
+ try:
24
+ async with httpx.AsyncClient() as client:
25
+ response = await client.get(
26
+ f"{self.base_url}/tunnels",
27
+ headers=self.headers
28
+ )
29
+ response.raise_for_status()
30
+ data = response.json()
31
+ return data.get("tunnels", [])
32
+ except Exception as e:
33
+ logger.error(f"Error fetching tunnels: {e}")
34
+ return []
35
+
36
+ async def get_edges(self) -> List[Dict]:
37
+ """Get all edges"""
38
+ try:
39
+ async with httpx.AsyncClient() as client:
40
+ response = await client.get(
41
+ f"{self.base_url}/edges/tcp",
42
+ headers=self.headers
43
+ )
44
+ response.raise_for_status()
45
+ data = response.json()
46
+ return data.get("tcp_edges", [])
47
+ except Exception as e:
48
+ logger.error(f"Error fetching edges: {e}")
49
+ return []
50
+
51
+ async def get_endpoints(self) -> List[Dict]:
52
+ """Get all endpoints"""
53
+ try:
54
+ async with httpx.AsyncClient() as client:
55
+ response = await client.get(
56
+ f"{self.base_url}/endpoints",
57
+ headers=self.headers
58
+ )
59
+ response.raise_for_status()
60
+ data = response.json()
61
+ return data.get("endpoints", [])
62
+ except Exception as e:
63
+ logger.error(f"Error fetching endpoints: {e}")
64
+ return []
65
+
66
+ def _format_url(self, url: str) -> str:
67
+ """Format URL by removing protocol prefix and handling edge cases"""
68
+ if not url or url == "N/A" or url == "":
69
+ return "N/A"
70
+
71
+ # Handle malformed URLs that start with ://
72
+ if url.startswith("://"):
73
+ return url[3:] # Remove "://"
74
+ elif url.startswith("tcp://"):
75
+ return url[6:] # Remove "tcp://"
76
+ elif url.startswith("http://"):
77
+ return url[7:] # Remove "http://"
78
+ elif url.startswith("https://"):
79
+ return url[8:] # Remove "https://"
80
+
81
+ return url
82
+
83
+ def _calculate_uptime(self, created_at: str) -> str:
84
+ """Calculate uptime from created_at timestamp"""
85
+ try:
86
+ # Parse the ISO timestamp
87
+ created_time = datetime.fromisoformat(created_at.replace('Z', '+00:00'))
88
+ current_time = datetime.now(created_time.tzinfo)
89
+ uptime = current_time - created_time
90
+
91
+ # Format uptime
92
+ days = uptime.days
93
+ hours, remainder = divmod(uptime.seconds, 3600)
94
+ minutes, _ = divmod(remainder, 60)
95
+
96
+ if days > 0:
97
+ return f"{days}d {hours}h {minutes}m"
98
+ elif hours > 0:
99
+ return f"{hours}h {minutes}m"
100
+ else:
101
+ return f"{minutes}m"
102
+ except Exception as e:
103
+ logger.error(f"Error calculating uptime: {e}")
104
+ return "Unknown"
105
+
106
+ def _get_time_since_last_refresh(self) -> str:
107
+ """Get time since last refresh in human readable format with random component"""
108
+ current_time = datetime.now()
109
+
110
+ if self._last_refresh_time is None:
111
+ self._last_refresh_time = current_time
112
+ return "now"
113
+
114
+ time_diff = current_time - self._last_refresh_time
115
+ total_seconds = int(time_diff.total_seconds())
116
+
117
+ # Add current timestamp to make message unique every time
118
+ timestamp = current_time.strftime("%H:%M:%S")
119
+
120
+ if total_seconds < 60:
121
+ return f"{total_seconds} second{'s' if total_seconds != 1 else ''} ago ({timestamp})"
122
+ elif total_seconds < 3600:
123
+ minutes = total_seconds // 60
124
+ return f"{minutes} minute{'s' if minutes != 1 else ''} ago ({timestamp})"
125
+ else:
126
+ hours = total_seconds // 3600
127
+ return f"{hours} hour{'s' if hours != 1 else ''} ago ({timestamp})"
128
+
129
+ def format_tunnel_info(self, tunnels: List[Dict], edges: List[Dict], endpoints: List[Dict]) -> str:
130
+ """Format tunnel information for display with consistent formatting"""
131
+ if not tunnels and not edges and not endpoints:
132
+ return "❌ No active tunnels, edges, or endpoints found."
133
+
134
+ # Update last refresh time
135
+ current_time = datetime.now()
136
+ time_since_refresh = self._get_time_since_last_refresh()
137
+ self._last_refresh_time = current_time
138
+
139
+ # Use f-string for better customization as requested
140
+ message = f"""πŸ”— **Ngrok Status**
141
+
142
+ """
143
+
144
+ if tunnels:
145
+ message += f"""**πŸš‡ Active Tunnels:**
146
+ """
147
+ for tunnel in tunnels:
148
+ name = tunnel.get("name", "")
149
+ public_url = tunnel.get("public_url", "N/A")
150
+ proto = tunnel.get("proto", "tcp") # Default to tcp if not specified
151
+ created_at = tunnel.get("created_at", "")
152
+
153
+ # Format URL without protocol and use code markdown
154
+ formatted_url = self._format_url(public_url)
155
+
156
+ # Consistent formatting - always show protocol and uptime structure
157
+ if created_at and formatted_url != "N/A":
158
+ uptime = self._calculate_uptime(created_at)
159
+ message += f"""β€’ ({proto})
160
+ `{formatted_url}`
161
+ ⏱️ Uptime: {uptime}
162
+
163
+ """
164
+ elif formatted_url != "N/A":
165
+ message += f"""β€’ ({proto})
166
+ `{formatted_url}`
167
+
168
+ """
169
+ else:
170
+ message += f"""β€’ ({proto})
171
+ `N/A`
172
+
173
+ """
174
+
175
+ if edges:
176
+ message += f"""**⚑ TCP Edges:**
177
+ """
178
+ for edge in edges:
179
+ edge_id = edge.get("id", "Unknown")
180
+ hostports = edge.get("hostports", [])
181
+ created_at = edge.get("created_at", "")
182
+
183
+ message += f"""β€’ **Edge ID:** `{edge_id}`
184
+ """
185
+ if hostports:
186
+ message += f""" **Hostports:** {', '.join(hostports)}
187
+ """
188
+
189
+ # Add uptime if available
190
+ if created_at:
191
+ uptime = self._calculate_uptime(created_at)
192
+ message += f""" ⏱️ Uptime: {uptime}
193
+ """
194
+
195
+ message += "\n"
196
+
197
+ if endpoints:
198
+ message += f"""**🎯 Endpoints:**
199
+ """
200
+ for endpoint in endpoints:
201
+ endpoint_id = endpoint.get("id", "Unknown")
202
+ public_url = endpoint.get("public_url", "N/A")
203
+ proto = endpoint.get("proto", "tcp") # Default to tcp if not specified
204
+ created_at = endpoint.get("created_at", "")
205
+
206
+ # Format URL without protocol and use code markdown
207
+ formatted_url = self._format_url(public_url)
208
+
209
+ # Consistent formatting - always show uptime structure for endpoints
210
+ if created_at and formatted_url != "N/A":
211
+ uptime = self._calculate_uptime(created_at)
212
+ message += f"""β€’ {endpoint_id} ({proto})
213
+ `{formatted_url}`
214
+ ⏱️ Uptime: {uptime}
215
+
216
+ """
217
+ elif formatted_url != "N/A":
218
+ message += f"""β€’ {endpoint_id} ({proto})
219
+ `{formatted_url}`
220
+
221
+ """
222
+ else:
223
+ message += f"""β€’ {endpoint_id} ({proto})
224
+ `N/A`
225
+
226
+ """
227
+
228
+ # Add relative time since last refresh
229
+ message += f"""πŸ• **Updated:** {time_since_refresh}"""
230
+
231
+ return message
232
+
233
+ def is_message_different(self, new_message: str) -> bool:
234
+ """Check if the new message is different from the last one"""
235
+ message_hash = hash(new_message)
236
+ if self._last_message_hash != message_hash:
237
+ self._last_message_hash = message_hash
238
+ return True
239
+ return False
240
+
241
+ def is_configured(self) -> bool:
242
+ """Check if API key is configured"""
243
+ return bool(self.api_key)
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core FastAPI and server dependencies
2
+ fastapi==0.104.1
3
+ uvicorn[standard]==0.24.0
4
+
5
+ # Telegram bot dependencies
6
+ pyrogram==2.0.106
7
+ tgcrypto==1.2.5
8
+
9
+ # HTTP client for API calls
10
+ httpx==0.25.2
11
+
12
+ # Environment and configuration
13
+ python-dotenv==1.0.0
test_deployment.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Test script to verify the FastAPI Telegram Bot deployment
4
+ """
5
+ import httpx
6
+ import sys
7
+
8
+ def test_health_endpoint():
9
+ """Test the health check endpoint"""
10
+ try:
11
+ response = httpx.get('http://localhost:7860/health', timeout=10)
12
+ if response.status_code == 200:
13
+ data = response.json()
14
+ print("βœ… Health Check: PASSED")
15
+ print(f" Status: {data.get('status')}")
16
+ print(f" Message: {data.get('message')}")
17
+ return True
18
+ else:
19
+ print(f"❌ Health Check: FAILED (Status: {response.status_code})")
20
+ return False
21
+ except Exception as e:
22
+ print(f"❌ Health Check: FAILED (Error: {e})")
23
+ return False
24
+
25
+ def test_sendmessage_endpoint():
26
+ """Test the sendmessage endpoint (will fail with invalid chat ID, but shows it's working)"""
27
+ try:
28
+ response = httpx.get('http://localhost:7860/sendmessage?log=123456789&msg=Test', timeout=10)
29
+ if response.status_code == 500 and "PEER_ID_INVALID" in response.text:
30
+ print("βœ… SendMessage Endpoint: WORKING (Expected error with invalid chat ID)")
31
+ return True
32
+ elif response.status_code == 200:
33
+ print("βœ… SendMessage Endpoint: WORKING (Message sent successfully)")
34
+ return True
35
+ else:
36
+ print(f"❌ SendMessage Endpoint: UNEXPECTED RESPONSE (Status: {response.status_code})")
37
+ print(f" Response: {response.text}")
38
+ return False
39
+ except Exception as e:
40
+ print(f"❌ SendMessage Endpoint: FAILED (Error: {e})")
41
+ return False
42
+
43
+ def main():
44
+ print("πŸš€ Testing FastAPI Telegram Bot Deployment")
45
+ print("=" * 50)
46
+
47
+ health_ok = test_health_endpoint()
48
+ sendmsg_ok = test_sendmessage_endpoint()
49
+
50
+ print("\n" + "=" * 50)
51
+ if health_ok and sendmsg_ok:
52
+ print("πŸŽ‰ DEPLOYMENT TEST: ALL PASSED")
53
+ print("\nYour FastAPI Telegram Bot is ready for production!")
54
+ print("\nNext steps:")
55
+ print("1. Test your bot by sending /start to it on Telegram")
56
+ print("2. Use the /sendmessage API with real chat IDs")
57
+ print("3. Monitor logs with: docker-compose logs -f")
58
+ sys.exit(0)
59
+ else:
60
+ print("❌ DEPLOYMENT TEST: SOME TESTS FAILED")
61
+ sys.exit(1)
62
+
63
+ if __name__ == "__main__":
64
+ main()