I can't run my code

My code starts without errors and after 10-20 seconds it turns off without errors either

import logging
import json
import requests
import random
import time

from telegram import Update
from telegram.ext import Updater, CommandHandler, MessageHandler, filters, CallbackContext

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)

TOKEN = ''

BITCOIN_API_URL = 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd'

BITCOIN_API_URL = 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd'


def get_bitcoin_rate():
  try:
    response = requests.get(BITCOIN_API_URL)
    data = response.json()
    return data.get('bitcoin', {}).get('usd', 0)
  except Exception as e:
    logging.error(f"Error fetching bitcoin rate: {str(e)}")
    return 0


def format_number(number):
  return '{:,.2f}'.format(number).replace(',', ' ')


def load_player_data():
  try:
    with open('player_data.json', 'r') as file:
      return json.load(file)
  except FileNotFoundError:
    return {}


def save_player_data(data):
  with open('player_data.json', 'w') as file:
    json.dump(data, file, indent=4)


def start(update, context):
  user = update.effective_user
  update.message.reply_html(f"hello, {user.mention_html()}!\n\n"
                            "Welcome! With me, you have a good time!")


def balance(update: Update, context: CallbackContext):
  user_id = update.effective_user.id
  player_data = load_player_data()
  if str(user_id) in player_data:
    user_data = player_data[str(user_id)]
    user_money_balance = user_data.get('money_balance', 0)
    user_bank_balance = user_data.get('bank_balance', 0)
    user_bitcoin_balance = user_data.get('bitcoin_balance', 0)
    bitcoin_rate = get_bitcoin_rate()

    formatted_money_balance = format_number(user_money_balance)
    formatted_bank_balance = format_number(user_bank_balance)

    update.message.reply_html(f"Nickname: @{update.effective_user.username}\n"
                              f"💰Money: {formatted_money_balance}$\n"
                              f"🏦Bank: {formatted_bank_balance}$\n"
                              f"💽Bitcoins: {user_bitcoin_balance} BTC\n")
  else:
    update.message.reply_html("you are new player create a account  /start.")


def mine_bitcoins(update: Update, context: CallbackContext):
  user_id = update.effective_user.id
  player_data = load_player_data()
  user_data = player_data.get(str(user_id), {})

  current_time = int(time.time())
  last_mining_time = user_data.get('last_mining_time', 0)
  energy = user_data.get('energy', 10)
  experience = user_data.get('experience', 0)
  max_energy = user_data.get('max_energy', 10)

  if current_time - last_mining_time >= 3600:
    energy = min(energy + 10, max_energy)

  if energy >= 1:
    # Изменения для опыта: добавляем случайное количество опыта от 6 до 29.
    experience += random.randint(6, 29)

    mined_bitcoins = random.randint(2, 5)
    energy -= 1

    user_data['energy'] = energy
    user_data['experience'] = experience
    user_data['last_mining_time'] = current_time

    if 'max_energy' not in user_data:
      user_data['max_energy'] = 10

    if 'max_energy_upgrade_count' not in user_data:
      user_data['max_energy_upgrade_count'] = 0

    if experience >= 1000 * (user_data['max_energy_upgrade_count'] + 1):
      user_data['max_energy'] += 10
      user_data['max_energy_upgrade_count'] += 1

    user_data['bitcoin_balance'] = user_data.get('bitcoin_balance',
                                                 0) + mined_bitcoins

    save_player_data(player_data)

    update.message.reply_html(
        f"@{update.effective_user.username}, you have successfully mined {mined_bitcoins} BTC."
        f"\n💡 Energy: {energy}, experience: {experience}"
        f"\nYour current max energy: {user_data['max_energy']}")
  else:
    update.message.reply_html(
        "Not enough energy for mining. Wait for energy to replenish.")


