Помогите допилить код бота

Помогите пожалуйста допилить бота. На данном этапе выдаёт ошибку:

c:\Users\Klim\Desktop\NewBot.py:96: RuntimeWarning: coroutine 'main' was never awaited main() RuntimeWarning: Enable tracemalloc to get the object allocation traceback

Вот код:

import requests
import logging
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, filters
import asyncio

# Включаем логирование
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)

# Конфигурация
TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'  # Замените на фактический токен вашего бота
REGION = 'ru'                       # Регион, например, 'eu'

# Используем словарь для хранения отслеживаемых параметров для каждого чата
chat_data = {}

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text('Привет! Я бот для отслеживания аукционных лотов. '
                                    'Используйте команду /track <item> <price> для начала отслеживания, '
                                    'например: /track helmet 150')


async def check_auctions(context: ContextTypes.DEFAULT_TYPE) -> None:
    chat_id = context.job.context
    if chat_id not in chat_data or not chat_data[chat_id].get('item') or not chat_data[chat_id].get('price_threshold'):
        return

item = chat_data[chat_id]['item']
price_threshold = chat_data[chat_id]['price_threshold']
previous_lots = chat_data[chat_id].get('previous_lots', [])
 
url = f"https://eapi.stalcraft.net/{REGION}/auction/{item}/lots"
try:
    response = requests.get(url)
    response.raise_for_status()  # Raise HTTPError for bad responses (4xx or 5xx)
    data = response.json()

    if 'data' in data and data['data']:
        lots = data['data']
        for lot in lots:
            if lot['price'] <= price_threshold and lot not in previous_lots:
                await context.bot.send_message(chat_id=chat_id, text=f"Новый лот найден: {lot}")
                previous_lots.append(lot)
        
        if len(previous_lots) > 10:
            previous_lots.pop(0)


        chat_data[chat_id]['previous_lots'] = previous_lots
    else:
        logger.warning(f"No data found for item: {item} in chat_id: {chat_id}")

except requests.exceptions.RequestException as e:
    logger.error(f"Error fetching auction data: {e} for chat_id: {chat_id}")
except ValueError as e:
    logger.error(f"Error parsing json response {e} for chat_id: {chat_id}")



async def track_item(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat_id = update.message.chat.id
    try:
        item = context.args[0]
        price_threshold = int(context.args[1])
    except (IndexError, ValueError):
        await update.message.reply_text('Пожалуйста, используйте команду /track <item> <price>, например: /track helmet 150')
        return
    
    if chat_id not in chat_data:
        chat_data[chat_id] = {}

    chat_data[chat_id]['item'] = item
    chat_data[chat_id]['price_threshold'] = price_threshold
    chat_data[chat_id]['previous_lots'] = [] # reset previous lots if we are starting a new tracking

    
    if 'job' in chat_data[chat_id] and chat_data[chat_id]['job']:
            chat_data[chat_id]['job'].schedule_removal()  # Remove the existing job if one exists
    
    job = context.job_queue.run_repeating(check_auctions, interval=10, first=0, context=chat_id)
    chat_data[chat_id]['job'] = job
    await update.message.reply_text(f'Начинаю отслеживание лотов для предмета {item} по цене не выше {price_threshold}!')

async def main() -> None:
    app = ApplicationBuilder().token(TOKEN).build()

    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("track", track_item))

    await app.run_polling()

if __name__ == '__main__':
    main() 

Заранее спасибо за помощь.


Ответы (1 шт):

Автор решения: CrazyElf
async def main() -> None:
    ...
if __name__ == '__main__':
    main() 

RuntimeWarning: coroutine 'main' was never awaited

Ну потому что асинхронную функцию main нужно тоже запускать асинхронно:

asyncio.run(main())

Хотя в вашем случае скорее наоборот нужно сделать main не асинхронной функцией, а обычной:

def main() -> None:
    app = ApplicationBuilder().token(TOKEN).build()

    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("track", track_item))

    app.run_polling()

По крайней мере, судя по этому примеру.

→ Ссылка