Navigation X
ALERT
Click here to register with a few steps and explore all our cool stuff we have to offer!



   498

hi everyon i have a big problem on my python code

by Yemnouz - 17 January, 2025 - 07:48 PM
This post is by a banned member (Yemnouz) - Unhide
Yemnouz  
Registered
118
Posts
1
Threads
#1
(This post was last modified: 17 January, 2025 - 08:10 PM by Yemnouz.)
CLICK HERE TO SEE THE ERROR


I Hope someone can help me here is my code 


https://paste.fo/79388abe49a0

im trying to make a bot that can track invitation to my telegram channel and give credit for each invitation people gonna make. after with that credit earned they can buy fortnite account.


plz any help will be loved Feelssadman Feelssadman Feelssadman Feelssadman

This is a bump
This post is by a banned member (OptimOS) - Unhide
OptimOS  
Contributor
107
Posts
44
Threads
6 Years of service
#2
try debugging your code or/and send your output or error message here so we can help
If you don't have cracked.io account

Click Here to Create One For FREE
-----------------------------------
 Telegram : @OptimOSPrime
-----------------------------------
This post is by a banned member (tactics) - Unhide
tactics  
Registered
17
Posts
3
Threads
#3
(This post was last modified: 19 January, 2025 - 06:10 PM by tactics.)
Code:
 
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
import sqlite3
import asyncio
import logging
import os

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

TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
if not TELEGRAM_BOT_TOKEN:
    logger.error("Telegram Bot Token not found.")
    exit(1)

DATABASE_NAME = 'invites.db'
ADMIN_USER_IDS = [123456789]

