-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.py
1703 lines (1319 loc) · 78.3 KB
/
main.py
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from typing import Optional
import telebot
import openai
from openai import OpenAI
from dotenv.main import load_dotenv
import json
import os
from datetime import datetime, timedelta
import time
from pydub import AudioSegment
from telebot.util import extract_arguments, extract_command
from telebot import types
import base64
import requests
DEFAULT_MODEL = "gpt-3.5-turbo-0125" # 16k
PREMIUM_MODEL = "gpt-4o" # 128k tokens context window
MAX_REQUEST_TOKENS = 4000 # max output tokens for one request (not including input tokens)
DEFAULT_SYSTEM_PROMPT = "You are a helpful assistant named Магдыч."
# Актуальные цены можно взять с сайта https://openai.com/pricing
PRICE_1K = 0.0015 # price per 1k tokens in USD
PREMIUM_PRICE_1K = 0.015 # price per 1k tokens in USD for premium model
IMAGE_PRICE = 0.08 # price per generated image in USD
WHISPER_MIN_PRICE = 0.006 # price per 1 minute of audio transcription in USD
DATE_FORMAT = "%d.%m.%Y %H:%M:%S" # date format for logging
UTC_HOURS_DELTA = 3 # time difference between server and local time in hours (UTC +3)
NEW_USER_BALANCE = 30000 # balance for new users
REFERRAL_BONUS = 20000 # bonus for inviting a new user
FAVOR_AMOUNT = 30000 # amount of tokens per granted favor
FAVOR_MIN_LIMIT = 10000 # minimum balance to ask for a favor
# load .env file with secrets
load_dotenv()
# Load OpenAI API credentials from .env file
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
# Create a new Telebot instance
bot = telebot.TeleBot(os.getenv("TELEGRAM_API_KEY"))
# Получаем айди админа, которому в лс будут приходить логи
ADMIN_ID = int(os.getenv("ADMIN_ID"))
# File with users and global token usage data
DATAFILE = "data.json"
BACKUPFILE = "data-backup.json"
# Default values for new users, who are not in the data file
DEFAULT_NEW_USER_DATA = {"requests": 0, "tokens": 0, "balance": NEW_USER_BALANCE,
"name": "None", "username": "None", "lastdate": "01.01.1990 00:00:00"}
"""======================FUNCTIONS======================="""
# Function to check if the user is in the data file
def is_user_exists(user_id: int) -> bool:
if user_id in data:
return True
else:
return False
# Function to check if the user is in the blacklist
def is_user_blacklisted(user_id: int) -> bool:
if user_id in data and "blacklist" in data[user_id]:
return data[user_id]["blacklist"]
else:
return False
# Function to add new user to the data file
def add_new_user(user_id: int, name: str, username: str, referrer=None) -> None:
data[user_id] = DEFAULT_NEW_USER_DATA.copy()
data[user_id]["name"] = name
if username is not None:
data[user_id]["username"] = '@'+username
else:
data[user_id]["username"] = "None"
if referrer is not None:
data[user_id]["balance"] += REFERRAL_BONUS
data[user_id]["ref_id"] = referrer
# Function to update the JSON file with relevant data
def update_json_file(new_data, file_name=DATAFILE) -> None:
with open(file_name, "w", encoding='utf-8') as file:
json.dump(new_data, file, ensure_ascii=False, indent=4)
# Function to get user_id by username
def get_user_id_by_username(username: str) -> Optional[int]:
for user_id in list(data.keys())[1:]:
if data[user_id]["username"] == username:
return user_id
return None
# Function to get the user's prompt
def get_user_prompt(user_id: int) -> str:
"""
This function returns the user's prompt from the data file if it exists, otherwise it returns the default system prompt.
:param user_id: The user's ID
:type user_id: int
:return: The user's prompt
:rtype: str
"""
if data[user_id].get("prompt") is None:
return DEFAULT_SYSTEM_PROMPT
else:
return str(data[user_id]["prompt"])
# Function to call the OpenAI API and get the response
def get_chatgpt_response(user_request: str, lang_model=DEFAULT_MODEL, prev_answer=None, system_prompt=DEFAULT_SYSTEM_PROMPT):
messages = [{"role": "system", "content": system_prompt}]
if prev_answer is not None:
messages.extend([{"role": "assistant", "content": prev_answer},
{"role": "user", "content": user_request}])
# print("\nЗапрос с контекстом 🤩")
else:
messages.append({"role": "user", "content": user_request})
# print("\nЗапрос без контекста")
return client.chat.completions.create(
model=lang_model,
max_tokens=MAX_REQUEST_TOKENS,
messages=messages
)
# Function to generate image with OpenAI API
def generate_image(image_prompt, model="dall-e-3"):
response = client.images.generate(
model=model,
prompt=image_prompt,
size="1024x1024",
quality="hd" # hd and standard, hd costs x2
)
return response
# Function to encode the image
def encode_image_b64(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
# Функция, которая получает на вход путь к картинке, декодирует ее в base64, отправляет по API в OpenAI и возвращает ответ
def get_openai_image_recognition_response(image_path: str, user_request: str, max_output_tokens: int = 1000) -> dict:
base64_image = encode_image_b64(image_path) # Getting the base64 string
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {client.api_key}"
}
payload = {
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": user_request
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
]
}
],
"max_tokens": 1000
}
response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
# print(response.status_code) # 200
return response.json()
# Function to get all user's referrals
def get_user_referrals(user_id: int) -> list:
user_referrals = []
for user in data:
if data[user].get("ref_id") == user_id:
user_referrals.append(user)
return user_referrals
def get_recent_active_users(days: int) -> list:
recent_active_users = []
current_date = datetime.now() + timedelta(hours=UTC_HOURS_DELTA)
for user_id, user_data in data.items():
if user_id == "global":
continue
try:
last_request_date = datetime.strptime(user_data["lastdate"], DATE_FORMAT)
# Если дата в неправильном формате, то пропускаем строчку (значит у юзера все равно 0 запросов, а Вы - олд)
except ValueError:
continue
if (current_date - last_request_date).days < days:
recent_active_users.append((user_id, last_request_date))
# Sort the list by last_request_date in descending order
recent_active_users = sorted(recent_active_users, key=lambda x: x[1], reverse=True)
# Extract only user_id from the sorted list
recent_active_users = [user_id for user_id, _ in recent_active_users]
return recent_active_users
# Function to get top users by specified parameter from data.json (requests, tokens, balance, etc.)
def get_top_users_by_data_parameter(max_users: int, parameter: str) -> list:
top_users = [(user_id, user_data[parameter]) for user_id, user_data in data.items() if user_id != "global" and user_data.get(parameter, 0) > 0]
top_users = sorted(top_users, key=lambda x: x[1], reverse=True)
top_users = top_users[:max_users]
return top_users
# Function to get top users by invited referrals
def get_top_users_by_referrals(max_users: int) -> list:
top_users = [(user_id, len(get_user_referrals(user_id))) for user_id in list(data.keys())[1:]]
top_users = [user for user in top_users if user[1] > 0]
top_users = sorted(top_users, key=lambda x: x[1], reverse=True)
top_users = top_users[:max_users]
return top_users
# Function to get top users by cost of their requests
def get_top_users_by_cost(max_users: int) -> list:
top_users = [(user_id, calculate_cost(data[user_id]['tokens'], data[user_id].get('premium_tokens', 0), data[user_id].get('images', 0))) for user_id in list(data.keys())[1:]]
top_users = [(user[0], round(user[1], 3)) for user in top_users if user[1] > 0]
top_users = sorted(top_users, key=lambda x: x[1], reverse=True)
top_users = top_users[:max_users]
return top_users
# Function to get user current model
def get_user_active_model(user_id: int) -> str:
if data[user_id].get("lang_model") is None:
return DEFAULT_MODEL
else:
model = str(data[user_id]["lang_model"])
if model == "premium":
return PREMIUM_MODEL
else:
return DEFAULT_MODEL
# Function to calculate the cost of the user requests (default + premium + images + whisper transcription) in cents
def calculate_cost(tokens: int, premium_tokens: int = 0, images: int = 0, whisper_seconds: int = 0) -> float:
tokens_cost = tokens * PRICE_CENTS
premium_tokens_cost = premium_tokens * PREMIUM_PRICE_CENTS
images_cost = images * IMAGE_PRICE_CENTS
whisper_seconds_cost = whisper_seconds * WHISPER_SEC_PRICE_CENTS
total_cost = tokens_cost + premium_tokens_cost + images_cost + whisper_seconds_cost
return total_cost
def format_cents_to_price_string(price: float) -> str:
"""
This function formats the price in cents to a string with the dollar or cent sign.
:param price: The price in cents
:type price: float
:return: The formatted price string
:rtype: str
"""
if price < 100:
return f"{round(price, 2)}¢"
else:
return f"${round(price / 100, 2)}"
# Получает на вход новые данные по пользователю по произведенным запросам, потраченным токенам, премиум токенам и изображениям и добавляет их в базу
# Если deduct_tokens = False, то токены не будут списаны с баланса (например, при запросах администратора)
# Вызывать, только если у пользователя положительный баланс используемых токенов!
def update_global_user_data(user_id: int, new_requests: int = 1, new_tokens: int = None, new_premium_tokens: int = None,
new_images: int = None, new_whisper_seconds: int = None, deduct_tokens: bool = True) -> None:
"""
This function updates the global and user-specific data based on the new requests, spent tokens, premium tokens and generated images.
It also updates the session counters for requests, tokens, premium tokens, and images.
:param user_id: The user's ID
:type user_id: int
:param new_requests: The number of new requests
:type new_requests: int
:param new_tokens: The number of used tokens
:type new_tokens: int
:param new_premium_tokens: The number of used premium tokens
:type new_premium_tokens: int
:param new_images: The number of generated images
:type new_images: int
:param new_whisper_seconds: The number of seconds of audio transcription using Whisper V2 model
:type new_whisper_seconds: int
:param deduct_tokens: Whether to deduct the tokens from the user's balance
:type deduct_tokens: bool
:returns: None
"""
global data, session_request_counter, session_tokens, premium_session_tokens, session_images, session_whisper_seconds # Глобальные счетчики текущей сессии
data[user_id]["requests"] += new_requests
data["global"]["requests"] += new_requests
session_request_counter += new_requests
data[user_id]["lastdate"] = (datetime.now() + timedelta(hours=UTC_HOURS_DELTA)).strftime(DATE_FORMAT)
if new_tokens:
data[user_id]["tokens"] += new_tokens
data["global"]["tokens"] += new_tokens
session_tokens += new_tokens
if deduct_tokens:
data[user_id]["balance"] -= new_tokens
if new_premium_tokens:
data[user_id]["premium_tokens"] = data[user_id].get("premium_tokens", 0) + new_premium_tokens
data["global"]["premium_tokens"] = data["global"].get("premium_tokens", 0) + new_premium_tokens
premium_session_tokens += new_premium_tokens
if deduct_tokens:
data[user_id]["premium_balance"] -= new_premium_tokens
if new_images:
data[user_id]["images"] = data[user_id].get("images", 0) + new_images
data["global"]["images"] = data["global"].get("images", 0) + new_images
session_images += new_images
if deduct_tokens:
data[user_id]["image_balance"] -= new_images
if new_whisper_seconds:
data[user_id]["whisper_seconds"] = data[user_id].get("whisper_seconds", 0) + new_whisper_seconds
data["global"]["whisper_seconds"] = data["global"].get("whisper_seconds", 0) + new_whisper_seconds
session_whisper_seconds += new_whisper_seconds
if deduct_tokens:
# data[user_id]["balance"] -= new_whisper_seconds * 100
data[user_id]["premium_balance"] -= new_whisper_seconds * 6 # минута Виспера - 400 прем токенов (6.666 токенов за 1 секунду), но сейчас скидка 10%
update_json_file(data)
def send_smart_split_message(bot_instance: telebot.TeleBot, chat_id: int, text: str, max_length: int = 4096, parse_mode: str = None, reply_to_message_id: int = None) -> None:
"""
This function sends a message to a specified chat ID, splitting the message into chunks if it exceeds the maximum length.
:param bot_instance: The Telebot instance to use for sending the message
:type bot_instance: telebot.TeleBot
:param chat_id: The chat ID to send the message to
:type chat_id: int
:param text: The text of the message
:type text: str
:param max_length: The maximum length of each message chunk
:type max_length: int
:param parse_mode: The parse mode of the message (e.g., "MARKDOWN" or "HTML")
:type parse_mode: str
:param reply_to_message_id: The message ID to reply to
:type reply_to_message_id: int
:return: None
"""
reply_parameters = None if reply_to_message_id is None else types.ReplyParameters(reply_to_message_id, allow_sending_without_reply=True)
if len(text) < max_length:
bot_instance.send_message(chat_id, text, parse_mode=parse_mode, reply_parameters=reply_parameters)
return
chunks = telebot.util.smart_split(text, max_length)
for chunk in chunks:
bot_instance.send_message(chat_id, chunk, parse_mode=parse_mode, reply_parameters=reply_parameters)
time.sleep(0.1) # Introduce a small delay between each message to avoid hitting Telegram's rate limits
def create_request_report(user: telebot.types.User, chat: telebot.types.Chat, request_tokens: int, request_price: float, voice_seconds: int = None) -> str:
"""
This function creates a report for the user's request.
Use `parse_mode="HTML"` to send telegram messages with this content.
:param user: The user who made the request
:type user: telebot.types.User
:param chat: The chat where the request was made
:type chat: telebot.types.Chat
:param request_tokens: The number of tokens used for the request
:type request_tokens: int
:param request_price: The price of the request in cents
:type request_price: float
:param voice_seconds: The duration of the transcribed voice message in seconds (default is None)
:type voice_seconds: int
:return: The report for the user's request
:rtype: str
"""
voice_seconds_info = f" ({voice_seconds} сек)" if voice_seconds is not None else ""
request_info = f"Запрос {session_request_counter}: {request_tokens}{voice_seconds_info} за {format_cents_to_price_string(request_price)}\n"
session_cost_cents = calculate_cost(session_tokens, premium_session_tokens, session_images, session_whisper_seconds)
session_info = f"Сессия: {session_tokens + premium_session_tokens} за {format_cents_to_price_string(session_cost_cents)}\n"
username = f"@{user.username} " if user.username is not None else ""
user_info = f"Юзер: {telebot.util.escape(user.full_name)} {username}<code>{user.id}</code>\n"
balance_info = f"Баланс: {data[user.id]['balance']}; {data[user.id].get('premium_balance', '')}\n"
chat_info = f"Чат: {telebot.util.escape(chat.title)} {chat.id}\n" if chat.id < 0 else "" # Если сообщение было в групповом чате, то указать данные о нём
global_cost_cents = calculate_cost(data['global']['tokens'], data['global'].get('premium_tokens', 0), data['global'].get('images', 0), data['global'].get('whisper_seconds', 0))
global_info = f"{data['global']} за {format_cents_to_price_string(global_cost_cents)}"
report = f"{request_info}{session_info}{user_info}{balance_info}{chat_info}{global_info}"
return report
def convert_ogg_to_mp3(source_ogg_path: str) -> str:
"""
Convert an OGG audio file to MP3 format using pydub with ffmpeg.
Deletes the original OGG file after conversion.
:param source_ogg_path: the path to the source OGG audio file.
:type source_ogg_path: str
:return: the path to the converted MP3 audio file.
:rtype: str
"""
mp3_path = source_ogg_path.replace(".ogg", ".mp3")
# load the ogg file using pydub
sound = AudioSegment.from_ogg(source_ogg_path)
# save the mp3 file
sound.export(mp3_path, format="mp3")
os.remove(source_ogg_path)
return mp3_path
def convert_voice_message_to_text(message: telebot.types.Message) -> str:
"""
Convert a voice message to text using OpenAI Whisper V2 model.
:param message: the Telegram message containing the voice message.
:type message: telebot.types.Message
:return: the text transcription of the voice message.
:rtype: str
"""
# get the voice message
voice = message.voice
# get the file ID
file_id = voice.file_id
# download the voice message
file_info = bot.get_file(file_id)
downloaded_file = bot.download_file(file_info.file_path)
# save the downloaded voice message to a local file
voice_ogg_path = f"voice_{message.from_user.id}.ogg"
with open(voice_ogg_path, 'wb') as new_file:
new_file.write(downloaded_file)
# convert the voice message from OGG to MP3 format
voice_mp3_path = convert_ogg_to_mp3(voice_ogg_path)
# open the converted MP3 file and create a transcription using OpenAI's Whisper model
with open(voice_mp3_path, "rb") as audio_file:
transcription = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file
)
# delete the MP3 file from disk
os.remove(voice_mp3_path)
return transcription.text
"""========================SETUP========================="""
# Check if the file exists
if os.path.isfile(DATAFILE):
# Read the contents of the file
with open(DATAFILE, "r", encoding='utf-8') as f:
data = json.load(f)
# Convert keys to integers (except for the first key)
for key in list(data.keys())[1:]:
data[int(key)] = data.pop(key)
else:
data = {"global": {"requests": 0, "tokens": 0, "images": 0},
ADMIN_ID: {"requests": 0, "tokens": 0, "balance": 777777, "premium_balance": 77777, "image_balance": 777,
"name": "АДМИН", "username": "@admin", "lastdate": "01-05-2023 00:00:00"}}
# Create the file with default values
update_json_file(data)
# Calculate the price per token in cents
PRICE_CENTS = PRICE_1K / 10
PREMIUM_PRICE_CENTS = PREMIUM_PRICE_1K / 10
IMAGE_PRICE_CENTS = IMAGE_PRICE * 100
WHISPER_SEC_PRICE_CENTS = WHISPER_MIN_PRICE / 60 * 100
# Session token and request counters
session_request_counter, session_tokens, premium_session_tokens, session_images, session_whisper_seconds = 0, 0, 0, 0, 0 # TODO: мб бахнуть класс session
"""====================ADMIN_COMMANDS===================="""
# Define the handler for the admin /data command
@bot.message_handler(commands=["d", "data"])
def handle_data_command(message):
target_user_string = extract_arguments(message.text)
not_found_string = "Пользователь не найден, либо данные введены неверно.\n" \
"Укажите @username или id пользователя после команды `/data`"
# Проверки на доступность команды
if message.from_user.id != ADMIN_ID: # Если пользователь не админ
bot.reply_to(message, "Команда доступна только админу")
return
elif message.chat.type != "private": # Если команда вызвана не в личке с ботом (чтобы не скомпрометировать данные)
bot.reply_to(message, "Эта команда недоступна в групповых чатах")
return
if target_user_string == '': # Если аргументов нет, то отправить весь файл и указать общее число пользователей
bot.send_message(ADMIN_ID, f"Число пользователей: {len(data) - 1}\n\n"
f"Копия файла `{DATAFILE}`:", parse_mode="MARKDOWN")
bot.send_document(ADMIN_ID, open(DATAFILE, "rb"))
print("\nДанные отправлены админу")
return
elif target_user_string[0] == "@": # Поиск по @username
target_user_id = get_user_id_by_username(target_user_string)
if target_user_id is None:
bot.send_message(ADMIN_ID, not_found_string, parse_mode="MARKDOWN")
return
elif target_user_string.isdigit(): # Поиск по id пользователя
target_user_id = int(target_user_string)
if not is_user_exists(target_user_id):
bot.send_message(ADMIN_ID, not_found_string, parse_mode="MARKDOWN")
return
else: # Если аргументы были введены неверно, то просим исправиться
bot.send_message(ADMIN_ID, not_found_string, parse_mode="MARKDOWN")
return
if data[target_user_id].get("premium_balance") is not None:
premium_string = (f"premium tokens: {data[target_user_id].get('premium_tokens', 0)}\n"
f"premium balance: {data[target_user_id]['premium_balance']}\n\n")
else:
premium_string = ""
if "image_balance" in data[target_user_id]:
images_string = (f"images: {data[target_user_id].get('images', 0)}\n"
f"image balance: {data[target_user_id]['image_balance']}\n\n")
else:
images_string = ""
if "whisper_seconds" in data[target_user_id]:
whisper_string = f"whisper seconds: {data[target_user_id].get('whisper_seconds', 0)}\n\n"
else:
whisper_string = ""
# Если юзер был успешно найден, то формируем здесь сообщение с его статой
user_data_string = f"id {target_user_id}\n" \
f"{data[target_user_id]['name']} " \
f"{data[target_user_id]['username']}\n\n" \
f"requests: {data[target_user_id]['requests']}\n" \
f"tokens: {data[target_user_id]['tokens']}\n" \
f"balance: {data[target_user_id]['balance']}\n\n" \
f"{premium_string}" \
f"{images_string}" \
f"{whisper_string}" \
f"last request: {data[target_user_id]['lastdate']}\n"
# Calculate user cost in cents and round it to 3 digits after the decimal point
user_cost_cents = calculate_cost(data[target_user_id]['tokens'], data[target_user_id].get('premium_tokens', 0),
data[target_user_id].get('images', 0), data[target_user_id].get('whisper_seconds', 0))
user_data_string += f"user cost: {format_cents_to_price_string(user_cost_cents)}\n\n"
# Если есть инфа о количестве исполненных просьб на пополнение, то выдать ее
if "favors" in data[target_user_id]:
user_data_string += f"favors: {data[target_user_id]['favors']}\n\n"
# Если у пользователя есть промпт, то выдать его
if "prompt" in data[target_user_id]:
user_data_string += f"prompt: {data[target_user_id].get('prompt')}\n\n"
# Если пользователя пригласили по рефке, то выдать информацию о пригласившем
if "ref_id" in data[target_user_id]:
referrer = data[target_user_id]["ref_id"]
user_data_string += f"invited by: {data[referrer]['name']} {data[referrer]['username']} {referrer}\n\n"
user_referrals_list: list = get_user_referrals(target_user_id)
if not user_referrals_list: # Если рефералов нет, то просто отправляем текущие данные по пользователю
bot.send_message(ADMIN_ID, user_data_string)
return
user_data_string += f"{len(user_referrals_list)} invited users:\n"
for ref in user_referrals_list:
user_data_string += f"{data[ref]['name']} {data[ref]['username']} {ref}: {data[ref]['requests']}\n"
send_smart_split_message(bot, ADMIN_ID, user_data_string)
# Define the handler for the admin /recent_users command to get recent active users in past n days
@bot.message_handler(commands=["recent", "recent_users", "last"])
def handle_recent_users_command(message):
user = message.from_user
wrong_input_string = "Укажите целое число дней после команды /recent_users"
if user.id != ADMIN_ID or message.chat.type != "private":
return
# Получаем аргументы команды
num_of_days = extract_arguments(message.text)
if num_of_days == "":
bot.reply_to(message, wrong_input_string)
return
elif not num_of_days.isdigit():
bot.reply_to(message, wrong_input_string)
return
num_of_days = int(num_of_days)
if num_of_days < 1:
bot.reply_to(message, wrong_input_string)
return
recent_active_users: list = get_recent_active_users(num_of_days)
if not recent_active_users:
bot.reply_to(message, f"За последние {num_of_days} дней активных пользователей не найдено")
return
answer = f"Активные юзеры за последние {num_of_days} дней: {len(recent_active_users)}\n\n"
for user_id in recent_active_users:
answer += f"{data[user_id]['name']} {data[user_id]['username']} {user_id}: {data[user_id]['requests']}\n"
send_smart_split_message(bot, ADMIN_ID, answer, reply_to_message_id=message.message_id)
# Define the handler for the admin /top_users command. we get 2 arguments: number of users and parameter
@bot.message_handler(commands=["top", "top_users"])
def handle_top_users_command(message):
user = message.from_user
wrong_input_string = "Укажите целое число пользователей и искомый параметр после команды\n\nПример: `/top 10 requests`"
if user.id != ADMIN_ID or message.chat.type != "private":
return
try:
max_users, parameter = extract_arguments(message.text).split()
max_users = int(max_users)
except (ValueError, IndexError):
bot.reply_to(message, wrong_input_string, parse_mode="MARKDOWN")
return
if max_users < 1:
bot.reply_to(message, wrong_input_string)
return
if parameter in ["requests", "tokens", "balance", "premium_tokens", "premium_balance", "images", "image_balance", "favors", "ref_id"]:
top_users: list = get_top_users_by_data_parameter(max_users, parameter)
elif parameter in ["ref", "refs", "referrals", "invites"]:
top_users: list = get_top_users_by_referrals(max_users)
elif parameter in ["cost", "price"]:
top_users: list = get_top_users_by_cost(max_users)
top_users = [(user[0], f"{format_cents_to_price_string(user[1])}") for user in top_users]
else:
bot.reply_to(message, f"Неверный параметр: *{parameter}*\n\n"
"Доступные параметры: \n- `requests` \n- `tokens` \n- `balance` \n- `premium_tokens` "
"\n- `premium_balance` \n- `images` \n- `image_balance` \n- `favors` \n- `refs` \n- `cost`", parse_mode="MARKDOWN")
return
if not top_users:
bot.reply_to(message, f"Топ пользователей по параметру *{parameter}* не найдено", parse_mode="MARKDOWN")
return
user_place = 1
answer = f"Топ {max_users} пользователей by {parameter}:\n\n"
for user_id, parameter_value in top_users:
answer += (f"{user_place}. {data[user_id]['name']} {data[user_id]['username'] if data[user_id]['username'] != 'None' else ''} "
f"{user_id}: {parameter_value}\n")
user_place += 1
send_smart_split_message(bot, ADMIN_ID, answer, reply_to_message_id=message.message_id)
# Define the handler for the admin /refill command
@bot.message_handler(commands=["r", "refill"])
def handle_refill_command(message):
wrong_input_string = ("Укажите @username/id пользователя и сумму пополнения после команды.\n\n"
"Допишите `premium` последним аргументом, чтобы пополнить баланс премиум токенов. "
"Или `image`, чтобы пополнить баланс для генерации изображений.\n\n"
"Пример: `/refill @username 1000`")
# Проверки на доступность команды
if message.from_user.id != ADMIN_ID: # Если пользователь не админ
bot.reply_to(message, "Команда доступна только админу")
return
elif message.chat.type != "private": # Если команда вызвана не в личке с ботом
bot.reply_to(message, "Эта команда недоступна в групповых чатах")
return
try:
args = extract_arguments(message.text).split()
amount = int(args[1])
except ValueError:
bot.send_message(ADMIN_ID, wrong_input_string, parse_mode="MARKDOWN")
return
except IndexError:
bot.send_message(ADMIN_ID, wrong_input_string, parse_mode="MARKDOWN")
return
target_user = args[0]
not_found_string = f"Пользователь {target_user} не найден"
success_string = f"Баланс пользователя {target_user} успешно пополнен на {amount} токенов."
# Определяем тип баланса для пополнения в зависимости от третьего аргумента (обычный, премиум или генерации изображений)
balance_type = args[2] if len(args) > 2 else None
if balance_type is None:
balance_type = "balance"
prefix = "" # префикс для сообщений
elif balance_type in ["premium", "prem", "p"]:
balance_type = "premium_balance"
success_string = "ПРЕМИУМ " + success_string
prefix = "премиум "
elif balance_type in ["images", "image", "img", "i"]:
balance_type = "image_balance"
success_string = "IMAGE " + success_string
prefix = "image "
else:
bot.send_message(ADMIN_ID, wrong_input_string, parse_mode="MARKDOWN")
return
# Находим айди юзера, если он есть в базе, иначе выходим
if target_user[0] == '@': # Поиск по @username
target_user_id = get_user_id_by_username(target_user)
if target_user_id is None:
bot.send_message(ADMIN_ID, not_found_string)
return
elif target_user.isdigit(): # Поиск по id пользователя
target_user_id = int(target_user)
if not is_user_exists(target_user_id):
bot.send_message(ADMIN_ID, not_found_string)
return
else:
bot.send_message(ADMIN_ID, wrong_input_string, parse_mode="MARKDOWN")
return
# Сначала проверяем, есть ли такой тип баланса у юзера (если нет, то создаем), а потом уже пополняем
if data[target_user_id].get(balance_type) is None:
data[target_user_id][balance_type] = 0
data[target_user_id][balance_type] += amount
update_json_file(data)
bot.send_message(ADMIN_ID, success_string + f"\nТекущий {prefix}баланс: {data[target_user_id][balance_type]}")
try:
if amount > 0:
bot.send_message(target_user_id, f"Ваш баланс пополнен на {amount} {prefix}токенов!\n"
f"Текущий {prefix}баланс: {data[target_user_id][balance_type]}")
except Exception as e:
bot.send_message(ADMIN_ID, f"Ошибка при уведомлении юзера {target_user}, походу он заблочил бота 🤬")
print(e)
# Define the handler for the admin /block command
@bot.message_handler(commands=["ban", "block"])
def handle_block_command(message):
target_user = extract_arguments(message.text)
wrong_input_string = "Укажите @username/id пользователя после команды\n\n" \
"Пример: `/block @username`"
# Проверки на доступность команды
if message.from_user.id != ADMIN_ID:
return
elif message.chat.type != "private":
bot.reply_to(message, "Эта команда недоступна в групповых чатах")
return
if target_user == '':
bot.send_message(ADMIN_ID, wrong_input_string, parse_mode="MARKDOWN")
return
not_found_string = f"Пользователь {target_user} не найден"
success_string = f"Пользователь {target_user} успешно заблокирован"
# Находим айди юзера, если он есть в базе, иначе выходим
if target_user[0] == '@':
target_user = get_user_id_by_username(target_user)
if target_user is None:
bot.send_message(ADMIN_ID, not_found_string)
return
elif target_user.isdigit():
target_user = int(target_user)
if not is_user_exists(target_user):
bot.send_message(ADMIN_ID, not_found_string)
return
else:
bot.send_message(ADMIN_ID, wrong_input_string, parse_mode="MARKDOWN")
return
data[target_user]["blacklist"] = True
update_json_file(data)
bot.send_message(ADMIN_ID, success_string)
print(success_string)
# Define the handler for the /stop command
@bot.message_handler(commands=["stop"])
def handle_stop_command(message):
if message.from_user.id == ADMIN_ID:
bot.reply_to(message, "Stopping the script...")
bot.stop_polling()
# Define the handler for the /announce command
# Эта команда принимает сообщение от админа и рассылает его между пользователями бота (типа уведомления)
@bot.message_handler(commands=["a", "announce", "alert", "broadcast", "notify"])
def handle_announce_command(message):
user = message.from_user
if user.id != ADMIN_ID or message.chat.type != "private":
return
# Получаем аргументы команды (текст после /announce)
user_filter = extract_arguments(message.text)
if user_filter == "":
bot.reply_to(message, "Введите тип рассылки после команды /announce\n\n"
"Варианты:\n"
"all - рассылка всем пользователям\n"
"req1 - расылка всем пользователям, кто сделал хотя бы 1 запрос (любое значение)\n"
"bal1000 - рассылка всем пользователям с балансом от 1000 токенов (любое значение)\n"
"test - рассылка только админу (тест команды)\n\n"
"Так же можно уведомить только одного пользователя, написав его user_id или @username")
return
bot.reply_to(message, "Введите текст сообщения для рассылки.\nq - отмена")
bot.register_next_step_handler(message, process_announcement_message_step, user_filter)
def process_announcement_message_step(message, user_filter):
user = message.from_user
if user.id != ADMIN_ID or message.chat.type != "private":
return
announcement_text = message.html_text
recepients_list = []
if announcement_text == "q":
bot.send_message(user.id, "Рассылка отменена")
return
if user_filter == "test":
recepients_list.append(ADMIN_ID)
confirmation_text = f"Получатели: тестовый режим, только админ\n\n" \
"Отправить данное сообщение? (y/n)\n"
elif user_filter == "all":
recepients_list = list(data.keys())[1:]
confirmation_text = f"Получатели: все пользователи ({len(recepients_list)})\n\n" \
"Разослать данное сообщение? (y/n)\n"
elif user_filter.startswith("req"):
user_filter = user_filter[3:]
if not user_filter.isdigit():
bot.send_message(user.id, "Неверный тип рассылки!\nЖми /announce для справки")
return
user_filter = int(user_filter)
for user_id in list(data.keys())[1:]:
if data[user_id]["requests"] >= user_filter:
recepients_list.append(user_id)
confirmation_text = f"Получатели: юзеры от {user_filter} запросов ({len(recepients_list)})\n\n" \
"Разослать данное сообщение? (y/n)\n"
elif user_filter.startswith("bal"):
user_filter = user_filter[3:]
if not user_filter.isdigit():
bot.send_message(user.id, "Неверный тип рассылки!\nЖми /announce для справки")
return
user_filter = int(user_filter)
for user_id in list(data.keys())[1:]:
if data[user_id]["balance"] >= user_filter:
recepients_list.append(user_id)
confirmation_text = f"Получатели: юзеры с балансом от {user_filter} токенов ({len(recepients_list)})\n\n" \
"Разослать данное сообщение? (y/n)\n"
# Для групповых чатов (id с минусом)
elif user_filter[0] == "-" and user_filter[1:].isdigit():
user_filter = int(user_filter)
recepients_list.append(user_filter)
confirmation_text = f"Получатели: чат {user_filter}\n\n" \
"Отправить данное сообщение? (y/n)\n"
elif user_filter.isdigit():
user_filter = int(user_filter)
if not is_user_exists(user_filter):
bot.send_message(user.id, f"Пользователь не найден!")
return
recepients_list.append(user_filter)
confirmation_text = f"Получатель: {data[user_filter]['name']} {data[user_filter]['username']} {user_filter}\n\n" \
"Разослать данное сообщение? (y/n)\n"
elif user_filter[0] == "@":
user_filter = get_user_id_by_username(user_filter)
if user_filter is None:
bot.send_message(user.id, "Пользователь не найден!")
return
recepients_list.append(user_filter)
confirmation_text = f"Получатель: {data[user_filter]['name']} {data[user_filter]['username']} {user_filter}\n\n" \
"Отправить данное сообщение? (y/n)\n"
else:
bot.send_message(user.id, "Неверный тип рассылки!\nЖми /announce для справки")
return
announcement_msg = bot.send_message(user.id, announcement_text, parse_mode="HTML")
time.sleep(0.5)
bot.reply_to(announcement_msg, confirmation_text)
bot.register_next_step_handler(announcement_msg, process_announcement_confirmation_step,
recepients_list, announcement_text)
def process_announcement_confirmation_step(message, recepients_list, announcement_text):
user = message.from_user
if user.id != ADMIN_ID or message.chat.type != "private":
return
if message.text == "y":
bot.send_message(user.id, "Рассылка запущена")
print("Рассылка запущена")
else:
bot.send_message(user.id, "Рассылка отменена")
return
# Если в получателях только один групповой чат
if len(recepients_list) == 1 and recepients_list[0] < 0:
try:
bot.send_message(recepients_list[0], announcement_text, parse_mode="HTML")
admin_log = f"✉️ Сообщение отправлено в чат {recepients_list[0]}"
except Exception as e:
admin_log = f"❌ Ошибка: чат {recepients_list[0]} не найден"
bot.send_message(ADMIN_ID, admin_log)
print(admin_log)
return