Skip to content

Commit da513a9

Browse files
committed
feat(bot): show marzneshin synced user in telegram bot
1 parent ae8cbdc commit da513a9

1 file changed

Lines changed: 29 additions & 5 deletions

File tree

app/telegram_bot/__init__.py

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
21
import asyncio
32
import ipaddress
3+
import logging
44
from telegram import Update
55
from telegram.ext import (
66
ApplicationBuilder,
@@ -11,12 +11,16 @@
1111
filters,
1212
CallbackQueryHandler
1313
)
14-
from app.config import TELEGRAM_API_TOKEN
14+
from app.config import TELEGRAM_API_TOKEN, SYNC_WITH_PANEL, PANEL_USERNAME, PANEL_PASSWORD, PANEL_ADDRESS
1515
from app import user_limit_db, storage
1616
from app.db.models import UserLimit
1717
from app.models.user import User
18+
from app.models.panel import Panel
1819
from app.nobetnode import nodes
1920
from app.utils.telegram import restricted
21+
from app.db.marzneshin_db import MarzneshinDB
22+
23+
logger = logging.getLogger(__name__)
2024

2125
(
2226
ADD_USER_NAME,
@@ -28,6 +32,14 @@
2832
ACTIVE_IPS_USER_NAME
2933
) = range(7)
3034

35+
sync_db_instance = None
36+
if SYNC_WITH_PANEL:
37+
try:
38+
_panel = Panel(username=PANEL_USERNAME, password=PANEL_PASSWORD, domain=PANEL_ADDRESS)
39+
sync_db_instance = MarzneshinDB(_panel)
40+
except Exception as e:
41+
logger.error(f"Failed to initialize MarzneshinDB adapter: {e}")
42+
3143

3244
async def build_telegram_bot():
3345
if not TELEGRAM_API_TOKEN or not (application := ApplicationBuilder().token(TELEGRAM_API_TOKEN).build()):
@@ -136,11 +148,23 @@ async def get_user(update: Update, _context: ContextTypes.DEFAULT_TYPE):
136148

137149
@restricted
138150
async def get_user_name(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
139-
context.user_data["name"] = update.message.text.strip()
151+
username = update.message.text.strip()
152+
context.user_data["name"] = username
153+
154+
user = None
155+
156+
if SYNC_WITH_PANEL and sync_db_instance:
157+
try:
158+
user = await sync_db_instance.get(UserLimit.name == username)
159+
except Exception:
160+
pass
140161

141-
user = user_limit_db.get(UserLimit.name == context.user_data["name"])
162+
if not user or (SYNC_WITH_PANEL and user.limit == 0):
163+
local_user = user_limit_db.get(UserLimit.name == username)
164+
if local_user:
165+
user = local_user
142166

143-
if not user:
167+
if not user or (user.limit == 0 and not user_limit_db.get(UserLimit.name == username)):
144168
await context.bot.send_message(
145169
chat_id=update.effective_chat.id,
146170
text="User Isn't Exists"

0 commit comments

Comments
 (0)