def get_db_connection():
    conn = None
    try:
        conn = sqlite3.connect(DATABASE_NAME, check_same_thread=False)
        cursor = conn.cursor()
        cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT, credits INTEGER, invites INTEGER)''')
        cursor.execute('''CREATE TABLE IF NOT EXISTS accounts (id INTEGER PRIMARY KEY AUTOINCREMENT, account_info TEXT, price INTEGER)''')
        conn.commit()
    except sqlite3.Error as e:
        logger.error(f"DB connection error: {e}")
        if conn:
            conn.close()
        return None
    return conn

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text('Welcome! Use /invite and /checkcredits.')

async def invite(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    conn = get_db_connection()
    if not conn:
        await update.message.reply_text("DB error.")
        return
    try:
        user_id = update.message.from_user.id
        username = update.message.from_user.username
        conn.execute("INSERT OR IGNORE INTO users (id, username, credits, invites) VALUES (?, ?, 0, 0)", (user_id, username))
        conn.commit()
        link = f"https://t.me/PracezzServicesBot?start={user_id}"
        await update.message.reply_text(f"Invite link: {link}")
    except sqlite3.Error as e:
        logger.error(f"Invite error: {e}")
        await update.message.reply_text("Error generating invite.")
        conn.rollback()
    finally:
        conn.close()

async def track_invite(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    if context.args:
        conn = get_db_connection()
        if not conn:
            return
        try:
            user_id = int(context.args[0])
            conn.execute("UPDATE users SET credits = credits + 10, invites = invites + 1 WHERE id = ?", (user_id,))
            conn.commit()
            logger.info(f"User {user_id} credited.")
        except ValueError:
            logger.warning(f"Invalid user ID: {context.args[0]}")
        except sqlite3.Error as e:
            logger.error(f"Track invite error: {e}")
            conn.rollback()
        finally:
            conn.close()

async def check_credits(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    conn = get_db_connection()
    if not conn:
        await update.message.reply_text("DB error.")
        return
    try:
        cursor = conn.cursor()
        cursor.execute("SELECT credits FROM users WHERE id = ?", (update.message.from_user.id,))
        credits = cursor.fetchone()
        await update.message.reply_text(f"Credits: {credits[0]}" if credits else "No credits.")
    except sqlite3.Error as e:
        logger.error(f"Check credits error: {e}")
        await update.message.reply_text("Error checking credits.")
    finally:
        conn.close()

async def buy_account(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    conn = get_db_connection()
    if not conn:
        await update.message.reply_text("DB error.")
        return
    try:
        user_id = update.message.from_user.id
        cursor = conn.cursor()
        cursor.execute("SELECT credits FROM users WHERE id = ?", (user_id,))
        credits = cursor.fetchone()
        if not credits or credits[0] <= 0:
            await update.message.reply_text("No credits.")
            return
        if not context.args:
            await update.message.reply_text("Provide account ID.")
            return
        try:
            account_id = int(context.args[0])
            cursor.execute("SELECT account_info, price FROM accounts WHERE id = ?", (account_id,))
            account = cursor.fetchone()
            if not account or credits[0] < account[1]:
                await update.message.reply_text("Insufficient credits or account not found.")
                return
            conn.execute("UPDATE users SET credits = credits - ? WHERE id = ?", (account[1], user_id))
            conn.commit()
            await update.message.reply_text(f"Purchased: {account[0]}")
        except ValueError:
            await update.message.reply_text("Invalid account ID.")
    except sqlite3.Error as e:
        logger.error(f"Buy account error: {e}")
        await update.message.reply_text("Purchase error.")
        conn.rollback()
    finally:
        conn.close()

async def add_account(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    if update.message.from_user.id not in ADMIN_USER_IDS:
        await update.message.reply_text("Unauthorized.")
        return
    conn = get_db_connection()
    if not conn:
        await update.message.reply_text("DB error.")
        return
    if not context.args or len(context.args) < 2:
        await update.message.reply_text("Provide account info and price.")
        return
    try:
        price = int(context.args[-1])
        info = ' '.join(context.args[:-1])
        cursor = conn.cursor()
        cursor.execute("INSERT INTO accounts (account_info, price) VALUES (?, ?)", (info, price))
        conn.commit()
        account_id = cursor.lastrowid
        await update.message.reply_text(f"Account '{info}' added with ID {account_id}, price {price}.")
    except ValueError:
        await update.message.reply_text("Invalid price.")
    except sqlite3.Error as e:
        logger.error(f"Add account error: {e}")
        await update.message.reply_text("Error adding account.")
        conn.rollback()
    finally:
        conn.close()

async def list_accounts(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    conn = get_db_connection()
    if not conn:
        await update.message.reply_text("DB error.")
        return
    try:
        cursor = conn.cursor()
        cursor.execute("SELECT id, account_info, price FROM accounts")
        accounts = cursor.fetchall()
        if accounts:
            message = "Available Accounts:\n"
            for acc in accounts:
                message += f"ID: {acc[0]}, Info: {acc[1]}, Price: {acc[2]}\n"
            await update.message.reply_text(message)
        else:
            await update.message.reply_text("No accounts available.")
    except sqlite3.Error as e:
        logger.error(f"List accounts error: {e}")
        await update.message.reply_text("Error listing accounts.")
    finally:
        conn.close()

async def main() -> None:
    if not TELEGRAM_BOT_TOKEN:
        return
    app = ApplicationBuilder().token(TELEGRAM_BOT_TOKEN).build()
    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("invite", invite))
    app.add_handler(CommandHandler("trackinvite", track_invite))
    app.add_handler(CommandHandler("checkcredits", check_credits))
    app.add_handler(CommandHandler("buyaccount", buy_account))
    app.add_handler(CommandHandler("addaccount", add_account))
    app.add_handler(CommandHandler("listaccounts", list_accounts))
    await app.run_polling()

if __name__ == '__main__':
    asyncio.run(main())

or
 
Code:
 
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, filters
import sqlite3
import asyncio
import logging
import os

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

TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
if not TELEGRAM_BOT_TOKEN:
    logger.error("Telegram Bot Token not found.")
    exit(1)

DATABASE_NAME = 'fortnite_invites.db'
ADMIN_USER_IDS = [123456789]  # Replace with your Telegram User ID
CHANNEL_USERNAME = "@your_channel_username"  # Replace with your channel's username
INVITE_CREDITS = 10

def get_db_connection():
    conn = None
    try:
        conn = sqlite3.connect(DATABASE_NAME, check_same_thread=False)
        cursor = conn.cursor()
        cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT, credits INTEGER)''')
        cursor.execute('''CREATE TABLE IF NOT EXISTS accounts (id INTEGER PRIMARY KEY AUTOINCREMENT, account_info TEXT, price INTEGER)''')
        conn.commit()
    except sqlite3.Error as e:
        logger.error(f"DB connection error: {e}")
        if conn:
            conn.close()
        return None
    return conn

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    user = update.message.from_user
    conn = get_db_connection()
    if not conn:
        await update.message.reply_text("Database error.")
        return
    try:
        cursor = conn.cursor()
        cursor.execute("INSERT OR IGNORE INTO users (id, username, credits) VALUES (?, ?, 0)", (user.id, user.username))
        conn.commit()
        if context.args:
            referrer_id = int(context.args[0])
            if referrer_id != user.id:
                cursor.execute("SELECT id FROM users WHERE id = ?", (referrer_id,))
                referrer = cursor.fetchone()
                if referrer:
                    conn.execute("UPDATE users SET credits = credits + ? WHERE id = ?", (INVITE_CREDITS, referrer_id))
                    conn.commit()
                    await context.bot.send_message(referrer_id, f"? {user.username} joined using your invite link! You earned {INVITE_CREDITS} credits.")
        await update.message.reply_text(f"Welcome, {user.username}! Invite friends to the channel and earn credits to buy Fortnite accounts.\nUse /invite to get your link and /credits to check your balance.")
    except sqlite3.Error as e:
        logger.error(f"Start command error: {e}")
        await update.message.reply_text("Error processing your start command.")
        conn.rollback()
    finally:
        conn.close()

