БОТ TELEGRAM DASHSKINSPython

Программы на Python
Ответить
Anonymous
 БОТ TELEGRAM DASHSKINS

Сообщение Anonymous »

Критерии поиска: боту необходимо искать товары стоимостью выше 150 реалов, но в коде фильтр установлен для значений ниже 200 реалов. Как это исправить?
Обнаружены ошибки: я обнаружил некоторые ошибки, связанные с API и использованием asyncio для бота. Как я могу отладить и решить эти проблемы?
Интеграция API. Ответ API не всегда приходит в ожидаемом формате, что приводит к ошибкам. Как лучше всего обрабатывать неожиданные ответы API?
import os
import requests
from apscheduler.schedulers.background import BackgroundScheduler
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes

# URL da API
API_URL = 'https://dashskins.com.br/api/listing/prices'

# Definir as credenciais do Telegram
TOKEN = os.getenv('TELEGRAM_TOKEN', 'token from bot') # Substitua pelo seu token

all_deals = []

# Inicializa a aplicação globalmente
application = ApplicationBuilder().token(TOKEN).build()

# Inicia o agendador globalmente
scheduler = BackgroundScheduler()
scheduler.start()

def fetch_all_deals_from_site():
all_deals.clear()
try:
response = requests.get(API_URL)
response.raise_for_status()
deals_data = response.json()

if not isinstance(deals_data, dict):
print("Erro: O formato da resposta não é um dicionário.", deals_data)
return

for category, items in deals_data.items():
if isinstance(items, dict):
for name, price in items.items():
# Ajuste o critério de desconto aqui
if isinstance(price, (int, float)) and price < 200:
all_deals.append(f"{name}: R${price:.2f}")
else:
print(f"Formato inesperado para a categoria '{category}': {items}")

except requests.exceptions.HTTPError as http_err:
print(f"Erro HTTP: {http_err}")
except Exception as e:
print(f"Erro durante a requisição à API: {e}")

async def send_message_via_telegram(deals, chat_id):
if deals:
message_chunk = ""
for deal in deals:
if len(message_chunk) + len(deal) + 2 > 4096: # Limite de mensagem do Telegram
await application.bot.send_message(chat_id=chat_id, text=message_chunk)
message_chunk = ""
message_chunk += deal + "\n"
if message_chunk:
await application.bot.send_message(chat_id=chat_id, text=message_chunk)
else:
await application.bot.send_message(chat_id=chat_id, text="Nenhuma oferta disponível.")

async def fetch_and_send_deals(chat_id):
fetch_all_deals_from_site()
await send_message_via_telegram(all_deals, chat_id)

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = update.message.chat.id
await update.message.reply_text("Bot iniciado! Você receberá ofertas com desconto a cada 10 minutos.")

if scheduler.get_job(str(chat_id)) is None:
scheduler.add_job(fetch_and_send_deals, 'interval', minutes=10, args=[chat_id], id=str(chat_id))

async def stop(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = update.message.chat.id
job = scheduler.get_job(str(chat_id))

if job:
scheduler.remove_job(str(chat_id))
await update.message.reply_text("Bot parado! Não enviando mais ofertas.")
else:
await update.message.reply_text("Nenhum job agendado para este chat.")

async def refresh(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = update.message.chat.id
fetch_all_deals_from_site()
await send_message_via_telegram(all_deals, chat_id)

async def main():
application.add_handler(CommandHandler('start', start))
application.add_handler(CommandHandler('stop', stop))
application.add_handler(CommandHandler('refresh', refresh))

async with application: # Usando gerenciador de contexto para iniciar o bot
await application.initialize()
await application.run_polling() # Inicia o bot

if __name__ == '__main__':
try:
# Check if the event loop is already running
loop = asyncio.get_event_loop()
if loop.is_running():
print("Event loop already running. Starting the bot without asyncio.run()")
asyncio.ensure_future(main())
else:
asyncio.run(main())
except (KeyboardInterrupt, SystemExit):
scheduler.shutdown()```

To resolve the problem


Подробнее здесь: https://stackoverflow.com/questions/791 ... -dashskins
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»