-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbot.py
More file actions
657 lines (597 loc) · 33.1 KB
/
Copy pathbot.py
File metadata and controls
657 lines (597 loc) · 33.1 KB
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
import asyncio
import base64
import aiohttp
import datetime
from functools import wraps
from pyrogram import filters
from pyrogram.types import (
Message,
InlineKeyboardMarkup,
InlineKeyboardButton,
CallbackQuery
)
from pyrogram.enums import ParseMode
from pyrogram.errors import (
UserIdInvalid,
UsernameNotOccupied,
MessageNotModified
)
from pymongo.errors import ConnectionFailure
from config import ADMIN_IDS
from core import (
users_collection,
numbers_collection,
authorized_users_collection
)
from utils import LOGGER
from app import bot
# Load authorized users from MongoDB
def load_authorized_users():
authorized_users = set()
try:
for user in authorized_users_collection.find():
if "user_id" in user:
authorized_users.add(user["user_id"])
else:
LOGGER.warning(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - WARNING - Skipping invalid authorized user document: {user}")
except ConnectionFailure:
LOGGER.error(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - ERROR - Failed to connect to MongoDB")
return authorized_users
# Save authorized user to MongoDB
def auth_user(user_id):
authorized_users_collection.update_one(
{"user_id": user_id},
{"$set": {"user_id": user_id}},
upsert=True
)
LOGGER.info(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - INFO - Authorized user_id {user_id}")
# Remove authorized user from MongoDB
def unauth_user(user_id):
authorized_users_collection.delete_one({"user_id": user_id})
LOGGER.info(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - INFO - Unauthorized user_id {user_id}")
# Load data from MongoDB
def load_data():
twilio_users = {}
twilio_numbers = {}
try:
for user in users_collection.find():
if "user_id" in user and "sid" in user and "token" in user:
twilio_users[user["user_id"]] = (user["sid"], user["token"])
else:
LOGGER.warning(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - WARNING - Skipping invalid user document: {user}")
for number in numbers_collection.find():
if "user_id" in number and "numbers" in number:
twilio_numbers[number["user_id"]] = number["numbers"]
else:
LOGGER.warning(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - WARNING - Skipping invalid numbers document: {number}")
except ConnectionFailure:
LOGGER.error(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - ERROR - Failed to connect to MongoDB")
return twilio_users, twilio_numbers
# Save data to MongoDB
def save_user(user_id, sid, token):
if not sid or not token:
LOGGER.error(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - ERROR - Attempted to save invalid SID or token for user_id {user_id}")
return
users_collection.update_one(
{"user_id": user_id},
{"$set": {"user_id": user_id, "sid": sid, "token": token}},
upsert=True
)
LOGGER.info(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - INFO - Saved user data for user_id {user_id}")
def save_numbers(user_id, numbers):
numbers_collection.update_one(
{"user_id": user_id},
{"$set": {"user_id": user_id, "numbers": numbers}},
upsert=True
)
LOGGER.info(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - INFO - Saved numbers for user_id {user_id}")
def delete_user_data(user_id):
users_collection.delete_one({"user_id": user_id})
numbers_collection.delete_one({"user_id": user_id})
LOGGER.info(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - INFO - Deleted data for user_id {user_id}")
twilio_users, twilio_numbers = load_data()
authorized_users = load_authorized_users()
# Helper function to resolve username or user ID to user ID
async def resolve_identifier(client, identifier):
try:
if identifier.startswith("@"):
username = identifier[1:] # Remove "@"
user = await client.get_users(username)
LOGGER.info(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - INFO - Resolved username {identifier} to user_id {user.id}")
return user.id
else:
user_id = int(identifier)
return user_id
except (UserIdInvalid, UsernameNotOccupied, ValueError) as e:
LOGGER.error(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - ERROR - Failed to resolve identifier {identifier}: {str(e)}")
return None
# Decorator to restrict commands to authorized users or admins
def restrict_to_authorized(func):
@wraps(func)
async def wrapper(client, message: Message, *args, **kwargs):
user_id = message.from_user.id
if user_id in ADMIN_IDS or user_id in authorized_users:
return await func(client, message, *args, **kwargs)
else:
buttons = [[InlineKeyboardButton("Contact Owner", user_id=5991909954)]]
await client.send_message(
message.chat.id,
"**Sorry Bro Unauthorized User Kindly Contact @Ruhulxr For Auth**",
reply_markup=InlineKeyboardMarkup(buttons),
parse_mode=ParseMode.MARKDOWN
)
return wrapper
@bot.on_message(filters.command("auth") & filters.user(ADMIN_IDS))
async def auth_command(client, message: Message):
try:
_, identifier = message.text.split(maxsplit=1)
except ValueError:
await client.send_message(
message.chat.id,
"**✘《 Error ↯ 》 Usage: /auth <useridOrusername>**",
parse_mode=ParseMode.MARKDOWN
)
return
user_id = await resolve_identifier(client, identifier)
if user_id is None:
await client.send_message(
message.chat.id,
"**✘《 Error ↯ 》 Invalid user ID or username**",
parse_mode=ParseMode.MARKDOWN
)
return
if user_id in authorized_users:
await client.send_message(
message.chat.id,
f"**✘《 Error ↯ 》 User ID {user_id} is already authorized**",
parse_mode=ParseMode.MARKDOWN
)
return
authorized_users.add(user_id)
auth_user(user_id)
await client.send_message(
message.chat.id,
f"**✘《 Success ↯ 》 User ID {user_id} has been authorized**",
parse_mode=ParseMode.MARKDOWN
)
@bot.on_message(filters.command("unauth") & filters.user(ADMIN_IDS))
async def unauth_command(client, message: Message):
try:
_, identifier = message.text.split(maxsplit=1)
except ValueError:
await client.send_message(
message.chat.id,
"**✘《 Error ↯ 》 Usage: /unauth <useridOrusername>**",
parse_mode=ParseMode.MARKDOWN
)
return
user_id = await resolve_identifier(client, identifier)
if user_id is None:
await client.send_message(
message.chat.id,
"**✘《 Error ↯ 》 Invalid user ID or username**",
parse_mode=ParseMode.MARKDOWN
)
return
if user_id not in authorized_users:
await client.send_message(
message.chat.id,
f"**✘《 Error ↯ 》 User ID {user_id} is not authorized**",
parse_mode=ParseMode.MARKDOWN
)
return
authorized_users.remove(user_id)
unauth_user(user_id)
await client.send_message(
message.chat.id,
f"**✘《 Success ↯ 》 User ID {user_id} has been unauthorized**",
parse_mode=ParseMode.MARKDOWN
)
@bot.on_message(filters.command("start"))
@restrict_to_authorized
async def start(client, message: Message):
full_name = message.from_user.first_name
if message.from_user.last_name:
full_name += f" {message.from_user.last_name}"
text = (
f"**Hello, {full_name}! Welcome to the Twilio Bot!**\n\n"
"Here, you can easily purchase numbers and retrieve OTPs to create WhatsApp or Telegram accounts. Follow the commands below to get started:\n\n"
"**/login <SID> <TOKEN>** - Log in to your Twilio account\n"
"**/buy** - Purchase available numbers\n"
"**/get** - Retrieve OTP messages\n"
"**/del <PhoneNumber>** - Delete a purchased number\n"
"**/my** - List your active numbers\n"
"**/logout** - Log out from your Twilio account\n\n"
"**Support: @TheSmartDev**"
)
buttons = [
[
InlineKeyboardButton("✘《 Updates ↯ 》", url="t.me/TheSmartDev"),
InlineKeyboardButton("✘《 Dev ↯ 》", user_id=7303810912)
]
]
await client.send_message(
message.chat.id,
text,
reply_markup=InlineKeyboardMarkup(buttons),
parse_mode=ParseMode.MARKDOWN
)
@bot.on_message(filters.command("login"))
@restrict_to_authorized
async def login(client, message: Message):
loading_message = await client.send_message(message.chat.id, "**✘《 Loading ↯ 》 Processing login...**", parse_mode=ParseMode.MARKDOWN)
try:
parts = message.text.split()
if len(parts) != 3:
raise ValueError("Invalid format")
_, sid, token = parts
if not sid.startswith("AC") or len(token) < 32:
raise ValueError("Invalid SID or token format")
except ValueError:
await client.edit_message_text(message.chat.id, loading_message.id, "**✘《 Error ↯ 》 Usage: /login <SID> <TOKEN>**", parse_mode=ParseMode.MARKDOWN)
return
headers = {
"Authorization": "Basic " + base64.b64encode(f"{sid}:{token}".encode()).decode()
}
async with aiohttp.ClientSession() as session:
try:
async with session.get(f"https://api.twilio.com/2010-04-01/Accounts/{sid}.json", headers=headers) as resp:
response_text = await resp.text()
LOGGER.info(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - INFO - Login API response for user_id {message.from_user.id}: Status {resp.status}, Response {response_text}")
if resp.status == 200:
twilio_users[message.from_user.id] = (sid, token)
twilio_numbers.setdefault(message.from_user.id, [])
save_user(message.from_user.id, sid, token)
save_numbers(message.from_user.id, twilio_numbers[message.from_user.id])
await client.edit_message_text(message.chat.id, loading_message.id, "**✘《 Success ↯ 》 Login successful**", parse_mode=ParseMode.MARKDOWN)
else:
error_message = f"**✘《 Error ↯ 》 Login failed. Check your SID/TOKEN.**\nDetails: HTTP {resp.status}"
try:
error_data = await resp.json()
error_message += f" - {error_data.get('message', 'Unknown error')}"
except ValueError:
error_message += f" - {response_text}"
await client.edit_message_text(message.chat.id, loading_message.id, error_message, parse_mode=ParseMode.MARKDOWN)
except aiohttp.ClientError as e:
LOGGER.error(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - ERROR - Network error during login for user_id {message.from_user.id}: {str(e)}")
await client.edit_message_text(message.chat.id, loading_message.id, "**✘《 Error ↯ 》 Network error during login. Please try again.**", parse_mode=ParseMode.MARKDOWN)
@bot.on_message(filters.command("logout"))
@restrict_to_authorized
async def logout(client, message: Message):
user_id = message.from_user.id
loading_message = await client.send_message(message.chat.id, "**✘《 Loading ↯ 》 Processing logout...**", parse_mode=ParseMode.MARKDOWN)
if user_id in twilio_users:
del twilio_users[user_id]
if user_id in twilio_numbers:
del twilio_numbers[user_id]
delete_user_data(user_id)
await client.edit_message_text(message.chat.id, loading_message.id, "**✘《 Success ↯ 》 Logout successful**", parse_mode=ParseMode.MARKDOWN)
else:
await client.edit_message_text(message.chat.id, loading_message.id, "**✘《 Error ↯ 》 You are not logged in**", parse_mode=ParseMode.MARKDOWN)
@bot.on_message(filters.command("buy"))
@restrict_to_authorized
async def buy_numbers(client, message: Message):
user_id = message.from_user.id
if user_id not in twilio_users:
await client.send_message(message.chat.id, "**✘《 Error ↯ 》 Log in first using /login**", parse_mode=ParseMode.MARKDOWN)
return
buttons = [
[
InlineKeyboardButton("US 🇺🇸", callback_data="country_US"),
InlineKeyboardButton("CA 🇨🇦", callback_data="country_CA")
],
[
InlineKeyboardButton("PR 🇵🇷", callback_data="country_PR")
]
]
await client.send_message(
message.chat.id,
"**✘《 Kindly Choose The Country You Prefer ↯ 》**",
reply_markup=InlineKeyboardMarkup(buttons),
parse_mode=ParseMode.MARKDOWN
)
async def fetch_numbers(client, message: Message, user_id, country_code, custom_prefix=None):
loading_message = await client.send_message(message.chat.id, f"**✘《 Loading ↯ 》 Fetching {country_code} numbers...**", parse_mode=ParseMode.MARKDOWN)
sid, token = twilio_users[user_id]
headers = {
"Authorization": "Basic " + base64.b64encode(f"{sid}:{token}".encode()).decode()
}
url = f"https://api.twilio.com/2010-04-01/Accounts/{sid}/AvailablePhoneNumbers/{country_code}/Local.json?PageSize=10"
if custom_prefix:
if country_code == "PR":
url += f"&AreaCode=787"
else:
url += f"&AreaCode={custom_prefix}"
async with aiohttp.ClientSession() as session:
try:
async with session.get(url, headers=headers) as resp:
response_text = await resp.text()
LOGGER.info(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - INFO - Fetch numbers API response for user_id {user_id}: Status {resp.status}, Response {response_text}")
if resp.status != 200:
error_message = f"**✘《 Error ↯ 》 Failed to fetch {country_code} numbers.**\nDetails: HTTP {resp.status}"
try:
error_data = await resp.json()
error_message += f" - {error_data.get('message', 'Unknown error')}"
except ValueError:
error_message += f" - {response_text}"
await client.edit_message_text(message.chat.id, loading_message.id, error_message, parse_mode=ParseMode.MARKDOWN)
return
data = await resp.json()
numbers = data.get("available_phone_numbers", [])
if country_code == "CA":
numbers = [num for num in numbers if num['phone_number'].startswith('+1')]
if not numbers:
error_message = f"**✘《 Error ↯ 》 No available {country_code} numbers{' with area code ' + custom_prefix if custom_prefix else ''}**"
await client.edit_message_text(message.chat.id, loading_message.id, error_message, parse_mode=ParseMode.MARKDOWN)
return
# Filter numbers by custom prefix if provided
if custom_prefix and country_code != "PR":
numbers = [num for num in numbers if num['phone_number'].startswith(f'+1{custom_prefix}')]
elif custom_prefix and country_code == "PR":
numbers = [num for num in numbers if num['phone_number'].startswith('+1787')]
if not numbers:
error_message = f"**✘《 Error ↯ 》 No available {country_code} numbers with area code {custom_prefix}**"
await client.edit_message_text(message.chat.id, loading_message.id, error_message, parse_mode=ParseMode.MARKDOWN)
return
# Filter out already owned numbers
owned_numbers = twilio_numbers.get(user_id, [])
numbers = [num for num in numbers if num['phone_number'] not in owned_numbers]
if not numbers:
error_message = f"**✘《 Error ↯ 》 All available {country_code} numbers{' with area code ' + custom_prefix if custom_prefix else ''} are already owned**"
await client.edit_message_text(message.chat.id, loading_message.id, error_message, parse_mode=ParseMode.MARKDOWN)
return
numbers_list = "\n".join(num['phone_number'] for num in numbers)
message_text = f"**Available {country_code} Numbers{' with area code ' + custom_prefix if custom_prefix else ''}:**\n{numbers_list}\n\n**Select a number to purchase:**"
buttons = []
row = []
for i, num in enumerate(numbers):
phone = num['phone_number']
row.append(InlineKeyboardButton(phone, callback_data=f"buy_{phone}"))
if len(row) == 2:
buttons.append(row)
row = []
if row:
buttons.append(row)
try:
await client.edit_message_text(
message.chat.id,
loading_message.id,
message_text,
reply_markup=InlineKeyboardMarkup(buttons),
parse_mode=ParseMode.MARKDOWN
)
except MessageNotModified:
LOGGER.debug(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - DEBUG - Message not modified for fetch_numbers, user_id {user_id}")
except aiohttp.ClientError as e:
LOGGER.error(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - ERROR - Network error during fetch_numbers for user_id {user_id}: {str(e)}")
await client.edit_message_text(message.chat.id, loading_message.id, "**✘《 Error ↯ 》 Network error while fetching numbers. Please try again.**", parse_mode=ParseMode.MARKDOWN)
@bot.on_message(filters.regex(r"^[0-9]{3}$") & filters.reply)
@restrict_to_authorized
async def handle_custom_area_code(client, message: Message):
user_id = message.from_user.id
if user_id not in twilio_users:
await client.send_message(message.chat.id, "**✘《 Error ↯ 》 Log in first using /login**", parse_mode=ParseMode.MARKDOWN)
return
area_code = message.text.strip()
if message.reply_to_message and message.reply_to_message.text:
if "Enter your preferred 3-digit area code for" in message.reply_to_message.text:
country_code = message.reply_to_message.text.split("for ")[-1].split(" ")[0]
await fetch_numbers(client, message, user_id, country_code, custom_prefix=area_code)
return
await client.send_message(message.chat.id, "**✘《 Error ↯ 》 Please select a country first and reply to the area code prompt**", parse_mode=ParseMode.MARKDOWN)
@bot.on_callback_query()
async def handle_callbacks(client, callback_query: CallbackQuery):
user_id = callback_query.from_user.id
if user_id not in twilio_users and user_id not in ADMIN_IDS and user_id not in authorized_users:
await callback_query.answer("Please log in first and ensure you are authorized.", show_alert=True)
return
data = callback_query.data
if data.startswith("country_"):
country_code = data.split("_")[1]
buttons = [
[
InlineKeyboardButton("✘《 Yes ↯ 》", callback_data=f"custom_{country_code}"),
InlineKeyboardButton("✘《 No ↯ 》", callback_data=f"all_{country_code}")
]
]
try:
await client.edit_message_text(
callback_query.message.chat.id,
callback_query.message.id,
"**✘《 Do You Prefer Custom Area Code ↯ 》**",
reply_markup=InlineKeyboardMarkup(buttons),
parse_mode=ParseMode.MARKDOWN
)
except MessageNotModified:
LOGGER.debug(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - DEBUG - Message not modified for country selection, user_id {user_id}")
await callback_query.answer()
elif data.startswith("all_"):
country_code = data.split("_")[1]
await fetch_numbers(client, callback_query.message, user_id, country_code)
await callback_query.answer()
elif data.startswith("custom_"):
country_code = data.split("_")[1]
try:
await callback_query.message.reply(f"**Enter your preferred 3-digit area code for {country_code} (e.g., 592):**", parse_mode=ParseMode.MARKDOWN)
except Exception as e:
LOGGER.error(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - ERROR - Failed to send area code prompt for user_id {user_id}: {str(e)}")
await client.send_message(callback_query.message.chat.id, "**✘《 Error ↯ 》 Failed to prompt for area code. Please try again.**", parse_mode=ParseMode.MARKDOWN)
await callback_query.answer()
elif data.startswith("buy_"):
phone = data.replace("buy_", "")
if phone in twilio_numbers.get(user_id, []):
await callback_query.answer(f"Number {phone} is already owned by you.", show_alert=True)
return
sid, token = twilio_users[user_id]
loading_message = await client.send_message(
callback_query.message.chat.id,
f"**✘《 Loading ↯ 》 Purchasing number `{phone}`...**",
parse_mode=ParseMode.MARKDOWN
)
headers = {
"Authorization": "Basic " + base64.b64encode(f"{sid}:{token}".encode()).decode(),
"Content-Type": "application/x-www-form-urlencoded"
}
data = {
"PhoneNumber": phone,
"SmsEnabled": "true" # Ensure SMS capability for OTP
}
async with aiohttp.ClientSession() as session:
try:
async with session.post(
f"https://api.twilio.com/2010-04-01/Accounts/{sid}/IncomingPhoneNumbers.json",
headers=headers,
data=data
) as resp:
response_text = await resp.text()
LOGGER.info(
f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - INFO - "
f"Purchase number API response for user_id {user_id}: Status {resp.status}, Response {response_text}"
)
if resp.status == 201:
twilio_numbers.setdefault(user_id, []).append(phone)
save_numbers(user_id, twilio_numbers[user_id])
await client.edit_message_text(
callback_query.message.chat.id,
loading_message.id,
f"**✘《 Success ↯ 》 Number purchased: `{phone}`**",
parse_mode=ParseMode.MARKDOWN
)
else:
error_message = f"**✘《 Error ↯ 》 Failed to purchase number: `{phone}`**"
try:
error_data = await resp.json()
error_message += f"\nDetails: {error_data.get('message', 'Unknown error')}"
except ValueError:
error_message += f"\nDetails: HTTP {resp.status} - {response_text}"
await client.edit_message_text(
callback_query.message.chat.id,
loading_message.id,
error_message,
parse_mode=ParseMode.MARKDOWN
)
except aiohttp.ClientError as e:
LOGGER.error(
f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - ERROR - "
f"Network error during number purchase for user_id {user_id}: {str(e)}"
)
await client.edit_message_text(
callback_query.message.chat.id,
loading_message.id,
f"**✘《 Error ↯ 》 Network error while purchasing `{phone}`. Please try again.**",
parse_mode=ParseMode.MARKDOWN
)
await callback_query.answer()
@bot.on_message(filters.command("my"))
@restrict_to_authorized
async def my_numbers(client, message: Message):
user_id = message.from_user.id
loading_message = await client.send_message(message.chat.id, "**✘《 Loading ↯ 》 Fetching your numbers...**", parse_mode=ParseMode.MARKDOWN)
nums = twilio_numbers.get(user_id, [])
if not nums:
await client.edit_message_text(message.chat.id, loading_message.id, "**✘《 Error ↯ 》 No numbers found**", parse_mode=ParseMode.MARKDOWN)
return
text = "**Your Active Numbers:**\n\n" + "\n".join(num for num in nums)
try:
await client.edit_message_text(message.chat.id, loading_message.id, text, parse_mode=ParseMode.MARKDOWN)
except MessageNotModified:
LOGGER.debug(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - DEBUG - Message not modified for my_numbers, user_id {user_id}")
@bot.on_message(filters.command("del"))
@restrict_to_authorized
async def delete_number(client, message: Message):
user_id = message.from_user.id
if user_id not in twilio_users:
await client.send_message(message.chat.id, "**✘《 Error ↯ 》 Log in first using /login**", parse_mode=ParseMode.MARKDOWN)
return
try:
_, number = message.text.split()
except ValueError:
await client.send_message(message.chat.id, "**✘《 Error ↯ 》 Usage: /del <PhoneNumber>**", parse_mode=ParseMode.MARKDOWN)
return
loading_message = await client.send_message(message.chat.id, f"**✘《 Loading ↯ 》 Deleting number `{number}`...**", parse_mode=ParseMode.MARKDOWN)
sid, token = twilio_users[user_id]
headers = {
"Authorization": "Basic " + base64.b64encode(f"{sid}:{token}".encode()).decode()
}
async with aiohttp.ClientSession() as session:
try:
async with session.get(f"https://api.twilio.com/2010-04-01/Accounts/{sid}/IncomingPhoneNumbers.json", headers=headers) as resp:
response_text = await resp.text()
LOGGER.info(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - INFO - Fetch incoming numbers API response for user_id {user_id}: Status {resp.status}, Response {response_text}")
if resp.status != 200:
error_message = f"**✘《 Error ↯ 》 Failed to fetch numbers.**\nDetails: HTTP {resp.status}"
try:
error_data = await resp.json()
error_message += f" - {error_data.get('message', 'Unknown error')}"
except ValueError:
error_message += f" - {response_text}"
await client.edit_message_text(message.chat.id, loading_message.id, error_message, parse_mode=ParseMode.MARKDOWN)
return
data = await resp.json()
for record in data.get("incoming_phone_numbers", []):
if record.get("phone_number") == number:
sid_to_delete = record.get("sid")
del_url = f"https://api.twilio.com/2010-04-01/Accounts/{sid}/IncomingPhoneNumbers/{sid_to_delete}.json"
async with session.delete(del_url, headers=headers) as del_resp:
del_response_text = await del_resp.text()
LOGGER.info(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - INFO - Delete number API response for user_id {user_id}: Status {del_resp.status}, Response {del_response_text}")
if del_resp.status == 204:
twilio_numbers[user_id].remove(number)
save_numbers(user_id, twilio_numbers[user_id])
await client.edit_message_text(message.chat.id, loading_message.id, f"**✘《 Success ↯ 》 Number deleted: `{number}`**", parse_mode=ParseMode.MARKDOWN)
return
else:
error_message = f"**✘《 Error ↯ 》 Failed to delete number: `{number}`**"
try:
error_data = await del_resp.json()
error_message += f"\nDetails: {error_data.get('message', 'Unknown error')}"
except ValueError:
error_message += f"\nDetails: HTTP {del_resp.status} - {del_response_text}"
await client.edit_message_text(message.chat.id, loading_message.id, error_message, parse_mode=ParseMode.MARKDOWN)
return
await client.edit_message_text(message.chat.id, loading_message.id, "**✘《 Error ↯ 》 Number not found in your account**", parse_mode=ParseMode.MARKDOWN)
except aiohttp.ClientError as e:
LOGGER.error(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - ERROR - Network error during delete_number for user_id {user_id}: {str(e)}")
await client.edit_message_text(message.chat.id, loading_message.id, "**✘《 Error ↯ 》 Network error while deleting number. Please try again.**", parse_mode=ParseMode.MARKDOWN)
@bot.on_message(filters.command("get"))
@restrict_to_authorized
async def get_otp(client, message: Message):
user_id = message.from_user.id
if user_id not in twilio_users:
await client.send_message(message.chat.id, "**✘《 Error ↯ 》 Login required. Use /login**", parse_mode=ParseMode.MARKDOWN)
return
loading_message = await client.send_message(message.chat.id, "**✘《 Loading ↯ 》 Fetching OTP messages...**", parse_mode=ParseMode.MARKDOWN)
sid, token = twilio_users[user_id]
headers = {
"Authorization": "Basic " + base64.b64encode(f"{sid}:{token}".encode()).decode()
}
url = f"https://api.twilio.com/2010-04-01/Accounts/{sid}/Messages.json?PageSize=10"
async with aiohttp.ClientSession() as session:
try:
async with session.get(url, headers=headers) as resp:
response_text = await resp.text()
LOGGER.info(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - INFO - Fetch OTP messages API response for user_id {user_id}: Status {resp.status}, Response {response_text}")
if resp.status != 200:
error_message = f"**✘《 Error ↯ 》 Failed to fetch messages.**\nDetails: HTTP {resp.status}"
try:
error_data = await resp.json()
error_message += f" - {error_data.get('message', 'Unknown error')}"
except ValueError:
error_message += f" - {response_text}"
await client.edit_message_text(message.chat.id, loading_message.id, error_message, parse_mode=ParseMode.MARKDOWN)
return
data = await resp.json()
messages = data.get("messages", [])
if not messages:
await client.edit_message_text(message.chat.id, loading_message.id, "**✘《 Error ↯ 》 No messages found**", parse_mode=ParseMode.MARKDOWN)
return
text = "**Latest OTP Messages:**\n\n"
for msg in messages:
if msg.get("direction") == "inbound":
text += f"{msg.get('from')} -> {msg.get('body')}\n"
await client.edit_message_text(message.chat.id, loading_message.id, text or "**✘《 Error ↯ 》 No OTPs found**", parse_mode=ParseMode.MARKDOWN)
except aiohttp.ClientError as e:
LOGGER.error(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - ERROR - Network error during get_otp for user_id {user_id}: {str(e)}")
await client.edit_message_text(message.chat.id, loading_message.id, "**✘《 Error ↯ 》 Network error while fetching OTPs. Please try again.**", parse_mode=ParseMode.MARKDOWN)
LOGGER.info(f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - INFO - Bot Successfully Started! 💥")
bot.run()