import re
import json
import time
import asyncio
import logging
import functools
import os
from zoneinfo import ZoneInfo
from telegram import Update
from datetime import datetime, timedelta, time as dt_time
from telegram.constants import ChatAction
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, filters
from apscheduler.jobstores.base import JobLookupError
from gradio_client import Client
TOKEN = '7626716371:AAFTR6OHq2JJXwmo7BPUaN3Ef3Av4eNBOKY'
Initialize the Gradio client for the new API
client = Client("yuntian-deng/ChatGPT4")
Enable logging
logger = logging.getLogger(name)
Moscow timezone
moscow_tz = ZoneInfo("Europe/Moscow")
Path to the data file
DATA_FILE = 'data.json'
def load_data():
if os.path.exists(DATA_FILE):
with open(DATA_FILE, 'r') as f:
data = json.load(f)
else:
data = {'users': {}}
# Update data structure for existing users
for user_info in data['users'].values():
if not isinstance(user_info.get('messages_today'), int):
user_info['messages_today'] = 0
if not isinstance(user_info.get('total_messages'), int):
user_info['total_messages'] = 0
return data
def save_data(data):
with open(DATA_FILE, 'w') as f:
json.dump(data, f)
data = load_data()
ADMIN_ID = 1956293525
Maximum interval between messages in seconds
MAX_INTERVAL = 1 # You can adjust this value
def is_user_paid(user_id):
user_id_str = str(user_id)
if user_id_str in data['users']:
user_info = data['users'][user_id_str]
if user_info.get('subscription'):
expiry_datetime_str = user_info.get('subscription_expiry')
if expiry_datetime_str == 'unlimited':
return True
elif expiry_datetime_str:
expiry_datetime = datetime.fromisoformat(expiry_datetime_str)
if datetime.now(moscow_tz) <= expiry_datetime:
return True
else:
# Subscription has expired
user_info['subscription'] = False
user_info['subscription_expiry'] = None
save_data(data)
return False
else:
return False
else:
return False
else:
return False
def get_max_messages_per_day(user_id):
if is_user_paid(user_id):
return 50
else:
return 10
async def process_accumulated_message(context: ContextTypes.DEFAULT_TYPE):
user_id = context.job.data['user_id']
user_id_str = str(user_id)
user_info = data['users'][user_id_str]
if 'partial_message' in user_info:
full_message = user_info['partial_message']['text']
# Remove the accumulated message from user data
del user_info['partial_message']
save_data(data)
# Call handle_message with the full message
await handle_message(context.job.data['update'], context, user_message=full_message)
# Remove the job from context.chat_data['jobs'] to avoid attempting to cancel it again
if 'jobs' in context.chat_data and user_id in context.chat_data['jobs']:
del context.chat_data['jobs'][user_id]
def markdown_to_telegram_html(text):
import html
# Bold italic text
text = re.sub(r'***(.*?)***', r'\1', text)
# Bold text
text = re.sub(r'\*\*(.*?)\*\*', r'<b>\1</b>', text)
# Italic text
text = re.sub(r'\*(.*?)\*', r'<i>\1</i>', text)
# Strikethrough text
text = re.sub(r'~~(.*?)~~', r'<s>\1</s>', text)
# Horizontal line (replace with supported characters)
text = re.sub(r'^---$', r'――――――――――', text, flags=re.MULTILINE)
# Links
text = re.sub(r'$$(.*?)$$$(.*?)$', r'<a href="\2">\1</a>', text)
# Code blocks (multiline)
text = re.sub(
r'```(?:\w+\n)?([\s\S]+?)```',
lambda m: '<pre>{}</pre>'.format(html.escape(m.group(1))),
text
)
# Inline code
text = re.sub(
r'`(.*?)`',
lambda m: '<code>{}</code>'.format(html.escape(m.group(1))),
text
)
# Remove unsupported HTML tags
def remove_unsupported_html_tags(text):
allowed_tags = ['a', 'b', 'strong', 'i', 'em', 'u', 'ins', 's', 'strike', 'del', 'code', 'pre']
pattern = r'</?(?!(?:' + '|'.join(allowed_tags) + r')\b)([a-zA-Z]+)(?:\s[^>]*)?>'
text = re.sub(pattern, '', text)
return text
text = remove_unsupported_html_tags(text)
return text.strip()
Command /start
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user = update.effective_user
# Check if the user has access
if str(user.id) not in data['users']:
await update.message.reply_text("Извините, у вас нет доступа к этому боту.")
return
await update.message.reply_html(
rf"Привет, {user.mention_html()}! Как я могу вам помочь?",
)
Handle text messages
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE, user_message=None) -> None:
user_id = update.effective_user.id
user_id_str = str(user_id)
if user_message is None:
user_message = update.message.text
user_info = data['users'][user_id_str]
# Get current date
current_date = datetime.now(moscow_tz).date().isoformat()
# Initialize message counters
if user_info.get('messages_today') is None or not isinstance(user_info.get('messages_today'), int):
user_info['messages_today'] = 0
if user_info.get('total_messages') is None or not isinstance(user_info.get('total_messages'), int):
user_info['total_messages'] = 0
# Check and update user's request counter
if user_info.get('date') != current_date:
user_info['date'] = current_date
user_info['messages_today'] = 0
# Increase request counter
user_info['messages_today'] += 1
user_info['total_messages'] += 1
save_data(data)
# Flag to control typing action duration
processing = True
async def send_typing_action():
while processing:
# Send "typing..." action
await update.effective_chat.send_action(action=ChatAction.TYPING)
await asyncio.sleep(4) # Repeat every 4 seconds
# Start sending typing indicator in the background
task = context.application.create_task(send_typing_action())
# Get user's chat history or initialize new
chatbot = user_info.get('chatbot', [])
chat_counter = user_info.get('chat_counter', 0)
try:
# Use gradio_client to send the request
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(
None,
functools.partial(
client.predict,
inputs=user_message,
top_p=1,
temperature=1,
chat_counter=chat_counter,
chatbot=chatbot,
api_name="/predict"
)
)
# Update 'chatbot' and 'chat_counter' from the result
chatbot = result[0]
chat_counter = result[1]
status_code = result[2]
# Extract bot's reply from 'chatbot'
bot_reply = chatbot[-1][1]
# Update user data
user_info['chatbot'] = chatbot
user_info['chat_counter'] = chat_counter
save_data(data)
# Send the response to the user
if bot_reply:
send_bot_reply = markdown_to_telegram_html(bot_reply)
await send_large_message(send_bot_reply, update)
except Exception as e:
logger.error(f"Ошибка при обработке сообщения: {e}", exc_info=True)
await update.message.reply_text("Извините, произошла ошибка при обработке вашего запроса.", parse_mode='HTML')
finally:
# Stop sending typing indicator
processing = False
await task # Wait for the task to complete
Function to send large messages
def tokenize(message):
tokens = []
pos = 0
length = len(message)
while pos < length:
if message[pos] == '<':
# This is a tag
end_tag_pos = message.find('>', pos)
if end_tag_pos == -1:
# Incomplete tag, treat the rest as text
tokens.append(('text', message[pos:]))
break
else:
token_content = message[pos+1:end_tag_pos]
# Check if it's a closing tag
if token_content.startswith('/'):
tag_name = token_content[1:].split()[0]
tokens.append(('end_tag', tag_name, '<'+token_content+'>'))
else:
# Tag may contain attributes
tag_name = token_content.split()[0]
tokens.append(('start_tag', tag_name, '<'+token_content+'>'))
pos = end_tag_pos + 1
else:
# This is text
next_tag_pos = message.find('<', pos)
if next_tag_pos == -1:
# No more tags
tokens.append(('text', message[pos:]))
break
else:
tokens.append(('text', message[pos:next_tag_pos]))
pos = next_tag_pos
return tokens
def generate_closing_tags(open_tags):
closing_tags = ''
for start_tag in reversed(open_tags):
# Get tag name from the start tag
tag_content = start_tag[1:-1].strip()
if ' ' in tag_content:
tag_name = tag_content.split(' ',1)[0]
else:
tag_name = tag_content
closing_tags += '</{}>'.format(tag_name)
return closing_tags
async def send_large_message(message, update, reply_markup=None):
MAX_MESSAGE_LENGTH = 4000
tokens = tokenize(message)
open_tags = []
current_part = ''
current_length = 0
parts = []
for token in tokens:
if token[0] == 'start_tag':
tag_name = token[1]
tag_string = token[2]
token_length = len(tag_string)
if current_length + token_length > MAX_MESSAGE_LENGTH:
# Close tags and start a new part
closing_tags = generate_closing_tags(open_tags)
current_part += closing_tags
parts.append(current_part)
current_part = ''
current_length = 0
# Re-open tags
opening_tags = ''.join(open_tags)
current_part += opening_tags
current_length += len(opening_tags)
current_part += tag_string
current_length += token_length
open_tags.append(tag_string)
elif token[0] == 'end_tag':
tag_name = token[1]
tag_string = token[2]
token_length = len(tag_string)
if current_length + token_length > MAX_MESSAGE_LENGTH:
# Close tags and start a new part
closing_tags = generate_closing_tags(open_tags)
current_part += closing_tags
parts.append(current_part)
current_part = ''
current_length = 0
# Re-open tags
opening_tags = ''.join(open_tags)
current_part += opening_tags
current_length += len(opening_tags)
current_part += tag_string
current_length += token_length
if open_tags:
open_tags.pop()
elif token[0] == 'text':
text_content = token[1]
text_length = len(text_content)
pos = 0
while pos < text_length:
remaining_space = MAX_MESSAGE_LENGTH - current_length
if remaining_space <= 0:
# Close tags and start a new part
closing_tags = generate_closing_tags(open_tags)
current_part += closing_tags
parts.append(current_part)
current_part = ''
current_length = 0
# Re-open tags
opening_tags = ''.join(open_tags)
current_part += opening_tags
current_length += len(opening_tags)
remaining_space = MAX_MESSAGE_LENGTH - current_length
take_length = min(remaining_space, text_length - pos)
current_part += text_content[pos:pos+take_length]
current_length += take_length
pos += take_length
# Close any remaining open tags and add the last part
if open_tags:
closing_tags = generate_closing_tags(open_tags)
current_part += closing_tags
if current_part:
parts.append(current_part)
# Send message parts
for part in parts:
if part.strip(): # Send only non-empty parts
await update.message.reply_text(part, parse_mode='HTML', reply_markup=reply_markup)
# Remove keyboard after first message to avoid sending it multiple times
reply_markup = None
Command /clear to reset chat history
async def clear_chat(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user_id = update.effective_user.id
user_id_str = str(user_id)
# Check if the user has access
if user_id_str not in data['users']:
await update.message.reply_text("Извините, у вас нет доступа к этому боту.")
return
data['users'][user_id_str]['chatbot'] = []
data['users'][user_id_str]['chat_counter'] = 0
save_data(data)
await update.message.reply_text("Чат сброшен. Начнем с чистого листа!", parse_mode='HTML')
async def get_my_id(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user = update.effective_user
user_id = user.id
username = f"@{user.username}"
await update.message.reply_text(f"{user_id} {username}")
Function to add a user to data.json
async def add_user(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# Check if the user is an admin
if update.effective_user.id != ADMIN_ID:
await update.message.reply_text("Извините, у вас нет прав для выполнения этой команды.")
return
# Get user ID and name from command arguments
args = context.args
if len(args) < 2:
await update.message.reply_text("Пожалуйста, используйте команду в формате /add user_id username")
return
try:
user_id = int(args[0])
username = ' '.join(args[1:])
user_id_str = str(user_id)
# Check if the user is already in the list
if user_id_str in data['users']:
await update.message.reply_text(f"Пользователь с ID {user_id} уже имеет доступ.")
else:
data['users'][user_id_str] = {
'id': user_id,
'username': username,
'total_messages': 0,
'messages_today': 0,
'date': datetime.now(moscow_tz).date().isoformat(),
'subscription': False,
'subscription_expiry': None,
'chatbot': [],
'chat_counter': 0
}
save_data(data)
await update.message.reply_text(f"Пользователь с ID {user_id} и именем {username} добавлен в список доступа.")
except ValueError:
await update.message.reply_text("Пожалуйста, введите корректный числовой ID пользователя.")
Function to remove a user from data.json
async def remove_user(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# Check if the user is an admin
if update.effective_user.id != ADMIN_ID:
await update.message.reply_text("Извините, у вас нет прав для выполнения этой команды.")
return
# Get user ID from command arguments
args = context.args
if len(args) != 1:
await update.message.reply_text("Пожалуйста, используйте команду в формате /remove user_id")
return
try:
user_id = int(args[0])
user_id_str = str(user_id)
# Find and remove the user from the list
if user_id_str in data['users']:
username = data['users'][user_id_str]['username']
del data['users'][user_id_str]
save_data(data)
# Cancel scheduled jobs for the user, if any
if 'jobs' in context.chat_data and user_id in context.chat_data['jobs']:
try:
context.chat_data['jobs'][user_id].schedule_removal()
except JobLookupError:
pass # Job was already removed
del context.chat_data['jobs'][user_id]
await update.message.reply_text(f"Пользователь с ID {user_id} и именем {username} удалён из списка доступа, и все связанные данные удалены.")
else:
await update.message.reply_text(f"Пользователь с ID {user_id} не найден в списке доступа.")
except ValueError:
await update.message.reply_text("Пожалуйста, введите корректный числовой ID пользователя.")
Command /paid to grant subscription
async def paid_user(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# Check if the user is an admin
if update.effective_user.id != ADMIN_ID:
await update.message.reply_text("Извините, у вас нет прав для выполнения этой команды.")
return
args = context.args
if len(args) != 2:
await update.message.reply_text("Пожалуйста, используйте команду в формате /paid user_id количество_дней")
return
try:
user_id = int(args[0])
days = int(args[1])
user_id_str = str(user_id)
# Check if the user is in the allowed list
if user_id_str not in data['users']:
await update.message.reply_text(
f"Пользователь с ID {user_id} не найден в списке разрешённых пользователей. "
f"Сначала добавьте его с помощью команды /add"
)
return
# Get current date in Moscow timezone and set time to 00:00
current_date_midnight = datetime.now(moscow_tz).replace(hour=0, minute=0, second=0, microsecond=0)
# Calculate subscription expiry date
expiry_datetime = current_date_midnight + timedelta(days=days)
# Update subscription info
data['users'][user_id_str]['subscription'] = True
data['users'][user_id_str]['subscription_expiry'] = expiry_datetime.isoformat()
save_data(data)
await update.message.reply_text(
f"Пользователь с ID {user_id} получил подписку до {expiry_datetime.strftime('%Y-%m-%d %H:%M')}."
)
except ValueError:
await update.message.reply_text("Пожалуйста, введите корректные значения для user_id и количество_дней.")
Command /unpaid to cancel user's subscription
async def unpaid_user(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# Check if the user is an admin
if update.effective_user.id != ADMIN_ID:
await update.message.reply_text("Извините, у вас нет прав для выполнения этой команды.")
return
args = context.args
if len(args) != 1:
await update.message.reply_text("Пожалуйста, используйте команду в формате /unpaid user_id")
return
try:
user_id = int(args[0])
user_id_str = str(user_id)
if user_id_str in data['users']:
data['users'][user_id_str]['subscription'] = False
data['users'][user_id_str]['subscription_expiry'] = None
save_data(data)
await update.message.reply_text(f"Подписка пользователя с ID {user_id} была отменена.")
else:
await update.message.reply_text(f"Пользователь с ID {user_id} не найден.")
except ValueError:
await update.message.reply_text("Пожалуйста, введите корректный числовой ID пользователя.")
Command /profile to display user information
async def profile(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user_id = update.effective_user.id
user_id_str = str(user_id)
# Check if the user has access
if user_id_str not in data['users']:
await update.message.reply_text("Извините, у вас нет доступа к этому боту.")
return
user_info = data['users'][user_id_str]
current_date = datetime.now(moscow_tz).date().isoformat()
# Initialize message counters
if user_info.get('messages_today') is None or not isinstance(user_info.get('messages_today'), int):
user_info['messages_today'] = 0
if user_info.get('total_messages') is None or not isinstance(user_info.get('total_messages'), int):
user_info['total_messages'] = 0
# Check and update user's request counter
if user_info.get('date') != current_date:
user_info['date'] = current_date
user_info['messages_today'] = 0
# Get subscription status
if is_user_paid(user_id):
expiry_datetime_str = user_info['subscription_expiry']
if expiry_datetime_str == 'unlimited':
subscription_status = "У вас есть безлимитная подписка."
else:
expiry_datetime = datetime.fromisoformat(expiry_datetime_str)
subscription_status = (
f"У вас есть подписка до {expiry_datetime.strftime('%Y-%m-%d %H:%M')}."
)
else:
subscription_status = "У вас нет активной подписки."
# Messages left today
messages_sent = user_info['messages_today']
max_messages = get_max_messages_per_day(user_id)
if max_messages == float('inf'):
messages_left = "∞"
else:
messages_left = max_messages - messages_sent
# Total messages
total_messages = user_info.get('total_messages', 0)
await update.message.reply_text(
f"Информация о вашем профиле:\n"
f" - {subscription_status}\n"
f" - Осталось запросов на сегодня: {messages_left}\n"
f" - Всего запросов за всё время: {total_messages}"
)
Function to display the list of allowed users with their status
async def list_users(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# Check if the user is an admin
if update.effective_user.id != ADMIN_ID:
await update.message.reply_text("Извините, у вас нет прав для выполнения этой команды.")
return
if data['users']:
users_list = []
for user_id_str, user_info in data['users'].items():
user_id = int(user_id_str)
username = user_info.get('username', 'Unknown')
# Initialize message counters
if user_info.get('messages_today') is None or not isinstance(user_info.get('messages_today'), int):
user_info['messages_today'] = 0
if user_info.get('total_messages') is None or not isinstance(user_info.get('total_messages'), int):
user_info['total_messages'] = 0
# Messages today and total
messages_sent_today = user_info['messages_today']
total_messages = user_info.get('total_messages', 0)
# Get subscription status
if is_user_paid(user_id):
expiry_datetime_str = user_info['subscription_expiry']
if expiry_datetime_str == 'unlimited':
subscription_status = "Безлимитная подписка"
else:
expiry_datetime = datetime.fromisoformat(expiry_datetime_str)
subscription_status = f"Подписка до {expiry_datetime.strftime('%Y-%m-%d %H:%M')}"
else:
subscription_status = "Нет подписки"
users_list.append(
f"ID: {user_id}\n"
f"Username: {username}\n"
f"Запросов сегодня: {messages_sent_today}\n"
f"Всего запросов: {total_messages}\n"
f" - {subscription_status}.\n"
f"________________________________________"
)
users_text = "\n\n".join(users_list)
await update.message.reply_text(f"Список разрешённых пользователей:\n{users_text}")
else:
await update.message.reply_text("Список разрешённых пользователей пуст.")
Function to display admin help
async def admin_help(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# Check if the user is an admin
if update.effective_user.id != ADMIN_ID:
await update.message.reply_text("Извините, у вас нет прав для выполнения этой команды.")
return
help_text = (
"Доступные команды администратора:\n"
"/add ID имя - добавить пользователя в список разрешённых\n"
"/remove ID - удалить пользователя из списка разрешённых\n"
"/list - показать список разрешённых пользователей\n"
"/paid ID дни - выдать подписку пользователю\n"
"/unpaid ID - отменить подписку пользователя\n"
"/nolimit ID - выдать безлимитную подписку пользователю\n"
"/news - сделать единоразовую рассылку текста"
)
await update.message.reply_text(help_text)
Function to reset daily message counts at 00:00 Moscow time
async def reset_daily_message_counts(context: ContextTypes.DEFAULT_TYPE):
current_date = datetime.now(moscow_tz).date().isoformat()
for user_info in data['users'].values():
user_info['messages_today'] = 0
user_info['date'] = current_date
save_data(data)
async def nolimit_user(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# Check if the user is an admin
if update.effective_user.id != ADMIN_ID:
await update.message.reply_text("Извините, у вас нет прав для выполнения этой команды.")
return
args = context.args
if len(args) != 1:
await update.message.reply_text("Пожалуйста, используйте команду в формате /nolimit user_id")
return
try:
user_id = int(args[0])
user_id_str = str(user_id)
# Check if the user is in the allowed list
if user_id_str not in data['users']:
await update.message.reply_text(
f"Пользователь с ID {user_id} не найден в списке разрешённых пользователей. "
f"Сначала добавьте его с помощью команды /add"
)
return
# Set user's subscription to 'unlimited'
data['users'][user_id_str]['subscription'] = True
data['users'][user_id_str]['subscription_expiry'] = 'unlimited'
save_data(data)
await update.message.reply_text(
f"Пользователь с ID {user_id} получил безлимитную подписку."
)
except ValueError:
await update.message.reply_text("Пожалуйста, введите корректный числовой ID пользователя.")
async def message_collector(update: Update, context: ContextTypes.DEFAULT_TYPE):
if context.user_data.get('broadcast'):
# Ignore messages during broadcast
return
user_id = update.effective_user.id
user_id_str = str(user_id)
# Check if the user has access
if user_id_str not in data['users']:
await update.message.reply_text("Извините, у вас нет доступа к этому боту.")
return
user_info = data['users'][user_id_str]
message_text = update.message.text
# Initialize message counters
if user_info.get('messages_today') is None or not isinstance(user_info.get('messages_today'), int):
user_info['messages_today'] = 0
if user_info.get('total_messages') is None or not isinstance(user_info.get('total_messages'), int):
user_info['total_messages'] = 0
current_date = datetime.now(moscow_tz).date().isoformat()
# Check and update user's request counter
if user_info.get('date') != current_date:
user_info['date'] = current_date
user_info['messages_today'] = 0
messages_sent_today = user_info['messages_today']
max_messages_per_day = get_max_messages_per_day(user_id)
if messages_sent_today >= max_messages_per_day:
await update.message.reply_text(
f"Извините, вы достигли дневного лимита в {max_messages_per_day} запросов к ИИ."
)
return
current_time = time.time()
# Add or update user's partial message
if 'partial_message' in user_info:
user_info['partial_message']['text'] += message_text
user_info['partial_message']['last_time'] = current_time
else:
user_info['partial_message'] = {'text': message_text, 'last_time': current_time}
save_data(data)
# Cancel previous processing jobs for this user, if any
if 'jobs' not in context.chat_data:
context.chat_data['jobs'] = {}
if user_id in context.chat_data['jobs']:
try:
context.chat_data['jobs'][user_id].schedule_removal()
except JobLookupError:
pass # Job was already removed
# Schedule a new processing job after MAX_INTERVAL seconds
job = context.job_queue.run_once(
process_accumulated_message,
when=MAX_INTERVAL,
data={'user_id': user_id, 'update': update},
chat_id=update.effective_chat.id
)
context.chat_data['jobs'][user_id] = job
Implement /news command for broadcasting messages
async def new_message_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
# Check if the user is an admin
if update.effective_user.id != ADMIN_ID:
await update.message.reply_text("Извините, у вас нет прав для выполнения этой команды.")
return
await update.message.reply_text("Пожалуйста, введите текст, который будет разослан, или напишите /cancel для отмены.")
context.user_data['broadcast'] = True
async def new_message_receive(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.effective_user.id != ADMIN_ID:
return False
if context.user_data.get('broadcast'):
message_text = update.message.text
if message_text == '/cancel':
await update.message.reply_text("Рассылка отменена.")
context.user_data['broadcast'] = False
return True
else:
# Broadcast the message to all users
user_ids = [int(uid) for uid in data['users'].keys()]
for user_id in user_ids:
try:
await context.bot.send_message(chat_id=user_id, text=message_text)
except Exception as e:
logger.error(f"Не удалось отправить сообщение пользователю {user_id}: {e}")
await update.message.reply_text("Сообщение разослано всем пользователям.")
context.user_data['broadcast'] = False
return True
else:
# Allow other handlers to process the message if not in broadcast mode
return False
async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE):
if context.user_data.get('broadcast'):
await update.message.reply_text("Рассылка отменена.")
context.user_data['broadcast'] = False
def main():
application = ApplicationBuilder().token(TOKEN).build()
# Schedule daily reset of message counts at 00:00 Moscow time
application.job_queue.run_daily(
reset_daily_message_counts,
time=dt_time(0, 0, tzinfo=moscow_tz)
)
# Register admin command handlers
application.add_handler(CommandHandler("add", add_user))
application.add_handler(CommandHandler("remove", remove_user))
application.add_handler(CommandHandler("list", list_users))
application.add_handler(CommandHandler("adminhelp", admin_help))
application.add_handler(CommandHandler("paid", paid_user))
application.add_handler(CommandHandler("unpaid", unpaid_user))
application.add_handler(CommandHandler("nolimit", nolimit_user))
application.add_handler(CommandHandler("news", new_message_start))
application.add_handler(CommandHandler("cancel", cancel))
# Register other command and message handlers
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("clear", clear_chat))
application.add_handler(CommandHandler("myid", get_my_id))
application.add_handler(CommandHandler("profile", profile))
# Message handler for admin during broadcast
admin_message_filter = filters.TEXT & ~filters.COMMAND & filters.User(user_id=ADMIN_ID)
application.add_handler(MessageHandler(admin_message_filter, new_message_receive), group=1)
# Message handler for other users
message_handler = MessageHandler(filters.TEXT & ~filters.COMMAND, message_collector)
application.add_handler(message_handler)
# Start the bot
application.run_polling()
if name == 'main':
main()
замени все комментарии на русские