def text_message(update: Update, context: CallbackContext):
  user_id = update.effective_user.id
  player_data = load_player_data()
  if str(user_id) not in player_data:
    player_data[str(user_id)] = {
        'money_balance': 50000,
        'bank_balance': 0,
        'bitcoin_balance': 0.0,
        'energy': 10,
        'experience': 0,
        'last_mining_time': 0,
        'max_energy': 10,
        'max_energy_upgrade_count': 0
    }
    save_player_data(player_data)

  user_data = player_data[str(user_id)]
  user_money_balance = user_data.get('money_balance', 0)
  user_bank_balance = user_data.get('bank_balance', 0)
  user_bitcoin_balance = user_data.get('bitcoin_balance', 0)
  bitcoin_rate = get_bitcoin_rate()

  text = update.message.text.lower()

  if text.startswith("bank deposit"):
    try:
      amount = float(text.split()[-1])
      if amount > 0 and user_money_balance >= amount:
        user_data['bank_balance'] += amount
        user_data['money_balance'] -= amount
        save_player_data(player_data)
        update.message.reply_html(
            f"You have successfully deposited {amount}$ into the bank.")
      else:
        update.message.reply_html(
            "Not enough funds to complete the operation.")
    except ValueError:
      update.message.reply_html(
          "Please specify a valid amount for the 'bank deposit' operation.")

  elif text.startswith("bank withdraw"):
    try:
      amount = float(text.split()[-1])
      if amount > 0 and user_bank_balance >= amount:
        user_data['bank_balance'] -= amount
        user_data['money_balance'] += amount
        save_player_data(player_data)
        update.message.reply_html(
            f"You have successfully withdrawn {amount}$ from the bank.")
      else:
        update.message.reply_html(
            "Not enough funds to complete the operation.")
    except ValueError:
      update.message.reply_html(
          "Please specify a valid amount for the 'bank withdraw' operation.")

  elif text.startswith("buy bitcoin"):
    try:
      amount = float(text.split()[-1])
      bitcoin_cost = amount * bitcoin_rate
      if amount > 0 and user_money_balance >= bitcoin_cost:
        user_data['bitcoin_balance'] += amount
        user_data['money_balance'] -= bitcoin_cost
        save_player_data(player_data)
        update.message.reply_html(
            f"@{update.effective_user.username}, you have successfully bought {amount} BTC for {format_number(bitcoin_cost)}$ 🌐"
        )
      else:
        update.message.reply_html(
            "Not enough funds to buy this amount of bitcoin.")
    except ValueError:
      update.message.reply_html(
          "Please specify a valid amount for the 'buy bitcoin' operation.")

  elif text.startswith("sell bitcoin"):
    try:
      amount = float(text.split()[-1])
      if amount > 0 and user_bitcoin_balance >= amount:
        bitcoin_earnings = amount * bitcoin_rate
        user_data['bitcoin_balance'] -= amount
        user_data['money_balance'] += bitcoin_earnings
        save_player_data(player_data)
        update.message.reply_html(
            f"@{update.effective_user.username}, you have successfully sold {amount} BTC for {format_number(bitcoin_earnings)}$ 🌐"
        )
      else:
        update.message.reply_html(
            "Not enough bitcoin to complete the operation.")
    except ValueError:
      update.message.reply_html(
          "Please specify a valid amount for the 'sell bitcoin' operation.")

  elif text == "balance":
    balance(update, context)

  elif text == "bank":
    formatted_bank_balance = format_number(user_bank_balance)
    update.message.reply_html("🏦Bank Menu\n"
                              f"Nickname: @{update.effective_user.username}\n"
                              f"On your account {formatted_bank_balance}$")

  elif text == "bitcoin rate":
    update.message.reply_html(
        f"@{update.effective_user.username}, on the current moment, 1 BTC rate is {bitcoin_rate}$ 🌐"
    )

  elif text == "mine bitcoins" or text == "/mine_bitcoins":
    mine_bitcoins(update, context)


def main():
  updater = Updater(TOKEN)
  dispatcher = updater.dispatcher

  dispatcher.add_handler(CommandHandler("start", start))
  dispatcher.add_handler(CommandHandler("balance", balance))
  dispatcher.add_handler(CommandHandler("mine_bitcoins", mine_bitcoins))
  dispatcher.add_handler(
      MessageHandler(Filters.text & ~Filters.command, text_message))

  updater.start_polling()
  updater.idle()

Welcome to Ask! What does this program do exactly?

Bitcoin miners are not allowed on Replit.

I think this is a bitcoin miner simulator game, not a real bitcoin miner…

I went to that site. Seems like legit bitcoin to me. :man_shrugging: I’m not crypto expert.

they use real bitcoin data for their simulator but its not mining any bitcoin it seems

I’m not an expert but if I were to guess why it isn’t working, I would say that you never called any of your functions so none of them are being run.

1 Like

I’d assume so… There is a main function but it isn’t being called. Adding this code to the bottom of the file could work:

if __name__ == "__main__":
    main()

This would run the main function and therefore start the app, which seems to be (as described above) a Telegram bot that allows players to play a virtual Bitcoin mining simulator game using real values for the base.

4 Likes