简体   繁体   English

如何同时运行 aiogram bot 和 pyrogram app(这两个模块)?

[英]How to run aiogram bot and pyrogram app together (these two modules)?

I wrote a function on pyrogram that parses the history of a chat.我在 pyrogram 上写了一个 function 来解析聊天记录。 The history is filtered by participant id, if a specific user wrote to the chat, the message will be forwarded to me.历史记录按参与者 ID 过滤,如果特定用户写了聊天,消息将转发给我。 (We need to know: the name of the group, the id of the participant, the number of days for which we make a selection.) it works, code: (我们需要知道:组名,参与者id,我们选择的天数。)它有效,代码:

module_1

import configparser
from datetime import datetime, timedelta
from pyrogram import Client

config = configparser.ConfigParser()
config.read("config.ini")
api_id = int(config['Telegram']['api_id'])
api_hash = config['Telegram']['api_hash']
app = Client("my_account", api_id, api_hash)


# To test the function, separately from the bot!
# The data must come from the bot.
# id = input('"Enter user_id, for example: 33721 :   "')
# group = input("enter group name:   ")
# day = int(input("Enter number of days:   "))


async def pars(day, group):
    async with app:
        try:
            async for message in app.get_chat_history(group):
                try:
                    if message.date < datetime.now() - timedelta(days=day):
                        break
                    else:
                        data = str(message.date)
                        user_id = str(message.from_user.id)
                        user_name = str(message.from_user.username)
                        txt = str(message.text)
                        kortej = data, user_id, user_name, txt
                        print(kortej) # All msg print in console for test
                        if id in kortej:
                            stroka = '-'.join(kortej)
                            await app.send_message('me', stroka) #if id was find in all hystori


                except AttributeError:
                    print("Either it's a channel and not a chat, or it's not a text message.")
                    pass
        except:
            print("It looks like the chat doesn't exist or can't be accessed")


app.run(pars(day, group)


#module_2

import logging

from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.utils import executor

from auth_data import token

# Configure logging
logging.basicConfig(level=logging.INFO)

bot = Bot(token=token)

# For example use simple MemoryStorage for Dispatcher.
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)


class Form(StatesGroup):
    user_id = State()
    group = State()
    day = State()


@dp.message_handler(commands=['start', 'help'])
async def send_welcome(message: types.Message):
    """
    This handler will be called when user sends `/start` or `/help` command
    """
    # set state
    await Form.user_id.set()

    await message.reply(f"Enter user_id, for example: 33721")


# You can use state '*' if you need to handle all states
@dp.message_handler(state='*', commands='cancel')
@dp.message_handler(Text(equals='cancel', ignore_case=True), state='*')
async def cancel_handler(message: types.Message, state: FSMContext):
    """
    Allow user to cancel any action
    """
    current_state = await state.get_state()
    if current_state is None:
        return

    logging.info('Cancelling state %r', current_state)
    # Cancel state and inform user about it
    await state.finish()
    # And remove keyboard (just in case)
    await message.reply('Cancelled.', reply_markup=types.ReplyKeyboardRemove())


@dp.message_handler(state=Form.user_id)
async def process_file_name(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        (data['user_id']) = message.text

    await Form.next()
    await message.reply("Enter the name of the group, for example: magazeta_chat")


@dp.message_handler(state=Form.group)
async def process_file_name(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['group'] = message.text

    await Form.next()
    await message.reply("The number of days for which you need to select messages, for example: 3")


@dp.message_handler(state=Form.day)
async def process_file_name(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['day'] = message.text

        await message.bot.send_message(message.chat.id, text="Data received!")

    print(data['user_id']) # These variables need to be passed to the pyrogram application!
    print(data['group']) # These variables need to be passed to the pyrogram application!
    print(data['day']) # These variables need to be passed to the pyrogram application!
    await state.finish()

if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)

It is assumed that there is a JSON file that contains the user id, chats in which this user is a member.假设有一个 JSON 文件,其中包含用户 ID,该用户是其中成员的聊天。 It is possible to fix the bot to simply accept any data;可以修复机器人以简单地接受任何数据; the essence of the question is how to combine all this?问题的本质是如何将所有这些结合起来?

import asyncio

...
app.start()
...

def run_chat_bot():
    executor.start_polling(dp, skip_updates=True)

if __name__ == '__main__':
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.create_task(pars(day, group))
    run_chat_bot()
    loop.close()
    app.stop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM