Python:
import time
import logging
import pandas as pd
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from telethon.sync import TelegramClient
# Set up logging
# logging.basicConfig(level=logging.DEBUG)
# Create the bot and dispatcher objects
token = "6370592266:AAHEPh21W--k1Xzt7o9Wxrm-2bWwO-0jzoA"
bot = Bot(token="6370592266:AAHEPh21W--k1Xzt7o9Wxrm-2bWwO-0jzoA")
dp = Dispatcher(bot, storage=MemoryStorage())
# Define the parser function
async def get_messages(client, chat, keywords, limit=100):
data_message = []
chats = [await client.get_entity(chat_link) for chat_link in chat]
for chat_entity in chats:
chat_name = chat_entity.title
chat_id = chat_entity.id
messages = await client.iter_messages(chat_entity, limit=limit)
async for message in messages:
if message.text and isinstance(message.text, str):
for keyword in keywords:
if keyword.lower() in message.text.lower():
sender = message.sender
username = message.sender.username if message.sender.username else None
message_data = {
"username": username,
"message_text": message.text,
"group_name": chat_name,
"group_link": chat_entity.username,
"chat_id": chat_id,
"sending_time": message.date,
}
data_message.append(message_data)
break
df_message = pd.DataFrame(data_message)
return df_message
# Handler for the "Парсинг данных" command
@dp.message_handler(commands=['start'])
async def start(message: types.Message):
keyboard_markup = types.ReplyKeyboardMarkup(row_width=2)
buttons = [
types.KeyboardButton(text="Парсинг данных"),
types.KeyboardButton(text="Help"),
]
keyboard_markup.add(*buttons)
await message.answer("Привет! Что ты хочешь сделать?", reply_markup=keyboard_markup)
@dp.message_handler(lambda message: message.text == "Парсинг данных")
async def parsing_data(message: types.Message):
# Telegram API credentials
api_id =
api_hash = ""
user_name = ""
chat_list = [
]
keywords = [
]
phone_prompt = await bot.send_message(message.chat.id, "Please enter your phone number:")
phone_message = await bot.wait_for("message", lambda msg: msg.from_user.id == message.from_user.id)
phone_number = phone_message.text
verification_code_prompt = await bot.send_message(message.chat.id, "Please enter the verification code:")
verification_code_message = await bot.wait_for("message", lambda msg: msg.from_user.id == message.from_user.id)
verification_code = verification_code_message.text
client = TelegramClient(user_name, api_id, api_hash)
client.start(phone_number)
client.sign_in(phone_number, verification_code)
df_message = await get_messages(client, chat_list, keywords)
df_message.to_csv('messages.csv')
client.disconnect()
await message.answer("Data successfully parsed!")
# Handler for the "Help" button
@dp.message_handler(lambda message: message.text == "Help")
async def help(message: types.Message):
await message.answer("Помощь по использованию бота:\n"
"1. Команда /start - запуск бота\n"
"2. Кнопка 'Парсинг данных' - запуск парсинга\n"
"3. Кнопка 'Help' - отображение справочной информации")
if __name__ == '__main__':
# Start the bot
from aiogram import executor
executor.start_polling(dp)
Нужна помощь с написанием функции async def parsing_data. Она не работает. Получаю ошибки
```Task exception was never retrieved
future: <Task finished name='Task-12' coro=<Dispatcher._process_polling_updates() done, defined at C:\Users\79633\PycharmProjects\py_bot_pars\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py:407> exception=AttributeError("'Bot' object has no attribute 'wait_for'")>
Traceback (most recent call last):
File "C:\Users\79633\PycharmProjects\py_bot_pars\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 415, in _process_polling_updates
for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
File "C:\Users\79633\PycharmProjects\py_bot_pars\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 235, in process_updates
return await asyncio.gather(*tasks)
File "C:\Users\79633\PycharmProjects\py_bot_pars\venv\lib\site-packages\aiogram\dispatcher\handler.py", line 117, in notify
response = await handler_obj.handler(*args, **partial_data)
File "C:\Users\79633\PycharmProjects\py_bot_pars\venv\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 256, in process_update
return await self.message_handlers.notify(update.message)
File "C:\Users\79633\PycharmProjects\py_bot_pars\venv\lib\site-packages\aiogram\dispatcher\handler.py", line 117, in notify
response = await handler_obj.handler(*args, **partial_data)
File "C:\Users\79633\PycharmProjects\py_bot_pars\bot_main.py", line 116, in parsing_data
phone_message = await bot.wait_for("message", lambda msg: msg.from_user.id == message.from_user.id)
AttributeError: 'Bot' object has no attribute 'wait_for'```
Может кто поделиться примером кода как авторизоваться пользователю телеграмм в чате с ботом и затем далее выполняется функция парсинга
Последнее редактирование: