# В userAdd.py
def handle_number_input(bot, message, table_name):
    number = message.text
    cursor = mydb.cursor()
    sql_query = f"INSERT INTO {table_name} (phone_number, is_try) VALUES (%s, %s)"
    values = (number, 1)
    cursor.execute(sql_query, values)
    mydb.commit()
    cursor.close()
    bot.send_message(message.chat.id, text41)
def handle_table_selection(bot, message, table_name):
    # Отправляем сообщение с запросом ввода номера
    bot.send_message(message.chat.id, text40)
    # Устанавливаем состояние пользователя в ожидание ввода номера
    bot.register_next_step_handler(message, lambda msg: handle_number_input(bot, msg, table_name))
# В userDelete.py
def handle_number_input2(bot, message, table_name):
    number = message.text
    cursor = mydb.cursor()
    sql_query = f"DELETE FROM {table_name} WHERE phone_number = %s"
    values = (number,)
    cursor.execute(sql_query, values)
    mydb.commit()
    cursor.close()
    bot.send_message(message.chat.id, text45)
def handle_table_selection2(bot, message, table_name):
    # Отправляем сообщение с запросом ввода номера
    bot.send_message(message.chat.id, text40)
    # Устанавливаем состояние пользователя в ожидание ввода номера
    bot.register_next_step_handler(message, lambda msg: handle_number_input2(bot, msg, table_name))# Всякий нужный код до этого момента
    elif message.text == text42:
        userAdd.handle_table_selection(bot, message, table_name)
    elif message.text == text43:
        userDelete.handle_table_selection2(bot, message, table_name)
# Всякий нужный код после этого момента@dp.message_handler(content_types=['text', 'photo'])
async def main(message: types.Message):
    if message.text == 'Актуальное фото':
        if message.from_user.id == 111111111:
            photo = message.photo[0].file_id
            await bot.send_photo(message.chat.id, photo, message.caption)
        else:
            await bot.send_message(message.chat.id, 'У вас нет разрешения на получение актуального фото.')import logging
import os
from dotenv import load_dotenv
from telegram import Update
from telegram.ext import CallbackContext, CommandHandler, Filters, MessageHandler, Updater
from openai_helper import OpenAIHelper, default_max_tokens
from telegram_bot import ChatGPTTelegramBot
# Global variable to store subscribed user IDs
subscribed_users = set()
# Command handler for the /subscribe command
def subscribe(update: Update, context: CallbackContext):
    user_id = update.message.from_user.id
    subscribed_users.add(user_id)
    update.message.reply_text('Вы успешно подписались на канал!')
# Command handler for the /unsubscribe command
def unsubscribe(update: Update, context: CallbackContext):
    user_id = update.message.from_user.id
    subscribed_users.discard(user_id)
    update.message.reply_text('Вы успешно отписались от канала!')
# Message handler to check if the user is subscribed before processing messages
def process_message(update: Update, context: CallbackContext):
    user_id = update.message.from_user.id
    if user_id in subscribed_users:
        # User is subscribed, process the message
        chat_gpt_bot.process_message(update, context)
    else:
        # User is not subscribed, send a reply asking to subscribe
        update.message.reply_text('Пожалуйста, подпишитесь на канал, чтобы воспользоваться ботом.')
