Телеграмм бот ошибка на await

Рейтинг: 0Ответов: 1Опубликовано: 23.05.2023
import schedule
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from aiogram.types import InputFile
from telegram import Bot
from telegram.ext import Updater, CommandHandler
import asyncio
import aiohttp
import datetime


TOKEN = "скрыл"
CHANNEL_ID = "скрыл"
bot = Bot(token=TOKEN)

def get_q(url):
    driver = webdriver.Chrome()
    driver.get(url)

    question = driver.find_element(By.CSS_SELECTOR, 'div[itemtype="http://schema.org/Question"] [itemprop="name"]')
    question_text = question.text

    image = driver.find_element(By.CSS_SELECTOR, 'div[itemtype="http://schema.org/Question"] picture img')
    image_url = image.get_attribute('src')

    elements = driver.find_elements(By.XPATH, '//div[@itemprop="acceptedAnswer" or @itemprop="suggestedAnswer"]//span')
    texts = [element.text for element in elements]

    my_element = driver.find_element(By.CLASS_NAME, 'animate-pulse')
    text = my_element.text

    buttons = driver.find_elements(By.CLASS_NAME, 'p-1')

    next_url = buttons[1].get_attribute('href')


    print(question_text, '\n', texts, '\n', image_url, '\n', next_url)

    correct_option_id = texts.index(text)

    return question_text, texts, correct_option_id, image_url, next_url

async def send_poll(url):
    global bot
    question, options, correct_option_id, image_url, next_url = get_q(url)
    async with aiohttp.ClientSession() as session:
        async with session.get(image_url) as resp:
            image_bytes = **await** resp.read()
    **await** bot.send_photo(CHANNEL_ID, photo=image_url)
    **await** bot.send_poll(chat_id=CHANNEL_ID, question=question, options=options, type="quiz", correct_option_id=correct_option_id)
    now = datetime.datetime.now()
    time = now.time()
    #while time.minute !=3 and time.second != 0:
    #    now = datetime.datetime.now()
    #    time = now.time()
    g(next_url)



async def main(url):
    await send_poll(url)

def g(next_url):
    if __name__ == '__main__':
        asyncio.create_task(main(next_url))

if __name__ == '__main__':
    asyncio.run(main(input("Enter your link:")))

(Ссылка откуда беру данные например: https://umnik.net/questions/395-skolko-serdec-u-osminoga) Ошибку не выдаёт а просто останавливает код на await когда первый раз код прошёл всё написал в телеграмме а когда он второй раз включает send_poll() тогда код останавливается на await которые я выделил двумя звездочками

Ответы

▲ 0Принят

У тебя в коде целых 3 ошибки!

  1. Ты не импортировали модуль asyncio.
  2. Внутри функции send_poll() ты должен использовать await перед get_q(url), так как get_q() является асинхронной функцией.
  3. В функции g() ты не передаешь параметр next_url, поэтому код вызывает ошибку при попытке выполнения g(next_url).

Вот исправленный код:

import asyncio
import aiohttp
import datetime
from selenium import webdriver
from selenium.webdriver.common.by import By
from aiogram.types import InputFile
from telegram import Bot
from telegram.ext import Updater, CommandHandler

TOKEN = "токен бота"
CHANNEL_ID = "id канала"
bot = Bot(token=TOKEN)

def get_q(url):
    driver = webdriver.Chrome()
    driver.get(url)

    question = driver.find_element(By.CSS_SELECTOR, 'div[itemtype="http://schema.org/Question"] [itemprop="name"]')
    question_text = question.text

    image = driver.find_element(By.CSS_SELECTOR, 'div[itemtype="http://schema.org/Question"] picture img')
    image_url = image.get_attribute('src')

    elements = driver.find_elements(By.XPATH, '//div[@itemprop="acceptedAnswer" or @itemprop="suggestedAnswer"]//span')
    texts = [element.text for element in elements]

    my_element = driver.find_element(By.CLASS_NAME, 'animate-pulse')
    text = my_element.text

    buttons = driver.find_elements(By.CLASS_NAME, 'p-1')

    next_url = buttons[1].get_attribute('href')

    print(question_text, '\n', texts, '\n', image_url, '\n', next_url)

    correct_option_id = texts.index(text)

    return question_text, texts, correct_option_id, image_url, next_url

async def send_poll(url):
    global bot
    question, options, correct_option_id, image_url, next_url = await get_q(url)
    async with aiohttp.ClientSession() as session:
        async with session.get(image_url) as resp:
            image_bytes = await resp.read()
    await bot.send_photo(CHANNEL_ID, photo=image_url)
    await bot.send_poll(chat_id=CHANNEL_ID, question=question, options=options, type="quiz", correct_option_id=correct_option_id)
    now = datetime.datetime.now()
    time = now.time()

async def main(url):
    await send_poll(url)

def g(next_url):
    if __name__ == '__main__':
        asyncio.create_task(main(next_url))
    
if __name__ == '__main__':
    asyncio.run(main(input("Enter your link:")))

Так же лично моя рекомендация, добавь обработку ошибок и улучшь логику своего кода для более гладкой работы.