Короче я заебался самостоятельно каждый раз ебашить таблицы и сделал небольшой бот , который упрощает это все Функционал: - Ввод дохода за сегодняшний день - Изменение дохода в таблице за любой день месяца - Автоматическое создание месячной таблицы разделенная на 4 недели - Ввод дохода в рублях либо долларах - Автоматическая конвертация долларов в рубли (курс настраивается в коде) - Автоматический подсчет дохода за неделю и месяц в рублях и долларах сразу - Небольшой прикольчик после ввода заработанных бабок (но там сыро немного , мне лень доделывать) Видео функционала бота сам код (не ебу как на гитхаб заливать так что просто так закину) import telebot from telebot import types import datetime import pytz import sqlite3 import re bot = telebot.TeleBot('$$$$$$$$$$$$$$$$$$$$$$') # СЮДА ТОКЕН ЕБАШЬТЕ user_states = {} def init_db(): conn = sqlite3.connect('profits.db', check_same_thread=False) c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS profits (user_id INTEGER, date TEXT, amount REAL)''') conn.commit() conn.close() @bot.message_handler(commands=['profit']) def show_profit(message): show_profit_message(message) @bot.message_handler(commands=['start']) def start(message): welcome_text = """ *СЛУШАЙ СЮДА, БОЕЦ!* Ты здесь не для того, чтобы быть как все эти овощи вокруг! Ты здесь, чтобы ЗАРАБАТЫВАТЬ! Команды для настоящих воинов: /profit - глянуть, сколько ты ВЫЖАЛ из этого месяца /edit - переписать доход, если облажался ВАЖНАЯ Х**НЯ: • До 500 - считаем в баксах ($) • От 500 - считаем в деревянных (₽) """ bot.send_message(message.chat.id, welcome_text, parse_mode='Markdown', reply_markup=create_main_menu_markup()) def get_motivation_message(amount): is_rubles = amount >= 500 dollars = amount / 83 if is_rubles else amount messages = { 10: " БЛЯТЬ, ты серьезно? $10 за день?! Ты же не ебаная крыса, чтобы довольствоваться крохами! ВСТАВАЙ И ДЕЙСТВУЙ! ", 25: " $25 за день... Неплохо для сучки, которая боится рисковать! Хочешь так и остаться среди нищебродов?! ВЪЁБЫВАЙ СИЛЬНЕЕ! ", 50: " $50 в день - уже что-то! Но ты всё ещё ходишь по охуенно тонкому льду! Не время расслабляться, ПИЗДУЙ РАБОТАТЬ! ", 75: " $75 за день... Начинаешь понимать, как устроен этот ебучий мир! Но это всё ещё НИХУЯ! Давай, покажи на что способен! ", 100: " ОХУЕННО! Сотка баксов в день - ты начинаешь вызывать уважение! Но не вздумай останавливаться, СУКА! ТОЛЬКО ВПЕРЁД! ", 150: " ЕБАТЬ ТЫ МОНСТР! $150 за день - теперь ты понимаешь, что значит НАСТОЯЩИЙ заработок! Продолжай рвать эту систему! ", 200: " ДВЕСТИ БАКСОВ, СУКА! Ты превращаешься в машину по заработку! Но помни - остановишься, и система СОЖРЁТ тебя! РАБОТАЕМ! ", 250: " ЕБАТЬ ТЫ ЗВЕРЬ! $250 в день - ты уже в высшей лиге! Но знаешь что? ВСЕГДА ЕСТЬ КУДА РАСТИ! НЕ ТОРМОЗИ! " } thresholds = sorted(messages.keys()) for threshold in thresholds: if dollars <= threshold: return messages[threshold] + f"\n\n{'' if is_rubles else ''} Доход: {'₽' if is_rubles else '$'}{amount:.2f}" return " ЕБАТЬ-КОЛОТИТЬ! ТЫ ПРОСТО МАШИНА ЗАРАБОТКА! Система пытается тебя сожрать, но ты СИЛЬНЕЕ! ПРОДОЛЖАЙ РВАТЬ ЭТОТ МИР! " + f"\n\n{'' if is_rubles else ''} Доход: {'₽' if is_rubles else '$'}{amount:.2f}" def create_main_menu_markup(): markup = types.InlineKeyboardMarkup() btn1 = types.InlineKeyboardButton(" Ввести доход за сегодня", callback_data="enter_profit") btn2 = types.InlineKeyboardButton(" Изменить доход", callback_data="edit_profit") btn3 = types.InlineKeyboardButton(" Доход за месяц", callback_data="show_profit") markup.add(btn1) markup.add(btn2) markup.add(btn3) return markup def create_back_menu_markup(include_profit=True): markup = types.InlineKeyboardMarkup() if include_profit: btn1 = types.InlineKeyboardButton(" Твой месячный доход", callback_data="show_profit") btn2 = types.InlineKeyboardButton(" Главное меню", callback_data="back_to_menu") if include_profit: markup.add(btn1) markup.add(btn2) return markup @bot.callback_query_handler(func=lambda call: True) def callback_handler(call): if call.data == "back_to_menu": user_states.pop(call.from_user.id, None) bot.edit_message_text( " Главное меню", call.message.chat.id, call.message.message_id, reply_markup=create_main_menu_markup() ) if call.data == "enter_profit": user_states[call.from_user.id] = "waiting_for_profit" bot.edit_message_text( " Введите сумму заработка за сегодня:\n\n Числа до 500 считаются в долларах ($)\nЧисла от 500 считаются в рублях (₽)", call.message.chat.id, call.message.message_id, reply_markup=create_back_menu_markup(include_profit=False) ) elif call.data == "edit_profit": user_states[call.from_user.id] = "waiting_for_date" bot.edit_message_text( " Введите дату в формате ДД.ММ:", call.message.chat.id, call.message.message_id, reply_markup=create_back_menu_markup(include_profit=False) ) elif call.data == "show_profit": show_profit_message(call.message) def show_profit_message(message): conn = sqlite3.connect('profits.db', check_same_thread=False) c = conn.cursor() current_month = datetime.datetime.now(pytz.timezone('Asia/Omsk')).strftime('%m') c.execute("SELECT date, amount FROM profits WHERE user_id=? AND date LIKE ?", (message.chat.id, f'%.{current_month}')) profits = dict(c.fetchall()) conn.close() table = " *Ваш доход за текущий месяц:*\n\n" def get_amount_emoji(amount): if amount >= 500: # рубли amount_usd = amount / 83 else: # доллары amount_usd = amount if amount_usd < 10: return "" elif amount_usd < 25: return "" elif amount_usd < 50: return "" elif amount_usd < 75: return "" elif amount_usd < 100: return "" elif amount_usd < 150: return "" elif amount_usd < 200: return "" else: return "" def format_amount(amount): if amount >= 500: # рубли usd_amount = amount / 83 return f"{usd_amount:.2f}$ ({amount:.2f}₽)" else: # доллары rub_amount = amount * 83 return f"{amount:.2f}$ ({rub_amount:.2f}₽)" total_month_usd = 0 total_month_rub = 0 for week in range(1, 5): table += f" *Неделя {week}:*\n" start_day = (week - 1) * 7 + 1 end_day = week * 7 + 1 week_total_usd = 0 week_total_rub = 0 for day in range(start_day, end_day): date = f"{day:02d}.{current_month}" if date in profits: amount = profits[date] if amount >= 500: # рубли week_total_usd += amount / 83 week_total_rub += amount else: # доллары week_total_usd += amount week_total_rub += amount * 83 emoji = get_amount_emoji(amount) formatted_amount = format_amount(amount) table += f"{emoji} {date}: *{formatted_amount}*\n" else: if datetime.datetime.strptime(date, '%d.%m') > datetime.datetime.now(): table += f" {date}: Ещё не въебывали\n" else: table += f"✦ {date}: ...\n" total_month_usd += week_total_usd total_month_rub += week_total_rub table += f"*Итого за неделю:* {week_total_usd:.2f}$ ({week_total_rub:.2f}₽)\n\n" table += f"\n *Общий доход за месяц:* {total_month_usd:.2f}$ ({total_month_rub:.2f}₽)" markup = types.InlineKeyboardMarkup() edit_btn = types.InlineKeyboardButton(" Редактировать доход", callback_data="edit_profit") menu_btn = types.InlineKeyboardButton(" Главное меню", callback_data="back_to_menu") markup.add(edit_btn) markup.add(menu_btn) bot.send_message(message.chat.id, table, parse_mode='Markdown', reply_markup=markup) @bot.message_handler(func=lambda message: user_states.get(message.from_user.id) == "waiting_for_profit") def handle_profit(message): try: amount = float(re.sub(r'[^\d.]', '', message.text)) conn = sqlite3.connect('profits.db', check_same_thread=False) c = conn.cursor() today = datetime.datetime.now(pytz.timezone('Asia/Omsk')).strftime('%d.%m') c.execute("INSERT OR REPLACE INTO profits (user_id, date, amount) VALUES (?, ?, ?)", (message.from_user.id, today, amount)) conn.commit() conn.close() motivation = get_motivation_message(amount) bot.reply_to(message, motivation, reply_markup=create_back_menu_markup()) user_states.pop(message.from_user.id, None) except ValueError: bot.reply_to(message, " Пожалуйста, введите корректное число!", reply_markup=create_back_menu_markup(include_profit=False)) @bot.message_handler(func=lambda message: user_states.get(message.from_user.id) == "waiting_for_date") def handle_date(message): if re.match(r'\d{2}\.\d{2}', message.text): user_states[message.from_user.id] = f"waiting_for_profit_edit_{message.text}" bot.reply_to( message, " Введите новую сумму заработка:\n\n Числа до 500 считаются в долларах ($)\nЧисла от 500 считаются в рублях (₽)", reply_markup=create_back_menu_markup(include_profit=False) ) else: bot.reply_to( message, " Неверный формат даты. Используйте ДД.ММ", reply_markup=create_back_menu_markup(include_profit=False) ) @bot.message_handler(func=lambda message: user_states.get(message.from_user.id, "").startswith("waiting_for_profit_edit_")) def handle_edit_profit(message): try: date = user_states[message.from_user.id].split('_')[-1] amount = float(re.sub(r'[^\d.]', '', message.text)) conn = sqlite3.connect('profits.db', check_same_thread=False) c = conn.cursor() c.execute("INSERT OR REPLACE INTO profits (user_id, date, amount) VALUES (?, ?, ?)", (message.from_user.id, date, amount)) conn.commit() conn.close() motivation = get_motivation_message(amount) bot.reply_to(message, motivation, reply_markup=create_back_menu_markup()) user_states.pop(message.from_user.id, None) except ValueError: bot.reply_to( message, " Пожалуйста, введите корректное число!", reply_markup=create_back_menu_markup(include_profit=False) ) @bot.message_handler(commands=['profit']) def show_profit(message): show_profit_message(message) @bot.message_handler(commands=['edit']) def edit_profit(message): user_states[message.from_user.id] = "waiting_for_date" bot.reply_to( message, " Введите дату в формате ДД.ММ:", reply_markup=create_back_menu_markup(include_profit=False) ) def main(): try: print("Initializing bot...") init_db() print("Database initialized") print("Starting bot...") bot.infinity_polling(timeout=60, long_polling_timeout=60) except Exception as e: print(f"Error in main: {e}") finally: print("Bot stopped") if __name__ == '__main__': try: main() except KeyboardInterrupt: print("Bot stopped by user") except Exception as e: print(f"Unexpected error: {e}") Python import telebot from telebot import types import datetime import pytz import sqlite3 import re bot = telebot.TeleBot('$$$$$$$$$$$$$$$$$$$$$$') # СЮДА ТОКЕН ЕБАШЬТЕ user_states = {} def init_db(): conn = sqlite3.connect('profits.db', check_same_thread=False) c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS profits (user_id INTEGER, date TEXT, amount REAL)''') conn.commit() conn.close() @bot.message_handler(commands=['profit']) def show_profit(message): show_profit_message(message) @bot.message_handler(commands=['start']) def start(message): welcome_text = """ *СЛУШАЙ СЮДА, БОЕЦ!* Ты здесь не для того, чтобы быть как все эти овощи вокруг! Ты здесь, чтобы ЗАРАБАТЫВАТЬ! Команды для настоящих воинов: /profit - глянуть, сколько ты ВЫЖАЛ из этого месяца /edit - переписать доход, если облажался ВАЖНАЯ Х**НЯ: • До 500 - считаем в баксах ($) • От 500 - считаем в деревянных (₽) """ bot.send_message(message.chat.id, welcome_text, parse_mode='Markdown', reply_markup=create_main_menu_markup()) def get_motivation_message(amount): is_rubles = amount >= 500 dollars = amount / 83 if is_rubles else amount messages = { 10: " БЛЯТЬ, ты серьезно? $10 за день?! Ты же не ебаная крыса, чтобы довольствоваться крохами! ВСТАВАЙ И ДЕЙСТВУЙ! ", 25: " $25 за день... Неплохо для сучки, которая боится рисковать! Хочешь так и остаться среди нищебродов?! ВЪЁБЫВАЙ СИЛЬНЕЕ! ", 50: " $50 в день - уже что-то! Но ты всё ещё ходишь по охуенно тонкому льду! Не время расслабляться, ПИЗДУЙ РАБОТАТЬ! ", 75: " $75 за день... Начинаешь понимать, как устроен этот ебучий мир! Но это всё ещё НИХУЯ! Давай, покажи на что способен! ", 100: " ОХУЕННО! Сотка баксов в день - ты начинаешь вызывать уважение! Но не вздумай останавливаться, СУКА! ТОЛЬКО ВПЕРЁД! ", 150: " ЕБАТЬ ТЫ МОНСТР! $150 за день - теперь ты понимаешь, что значит НАСТОЯЩИЙ заработок! Продолжай рвать эту систему! ", 200: " ДВЕСТИ БАКСОВ, СУКА! Ты превращаешься в машину по заработку! Но помни - остановишься, и система СОЖРЁТ тебя! РАБОТАЕМ! ", 250: " ЕБАТЬ ТЫ ЗВЕРЬ! $250 в день - ты уже в высшей лиге! Но знаешь что? ВСЕГДА ЕСТЬ КУДА РАСТИ! НЕ ТОРМОЗИ! " } thresholds = sorted(messages.keys()) for threshold in thresholds: if dollars <= threshold: return messages[threshold] + f"\n\n{'' if is_rubles else ''} Доход: {'₽' if is_rubles else '$'}{amount:.2f}" return " ЕБАТЬ-КОЛОТИТЬ! ТЫ ПРОСТО МАШИНА ЗАРАБОТКА! Система пытается тебя сожрать, но ты СИЛЬНЕЕ! ПРОДОЛЖАЙ РВАТЬ ЭТОТ МИР! " + f"\n\n{'' if is_rubles else ''} Доход: {'₽' if is_rubles else '$'}{amount:.2f}" def create_main_menu_markup(): markup = types.InlineKeyboardMarkup() btn1 = types.InlineKeyboardButton(" Ввести доход за сегодня", callback_data="enter_profit") btn2 = types.InlineKeyboardButton(" Изменить доход", callback_data="edit_profit") btn3 = types.InlineKeyboardButton(" Доход за месяц", callback_data="show_profit") markup.add(btn1) markup.add(btn2) markup.add(btn3) return markup def create_back_menu_markup(include_profit=True): markup = types.InlineKeyboardMarkup() if include_profit: btn1 = types.InlineKeyboardButton(" Твой месячный доход", callback_data="show_profit") btn2 = types.InlineKeyboardButton(" Главное меню", callback_data="back_to_menu") if include_profit: markup.add(btn1) markup.add(btn2) return markup @bot.callback_query_handler(func=lambda call: True) def callback_handler(call): if call.data == "back_to_menu": user_states.pop(call.from_user.id, None) bot.edit_message_text( " Главное меню", call.message.chat.id, call.message.message_id, reply_markup=create_main_menu_markup() ) if call.data == "enter_profit": user_states[call.from_user.id] = "waiting_for_profit" bot.edit_message_text( " Введите сумму заработка за сегодня:\n\n Числа до 500 считаются в долларах ($)\nЧисла от 500 считаются в рублях (₽)", call.message.chat.id, call.message.message_id, reply_markup=create_back_menu_markup(include_profit=False) ) elif call.data == "edit_profit": user_states[call.from_user.id] = "waiting_for_date" bot.edit_message_text( " Введите дату в формате ДД.ММ:", call.message.chat.id, call.message.message_id, reply_markup=create_back_menu_markup(include_profit=False) ) elif call.data == "show_profit": show_profit_message(call.message) def show_profit_message(message): conn = sqlite3.connect('profits.db', check_same_thread=False) c = conn.cursor() current_month = datetime.datetime.now(pytz.timezone('Asia/Omsk')).strftime('%m') c.execute("SELECT date, amount FROM profits WHERE user_id=? AND date LIKE ?", (message.chat.id, f'%.{current_month}')) profits = dict(c.fetchall()) conn.close() table = " *Ваш доход за текущий месяц:*\n\n" def get_amount_emoji(amount): if amount >= 500: # рубли amount_usd = amount / 83 else: # доллары amount_usd = amount if amount_usd < 10: return "" elif amount_usd < 25: return "" elif amount_usd < 50: return "" elif amount_usd < 75: return "" elif amount_usd < 100: return "" elif amount_usd < 150: return "" elif amount_usd < 200: return "" else: return "" def format_amount(amount): if amount >= 500: # рубли usd_amount = amount / 83 return f"{usd_amount:.2f}$ ({amount:.2f}₽)" else: # доллары rub_amount = amount * 83 return f"{amount:.2f}$ ({rub_amount:.2f}₽)" total_month_usd = 0 total_month_rub = 0 for week in range(1, 5): table += f" *Неделя {week}:*\n" start_day = (week - 1) * 7 + 1 end_day = week * 7 + 1 week_total_usd = 0 week_total_rub = 0 for day in range(start_day, end_day): date = f"{day:02d}.{current_month}" if date in profits: amount = profits[date] if amount >= 500: # рубли week_total_usd += amount / 83 week_total_rub += amount else: # доллары week_total_usd += amount week_total_rub += amount * 83 emoji = get_amount_emoji(amount) formatted_amount = format_amount(amount) table += f"{emoji} {date}: *{formatted_amount}*\n" else: if datetime.datetime.strptime(date, '%d.%m') > datetime.datetime.now(): table += f" {date}: Ещё не въебывали\n" else: table += f"✦ {date}: ...\n" total_month_usd += week_total_usd total_month_rub += week_total_rub table += f"*Итого за неделю:* {week_total_usd:.2f}$ ({week_total_rub:.2f}₽)\n\n" table += f"\n *Общий доход за месяц:* {total_month_usd:.2f}$ ({total_month_rub:.2f}₽)" markup = types.InlineKeyboardMarkup() edit_btn = types.InlineKeyboardButton(" Редактировать доход", callback_data="edit_profit") menu_btn = types.InlineKeyboardButton(" Главное меню", callback_data="back_to_menu") markup.add(edit_btn) markup.add(menu_btn) bot.send_message(message.chat.id, table, parse_mode='Markdown', reply_markup=markup) @bot.message_handler(func=lambda message: user_states.get(message.from_user.id) == "waiting_for_profit") def handle_profit(message): try: amount = float(re.sub(r'[^\d.]', '', message.text)) conn = sqlite3.connect('profits.db', check_same_thread=False) c = conn.cursor() today = datetime.datetime.now(pytz.timezone('Asia/Omsk')).strftime('%d.%m') c.execute("INSERT OR REPLACE INTO profits (user_id, date, amount) VALUES (?, ?, ?)", (message.from_user.id, today, amount)) conn.commit() conn.close() motivation = get_motivation_message(amount) bot.reply_to(message, motivation, reply_markup=create_back_menu_markup()) user_states.pop(message.from_user.id, None) except ValueError: bot.reply_to(message, " Пожалуйста, введите корректное число!", reply_markup=create_back_menu_markup(include_profit=False)) @bot.message_handler(func=lambda message: user_states.get(message.from_user.id) == "waiting_for_date") def handle_date(message): if re.match(r'\d{2}\.\d{2}', message.text): user_states[message.from_user.id] = f"waiting_for_profit_edit_{message.text}" bot.reply_to( message, " Введите новую сумму заработка:\n\n Числа до 500 считаются в долларах ($)\nЧисла от 500 считаются в рублях (₽)", reply_markup=create_back_menu_markup(include_profit=False) ) else: bot.reply_to( message, " Неверный формат даты. Используйте ДД.ММ", reply_markup=create_back_menu_markup(include_profit=False) ) @bot.message_handler(func=lambda message: user_states.get(message.from_user.id, "").startswith("waiting_for_profit_edit_")) def handle_edit_profit(message): try: date = user_states[message.from_user.id].split('_')[-1] amount = float(re.sub(r'[^\d.]', '', message.text)) conn = sqlite3.connect('profits.db', check_same_thread=False) c = conn.cursor() c.execute("INSERT OR REPLACE INTO profits (user_id, date, amount) VALUES (?, ?, ?)", (message.from_user.id, date, amount)) conn.commit() conn.close() motivation = get_motivation_message(amount) bot.reply_to(message, motivation, reply_markup=create_back_menu_markup()) user_states.pop(message.from_user.id, None) except ValueError: bot.reply_to( message, " Пожалуйста, введите корректное число!", reply_markup=create_back_menu_markup(include_profit=False) ) @bot.message_handler(commands=['profit']) def show_profit(message): show_profit_message(message) @bot.message_handler(commands=['edit']) def edit_profit(message): user_states[message.from_user.id] = "waiting_for_date" bot.reply_to( message, " Введите дату в формате ДД.ММ:", reply_markup=create_back_menu_markup(include_profit=False) ) def main(): try: print("Initializing bot...") init_db() print("Database initialized") print("Starting bot...") bot.infinity_polling(timeout=60, long_polling_timeout=60) except Exception as e: print(f"Error in main: {e}") finally: print("Bot stopped") if __name__ == '__main__': try: main() except KeyboardInterrupt: print("Bot stopped by user") except Exception as e: print(f"Unexpected error: {e}") Так-же необходимо установить в терминальчике следующее pip install pyTelegramBotAPI pip install pytz Курс доллара к рублю редактируем в коде под себя , лично у меня по умолчанию стоит 83 руб Для овощей в начале указал с решеточкой куда вставлять свой токен бота , где доллары и рубли и т.д Заходим в botfather , создаем бота , он кидает токен , мы его закидываем в код. Можно воспользоваться Virtual Studio Code если планируется использовать чисто для себя библиотека telegram-python-bot вроде все расписал , пользуйтесь бесплатно
Pikuli, я такой скрипт делал , но он по итогу наполовину переломался и я хуй забил. мб потом как нибудь сделаю