async def invite(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    user_id = update.message.from_user.id
    invite_link = f"https://t.me/{context.bot.username}?start={user_id}"
    await update.message.reply_text(f"Share this link to invite others: {invite_link}")

async def credits(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    conn = get_db_connection()
    if not conn:
        await update.message.reply_text("Database error.")
        return
    try:
        cursor = conn.cursor()
        cursor.execute("SELECT credits FROM users WHERE id = ?", (update.message.from_user.id,))
        credits_data = cursor.fetchone()
        credits = credits_data[0] if credits_data else 0
        await update.message.reply_text(f"Your credits: {credits}")
    except sqlite3.Error as e:
        logger.error(f"Credits command error: {e}")
        await update.message.reply_text("Error fetching your credits.")
    finally:
        conn.close()

async def buyaccount(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    conn = get_db_connection()
    if not conn:
        await update.message.reply_text("Database error.")
        return
    try:
        user_id = update.message.from_user.id
        cursor = conn.cursor()
        cursor.execute("SELECT credits FROM users WHERE id = ?", (user_id,))
        credits_data = cursor.fetchone()
        if not credits_data:
            await update.message.reply_text("User not found.")
            return
        credits = credits_data[0]

        if not context.args:
            await update.message.reply_text("Please specify the account ID you want to buy.")
            return

        try:
            account_id = int(context.args[0])
            cursor.execute("SELECT account_info, price FROM accounts WHERE id = ?", (account_id,))
            account = cursor.fetchone()
            if not account:
                await update.message.reply_text("Account not found.")
                return

            account_info, price = account
            if credits >= price:
                conn.execute("UPDATE users SET credits = credits - ? WHERE id = ?", (price, user_id))
                conn.commit()
                await update.message.reply_text(f"Successfully purchased:\n{account_info}\nYour remaining credits: {credits - price}")
            else:
                await update.message.reply_text("Insufficient credits.")
        except ValueError:
            await update.message.reply_text("Invalid account ID.")
    except sqlite3.Error as e:
        logger.error(f"Buy account error: {e}")
        await update.message.reply_text("Error processing your purchase.")
        conn.rollback()
    finally:
        conn.close()

async def addaccount(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    if update.message.from_user.id not in ADMIN_USER_IDS:
        await update.message.reply_text("Unauthorized.")
        return
    conn = get_db_connection()
    if not conn:
        await update.message.reply_text("Database error.")
        return
    if len(context.args) < 2:
        await update.message.reply_text("Usage: /addaccount <account_info> <price>")
        return
    try:
        price = int(context.args[-1])
        account_info = " ".join(context.args[:-1])
        conn.execute("INSERT INTO accounts (account_info, price) VALUES (?, ?)", (account_info, price))
        conn.commit()
        await update.message.reply_text("Account added successfully.")
    except ValueError:
        await update.message.reply_text("Invalid price.")
    except sqlite3.Error as e:
        logger.error(f"Add account error: {e}")
        await update.message.reply_text("Error adding account.")
        conn.rollback()
    finally:
        conn.close()

async def listaccounts(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    conn = get_db_connection()
    if not conn:
        await update.message.reply_text("Database error.")
        return
    try:
        cursor = conn.cursor()
        cursor.execute("SELECT id, account_info, price FROM accounts")
        accounts = cursor.fetchall()
        if not accounts:
            await update.message.reply_text("No accounts available yet.")
            return
        message = "Available Fortnite Accounts:\n"
        for acc_id, info, price in accounts:
            message += f"ID: {acc_id}, Info: {info}, Price: {price} credits\n"
        await update.message.reply_text(message)
    except sqlite3.Error as e:
        logger.error(f"List accounts error: {e}")
        await update.message.reply_text("Error fetching accounts.")
    finally:
        conn.close()

async def handle_member_updates(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    if update.chat_member and update.chat_member.new_chat_member.user.id != context.bot.id:
        user = update.chat_member.new_chat_member.user
        conn = get_db_connection()
        if not conn:
            return
        try:
            cursor = conn.cursor()
            cursor.execute("INSERT OR IGNORE INTO users (id, username, credits) VALUES (?, ?, 0)", (user.id, user.username))
            conn.commit()
            logger.info(f"New member joined the channel: {user.username} ({user.id})")
            # Consider if you want to award credits for direct channel joins as well
        except sqlite3.Error as e:
            logger.error(f"Error handling new member: {e}")
            conn.rollback()
        finally:
            conn.close()

async def main() -> None:
    if not TELEGRAM_BOT_TOKEN:
        return
    app = ApplicationBuilder().token(TELEGRAM_BOT_TOKEN).build()

    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("invite", invite))
    app.add_handler(CommandHandler("credits", credits))
    app.add_handler(CommandHandler("buyaccount", buyaccount))
    app.add_handler(CommandHandler("listaccounts", listaccounts))
    app.add_handler(CommandHandler("addaccount", addaccount))
    app.add_handler(MessageHandler(filters.StatusUpdate.NEW_CHAT_MEMBERS, handle_member_updates))

    await app.run_polling()

if __name__ == '__main__':
    asyncio.run(main())
This post is by a banned member (Overdrive187) - Unhide
234
Posts
86
Threads
4 Years of service
#4
hi i just came across your thread. 
the issue is that you are trying to run main() asynchronously which doesnt work within ptb library 20.
instead dont define main function as async dont run it with async aswell:
fix for your issue
Code:
def main() -> None:
    if not TELEGRAM_BOT_TOKEN:
        return
    app = ApplicationBuilder().token(TELEGRAM_BOT_TOKEN).build()

    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("invite", invite))
    app.add_handler(CommandHandler("credits", credits))
    app.add_handler(CommandHandler("buyaccount", buyaccount))
    app.add_handler(CommandHandler("listaccounts", listaccounts))
    app.add_handler(CommandHandler("addaccount", addaccount))
    app.add_handler(MessageHandler(filters.StatusUpdate.NEW_CHAT_MEMBERS, handle_member_updates))

    app.run_polling()
Code:
if __name__ == '__main__':
[code]
    main()
Code:
 
[/code]

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
or
Sign in
Already have an account? Sign in here.


Forum Jump:


Users browsing this thread: 1 Guest(s)