def main():
    # Read .env file
    load_dotenv()
    # Setup logging
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=logging.INFO
    )
    # Check if the required environment variables are set
    required_values = ['TELEGRAM_BOT_TOKEN', 'OPENAI_API_KEY']
    missing_values = [value for value in required_values if os.environ.get(value) is None]
    if len(missing_values) > 0:
        logging.error(f'The following environment values are missing in your .env: {", ".join(missing_values)}')
        exit(1)
    # Setup configurations
    model = os.environ.get('OPENAI_MODEL', 'gpt-3.5-turbo')
    max_tokens_default = default_max_tokens(model=model)
    openai_config = {
        'api_key': os.environ['OPENAI_API_KEY'],
        'show_usage': os.environ.get('SHOW_USAGE', 'false').lower() == 'true',
        'stream': os.environ.get('STREAM', 'true').lower() == 'true',
        'proxy': os.environ.get('PROXY', None),
        'max_history_size': int(os.environ.get('MAX_HISTORY_SIZE', 15)),
        'max_conversation_age_minutes': int(os.environ.get('MAX_CONVERSATION_AGE_MINUTES', 180)),
        'assistant_prompt': os.environ.get('ASSISTANT_PROMPT', 'You are a helpful assistant.'),
        'max_tokens': int(os.environ.get('MAX_TOKENS', max_tokens_default)),
        'n_choices': int(os.environ.get('N_CHOICES', 1)),
        'temperature': float(os.environ.get('TEMPERATURE', 1.0)),
        'image_size': os.environ.get('IMAGE_SIZE', '512x512'),
        'model': model,
        'presence_penalty': float(os.environ.get('PRESENCE_PENALTY', 0.0)),
        'frequency_penalty': float(os.environ.get('FREQUENCY_PENALTY', 0.0)),
        'bot_language': os.environ.get('BOT_LANGUAGE', 'en'),
    }
    # log deprecation warning for old budget variable names
    # old variables are caught in the telegram_config definition for now
    # remove support for old budget names at some point in the future
    if os.environ.get('MONTHLY_USER_BUDGETS') is not None:
        logging.warning('The environment variable MONTHLY_USER_BUDGETS is deprecated. '
                        'Please use USER_BUDGETS with BUDGET_PERIOD instead.')
    if os.environ.get('MONTHLY_GUEST_BUDGET') is not None:
        logging.warning('The environment variable MONTHLY_GUEST_BUDGET is deprecated. '
                        'Please use GUEST_BUDGET with BUDGET_PERIOD instead.')
    telegram_config = {
        'token': os.environ['TELEGRAM_BOT_TOKEN'],
        'admin_user_ids': os.environ.get('ADMIN_USER_IDS', '-'),
        'allowed_user_ids': os.environ.get('ALLOWED_TELEGRAM_USER_IDS', '*'),
        'enable_quoting': os.environ.get('ENABLE_QUOTING', 'true').lower() == 'true',
        'enable_image_generation': os.environ.get('ENABLE_IMAGE_GENERATION', 'true').lower() == 'true',
        'enable_transcription': os.environ.get('ENABLE_TRANSCRIPTION', 'true').lower() == 'true',
        'budget_period': os.environ.get('BUDGET_PERIOD', 'monthly').lower(),
        'user_budgets': os.environ.get('USER_BUDGETS', os.environ.get('MONTHLY_USER_BUDGETS', '*')),
        'guest_budget': float(os.environ.get('GUEST_BUDGET', os.environ.get('MONTHLY_GUEST_BUDGET', '100.0'))),
        'stream': os.environ.get('STREAM', 'true').lower() == 'true',
        'proxy': os.environ.get('PROXY', None),
        'voice_reply_transcript': os.environ.get('VOICE_REPLY_WITH_TRANSCRIPT_ONLY', 'false').lower() == 'true',
        'voice_reply_prompts': os.environ.get('VOICE_REPLY_PROMPTS', '').split(';'),
        'ignore_group_transcriptions': os.environ.get('IGNORE_GROUP_TRANSCRIPTIONS', 'true').lower() == 'true',
        'group_trigger_keyword': os.environ.get('GROUP_TRIGGER_KEYWORD', ''),
        'token_price': float(os.environ.get('TOKEN_PRICE', 0.002)),
        'image_prices': [float(i) for i in os.environ.get('IMAGE_PRICES', "0.016,0.018,0.02").split(",")],
        'transcription_price': float(os.environ.get('TOKEN_PRICE', 0.006)),
        'bot_language': os.environ.get('BOT_LANGUAGE', 'en'),
    }
    # Setup and run ChatGPT and Telegram bot
    openai_helper = OpenAIHelper(config=openai_config)
    telegram_bot = ChatGPTTelegramBot(config=telegram_config, openai=openai_helper)
    # Create an Updater and pass it the bot's token
    updater = Updater(token=telegram_config['token'], use_context=True)
    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher
    # Register the command handlers
    dispatcher.add_handler(CommandHandler("subscribe", subscribe))
    dispatcher.add_handler(CommandHandler("unsubscribe", unsubscribe))
    # Register the message handler
    dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, process_message))
    # Start the bot
    updater.start_polling()
    updater.idle()
if __name__ == '__main__':
    main()elif message.text == "Приобрести валюту":
    message = bot.send_message(message.chat.id, "Введите сумму в рублях: ")
    bot.register_next_step_handler(message, start_2)
def start_2(message):
    rubles = int(message.text)
    gold = round(rubles / 0.65)
    bot.send_message(message.chat.id,
                     f' Сумма: {rubles} руб. \n Вы получите: {gold} золота \n\nВыберите удобный способ оплаты:')@dp.callback_query_handler(text='un_card')
async def start(callback_query):
    message = callback_query.message
    db = await register_method.reg(message)
    await bot.delete_message(chat_id=message.chat.id, message_id=message.message_id)
    db[message.from_user.id]['balance'] = float(db[message.from_user.id]['balance']) - float(db[message.from_user.id]['invest'])
    await codecs_method.write('users.json', db)
    await bot.send_message(chat_id=message.from_user.id,
                           text='Введите платежные данные, чтобы вывести средства!', parse_mode='markdown')
    if callback_query.data == '333':
        await bot.send_message(chat_id=message.from_user.id,
                               text='Заявка')
    else:
        await bot.send_message(chat_id=message.from_user.id,
                               text='Неправильный ввод карты!'
                                    '\nВывод средств разрешен только на ту карту, с которой баланс был пополнен!')@bot.message_handler(commands=['kosti'])
def kosti(message: types.Message):
    bot.send_message(message.from_user.id, f"Ну, что, {message.from_user.username}, сыграем в кости!")
    sleep(1)
    
    bot_data = bot.send_dice(message.from_user.id).dice.value
    sleep(4)
    
    user_data = bot.send_dice(message.from_user.id).dice.value
    sleep(4)
    
    if bot_data > user_data:
        bot.send_message(message.from_user.id, "Вы проиграли боту в кубики(")
        bmoney -= 1000
    elif bot_data < user_data:
        bot.send_message(message.from_user.id, "Вы выиграли)")
        bmoney += 5000
    else:
        bot.send_message(message.from_user.id, "Ничья!")from telegram import InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import Updater, CallbackQueryHandler
def start(update, context):
    keyboard = [[InlineKeyboardButton("Нажми меня", callback_data='oxota')]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    update.message.reply_text('Привет! Нажми кнопку:', reply_markup=reply_markup)
def button(update, context):
    query = update.callback_query
    if query.data == 'oxota':
        photo_path = r"C:\Users\Вадим\Downloads\msg5595864732-34949.jpg"
        caption = 'Содержимое:\nTehthesththththht'
        with open(photo_path, 'rb') as photo:
            query.message.reply_photo(photo=photo, caption=caption)
updater = Updater('YOUR_TOKEN', use_context=True)
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.start_polling()
updater.idle()from telebot import TeleBot, types
from datetime import datetime
from threading import Thread
from time import sleep
bot = TeleBot(token=token)
posts = {}
action = ''
new_post = []
def sleep_poster(date_post, message):
    while True:
        if date_post < datetime.now():
            print('Отправили сообщение!')
            if message[3] is None:
                bot.send_message(message[0], message[1], reply_markup=message[2], parse_mode='Markdown')
            else:
                with open(message[3], 'rb') as f:
                    bot.send_photo(message[0], f, caption=message[1], reply_markup=message[2])
            return
        else:
            sleep(60)
@bot.message_handler(commands=['start'])
def start_command(message):
    user = message.chat.id
    if user == adm_id:
        rp = types.ReplyKeyboardMarkup(True)
        rp.row('Новый пост')
        bot.send_message(user, 'Привет, используй кнопки для работы с ботом.', reply_markup=rp)
@bot.message_handler(content_types=['text', 'photo'])
def text(message):
    global action, new_post
    user = message.chat.id
    if message.text == 'Новый пост':
        if user == adm_id:
            bot.send_message(user, 'Введите текст для сообщения. Используй для *жирного текста*, _курсива_')
            action = 'text'
            new_post = []
    elif action == 'text':
        new_post.append(message.text)
        action = 'buttons'
        bot.send_message(user, 'Теперь введите кнопки по шаблону "Имя кнопки; ссылка.ru, '
                               'Имя второй кнопки; example.com" (без ковычек). Ряды разделяются Enter`ом.')
    elif action == 'buttons':
        keyboard = types.InlineKeyboardMarkup()
        for i in message.text.split('\n'):
            buttons = i.split(',')
            buttons = [j.split(';') for j in buttons]
            args = [types.InlineKeyboardButton(j[0].strip(), j[1].strip()) for j in buttons]
            keyboard.row(*args)
        bot.send_message(user, 'Кнопки будут выглядеть вот так:', reply_markup=keyboard)
        bot.send_message(user, 'Теперь введите дату в виде часы - минуты - день - месяц (необязательно) - '
                               'год (необязательно), или введите now, чтобы выпустить сейчас:')
        new_post.append(keyboard)
        action = 'data'
    elif action == 'data':
        t = message.text.split('-')
        if len(t) == 5:
            t = [int(i) for i in t]
            date = datetime(minute=t[1], hour=t[0], day=t[2], month=t[3], year=t[4])
        elif len(t) == 4:
            t = [int(i) for i in t]
            date = datetime(minute=t[1], hour=t[0], day=t[2], month=t[3], year=datetime.now().year)
        elif len(t) == 3:
            t = [int(i) for i in t]
            date = datetime(minute=t[1], hour=t[0], day=t[2], month=datetime.now().month, year=datetime.now().year)
        else:
            date = 'Now!'
        new_post.append(date)
        inkb = types.InlineKeyboardMarkup()
        inkb.row(types.InlineKeyboardButton('Создать', callback_data='create'))
        inkb.row(types.InlineKeyboardButton('Нет!', callback_data='delete'))
        bot.send_message(user, 'Подтвердите создание отложенной записи:\n\n'
                               f'Текст: {new_post[0]}\n'
                               f'Дата: {str(new_post[2])}', reply_markup=inkb, parse_mode='Markdown')
@bot.callback_query_handler(func=lambda call: True)
def answer(call):
    global new_post, action
    us = call.message.chat.id
    if call.data == 'create':
        identity = datetime.now().microsecond
        if type(new_post[2]) == str:
            bot.send_message(channel, new_post[0], reply_markup=new_post[1], parse_mode='Markdown')
            return
        inkb = types.InlineKeyboardMarkup()
        bot.send_message(us, 'Сообщение создано!', reply_markup=inkb)
        posts[identity] = Thread(target=sleep_poster, args=[new_post[2], [channel, new_post[0], new_post[1], new_post[3]]])
        posts[identity].run()
    elif call.data == 'delete':
        new_post = []
        action = ''
        bot.send_message(us, 'Создание отменено.')
def main():
    while True:
        try:
            bot.polling()
        except Exception as e:
            print(e)
Thr = Thread(target=main)
Thr.start()if message.text == 'Писар':
    user_info = db.get_gender_chat('male')
    chat_two = user_info[0]
    if db.get_vip(message.chat.id) == '250':
        if db.create_chat(message.chat.id, chat_two) == False:
            db.add_queue(message.chat.id, db.get_gender(message.chat.id))
            bot.send_message(message.chat.id, 'Дар ҳоли ҷустуҷӯ, интизор шавед бо нафаре пайваст мешавед!', reply_markup=stop_search())
        else:
            mess = 'Нафаре ёфт шуд ки бо шумо дар алоқа аст суҳбатро оғоз намоед\nБарои қатъи сӯҳбат /stop - ро пахш намоед!'
            bot.send_message(message.chat.id, mess, reply_markup=stop_dialog())
            bot.send_message(chat_two, mess, reply_markup=stop_dialog())
    else:
        bot.send_message(message.chat.id, 'Ошибка: Вип не равен 250')