GithubHelp home page GithubHelp logo

usernein / pyromod Goto Github PK

View Code? Open in Web Editor NEW
210.0 5.0 61.0 3.2 MB

A monkeypatcher add-on for Pyrogram

Home Page: https://pyromod.pauxis.dev/

License: GNU Lesser General Public License v3.0

Python 95.32% HTML 4.68%
conversation listen monkeypatch pyrogram python

pyromod's Introduction

Hey there ๐Ÿ‘‹

My name is Cezar Pauxis and i'm a brazilian Software Engineer.
People know me for becoming a software developer using broken smartphones.

Check out my portfolio!

Links

About me

โœจ +6 years creating and solving bugs
๐ŸŽฏ Goals: create fun projects and help people with useful projects
๐ŸŽฒ Programming is just one of my two main hobbies. I also love dancing.

Favorite technologies

docker logo typescript logo react logo figma logo amazonwebservices logo tailwindcss logo python logo linux logo nodejs logo regex logo raspberrypi logo electron logo

Other technologies i like to use

cloudflare logo css3 logo github logo githubactions logo html5 logo javascript logo jquery logo php logo prisma logo redux logo vite logo

Contact me

Wanna talk to me? Text me on Telegram telegram logo or Linkedin linkedin logo.

pyromod's People

Contributors

eikosa avatar jonatan1609 avatar jusidama-bot avatar kyee-rs avatar tofikdn avatar usernein avatar whalefell avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

pyromod's Issues

TypeError: object NoneType can't be used in 'await' expression

Everything seems to work fine but there is this peculiar error message that seems impossible to debug because its a fault within the module itself.

2022-07-28 10:08:31,968 - pyrogram.connection.connection - INFO - Connecting...
2022-07-28 10:08:32,059 - pyrogram.connection.connection - INFO - Connected! Production DC4 - IPv4 - TCPAbridgedO
2022-07-28 10:08:32,060 - pyrogram.session.session - INFO - NetworkTask started
2022-07-28 10:08:32,293 - pyrogram.session.internals.msg_id - INFO - Time synced: 2022-07-28 07:08:32.354201 UTC
2022-07-28 10:08:32,500 - pyrogram.session.session - INFO - Session initialized: Layer 142
2022-07-28 10:08:32,500 - pyrogram.session.session - INFO - Device: CPython 3.8.9 - Pyrogram 2.0.26
2022-07-28 10:08:32,500 - pyrogram.session.session - INFO - System: Darwin 20.6.0 (EN)
2022-07-28 10:08:32,500 - pyrogram.session.session - INFO - Session started
2022-07-28 10:08:32,504 - pyrogram.session.session - INFO - PingTask started
2022-07-28 10:08:32,607 - pyrogram.dispatcher - INFO - Started 12 HandlerTasks
2022-07-28 10:08:41,467 - pyrogram.dispatcher - ERROR - object NoneType can't be used in 'await' expression
Traceback (most recent call last):
  File "/Users/smi/Library/Python/3.8/lib/python/site-packages/pyrogram/dispatcher.py", line 240, in handler_worker
    await handler.callback(self.client, *args)
  File "/Users/smi/Library/Python/3.8/lib/python/site-packages/pyromod/listen/listen.py", line 93, in resolve_listener
    await self.user_callback(client, message, *args)
TypeError: object NoneType can't be used in 'await' expression
[request] Processing Link 'https://www.youtube.com/watch?v=tPEE9ZwTmy0&ab_channel=MylotheCat' from 'MahdeenSky'
[request] Downloaded Video at 'https://www.youtube.com/watch?v=tPEE9ZwTmy0&ab_channel=MylotheCat' with filesize: 0.069438
2022-07-28 10:08:43,835 - pyrogram.connection.connection - INFO - Connecting...
2022-07-28 10:08:43,931 - pyrogram.connection.connection - INFO - Connected! Production DC4 (media) - IPv4 - TCPAbridgedO
2022-07-28 10:08:43,932 - pyrogram.session.session - INFO - NetworkTask started
2022-07-28 10:08:44,391 - pyrogram.session.session - INFO - Session initialized: Layer 142
2022-07-28 10:08:44,392 - pyrogram.session.session - INFO - Device: CPython 3.8.9 - Pyrogram 2.0.26
2022-07-28 10:08:44,392 - pyrogram.session.session - INFO - System: Darwin 20.6.0 (EN)
2022-07-28 10:08:44,392 - pyrogram.session.session - INFO - Session started
2022-07-28 10:08:44,393 - pyrogram.session.session - INFO - PingTask started
2022-07-28 10:08:44,702 - pyrogram.session.session - INFO - PingTask stopped
2022-07-28 10:08:44,702 - pyrogram.connection.connection - INFO - Disconnected
2022-07-28 10:08:44,703 - pyrogram.session.session - INFO - NetworkTask stopped
2022-07-28 10:08:44,703 - pyrogram.session.session - INFO - Session stopped

Having Some Doubt....

Sir is we have to install pyromod by

pip3 install pyromod

before using it or it's pre - included with pyrogram already??

`Message.wait_for_click` and `Client.listen` will never return the expected `CallbackQuery`

message.wait_for_click() Even though clicking the button triggers the callback, it never makes him return. Unless a timeout triggers an error.

The same occurs in message.chat.listen when listener_type=ListenerTypes.CALLBACK_QUERY expects to receive a callback from the user pressing a button.

I had a feeling this was an issue and wondered if it could be reproduced on your end.

thanks for the reply. ๐Ÿ˜ƒ

image

AttributeError: 'NoneType' object has no attribute 'id'

from pyromod import listen
from pyromod.listen.listen import ListenerTimeout

@app.on_message()
async def test(_, message):
    print(message)
    
 
app.run()

when I send a message to channel , the bot raise this error:

'NoneType' object has no attribute 'id'
Traceback (most recent call last):
File ".....venv/lib/python3.10/site-packages/pyrogram/dispatcher.py", line 226, in handler_worker
if await handler.check(self.client, parsed_update):
File "......venv/lib/python3.10/site-packages/pyromod/listen/listen.py", line 196, in check
(message.chat.id, message.from_user.id, message.id),
AttributeError: 'NoneType' object has no attribute 'id'

how can I fix error?

`TypeError: Client.get_many_listeners_matching_with_identifier_pattern() got an unexpected keyword argument 'match_against_pattern'`

Remove the match_against_pattern argument. (Or comment it out till function updates)

Here is the additional info on the issue.

Actual error: Client.get_many_listeners_matching_with_identifier_pattern() got an unexpected keyword argument 'match_against_pattern'

Caused when (user's code):

return await client.stop_listening(
    chat_id=callback_query.message.chat.id,
    user_id=callback_query.from_user.id,
)

Caused by (package's code):

# pyromod/listen/client.py 187:189
listeners = self.get_many_listeners_matching_with_identifier_pattern(
    pattern,
    listener_type, 
    match_against_pattern=True # This arg's realization is absent in self.get_many_listeners_matching_with_identifier_pattern()
)

# Absent argument's position: pyromod/listen/client.py 160:170
    @should_patch()
    def get_many_listeners_matching_with_identifier_pattern(
        self,
        pattern: Identifier,
        listener_type: ListenerTypes, # No match_against_pattern?
    ) -> List[Listener]:
        listeners = []
        for listener in self.listeners[listener_type]:
            if pattern.matches(listener.identifier):
                listeners.append(listener)
        return listeners

Links to the broken code:
pyromod/listen/client.py 187:189
pyromod/listen/client.py 160:170

Bug in multi client and not work with uvloop

I utilize a client and a bot client. The 'app' client is a part of a private group and it listens for text containing ๐Ÿšจ๐Ÿšจ or a photo with the caption ๐Ÿšจ๐Ÿšจ. Afterwards, I utilize the 'app_bot' to transmit the message to my channel. It is essential for both of them to function properly, hence I employ 'await idle()' in order to avoid any blocking.

I want to receive the callback of the message with a button, so I use @app_bot.on_callback_query(). If the user selects Manual Input, I need to obtain the user's input. For this, I use coin = await chat.ask('Please input the coin: '). However, I am encountering an error message:

/Users/river/miniforge3/envs/tlg/bin/python /Users/river/Desktop/Troia-Crypto/main.py 
Pyromod is working! If you like pyromod, please star it at https://github.com/usernein/pyromod
[2023-11-08 19:25:42,034] [   ERROR] dispatcher.py:253 - <Queue at 0x2a07ced70 maxsize=1 _queue=[pyrogram.raw.functions.upload.SaveFilePart(file_id=7299050994019598340, file_part=0, bytes=b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\x07\x05\x05\x06\x05\x04\x07\x06\x06\x06\x08\x07\x07\x08\x0b\x12\x0b\x0b\n\n\x0b\x16\x0f\x10\r\x12\x1a\x16\x1b\x1a\x19\x16\x19\x18\x1c  tasks=1> is bound to a different event loop
[2023-11-08 19:25:42,048] [   ERROR] save_file.py:111 - Task <Task pending name='Task-516' coro=<SaveFile.save_file.<locals>.worker() running at /Users/river/miniforge3/envs/tlg/lib/python3.10/site-packages/pyrogram/methods/advanced/save_file.py:109>> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at /Users/river/miniforge3/envs/tlg/lib/python3.10/asyncio/futures.py:385]> attached to a different loop
Traceback (most recent call last):
  File "/Users/river/miniforge3/envs/tlg/lib/python3.10/site-packages/pyrogram/methods/advanced/save_file.py", line 109, in worker
    await session.invoke(data)
  File "/Users/river/miniforge3/envs/tlg/lib/python3.10/site-packages/pyrogram/session/session.py", line 389, in invoke
    return await self.send(query, timeout=timeout)
  File "/Users/river/miniforge3/envs/tlg/lib/python3.10/site-packages/pyrogram/session/session.py", line 326, in send
    payload = await self.loop.run_in_executor(
RuntimeError: Task <Task pending name='Task-516' coro=<SaveFile.save_file.<locals>.worker() running at /Users/river/miniforge3/envs/tlg/lib/python3.10/site-packages/pyrogram/methods/advanced/save_file.py:109>> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at /Users/river/miniforge3/envs/tlg/lib/python3.10/asyncio/futures.py:385]> attached to a different loop
[2023-11-08 19:26:00,717] [   ERROR] threading.py:251 - Task was destroyed but it is pending!
task: <Task pending name='Task-516' coro=<SaveFile.save_file.<locals>.worker() done, defined at /Users/river/miniforge3/envs/tlg/lib/python3.10/site-packages/pyrogram/methods/advanced/save_file.py:101> wait_for=<Future cancelled>>

Here is my code

async def main():
    app_bot = Client("crybot", api_id, api_hash, bot_token=bot_token, hide_password=True)
    app = Client("river", api_id, api_hash, hide_password=True)
    @app.on_message(filters.regex('๐Ÿšจ{2}') & filters.chat(group_id))
    async def listen(client, message):
        text = message.text
        if text is None:  # return is picture
            photo = await app.download_media(message.photo.file_id, in_memory=True)  # ไธ‹่ฝฝๅ›พ็‰‡ๅˆฐๅ†…ๅญ˜
            coin = text_from_image(photo.getvalue(), on_server=False, remove=False)
            coin, matched = match(coin)
        else:  # return is text
            coin, matched = find_coin_name(text)

        if matched:  # if matched
            response = post_data(coin, url)
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            output = f'[{current_time}] Buy coin {response}'
            if text is None:
                await app.send_photo(our_group_id, photo=photo, caption=output)
            else:
                await app.send_message(our_group_id, text=output)
        else:  # if not matched
            buttons = [[InlineKeyboardButton(text='๐Ÿช™ ' + c, callback_data=c)] for c in coin]
            buttons.append([InlineKeyboardButton(text='โš™๏ธ Manual Input', callback_data='Manual Input')])
            markup = InlineKeyboardMarkup(buttons)
            if text is None:
                await app_bot.send_photo(our_group_id, photo=photo, caption='Please Select the Button Bellow: ',
                                     reply_markup=markup)
            else:
                await app_bot.send_message(our_group_id, 'Please Select the Button Bellow: ', reply_markup=markup)

    @app_bot.on_callback_query()
    async def echo(client, callback_query):
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        if callback_query.data == 'Manual Input':
            chat = callback_query.message.chat
            coin = await chat.ask('Please input the coin: ')
            coin = coin.text.upper()
            while coin not in known_coins:
                coin = await chat.ask('Invalid Coin Name, Please reinput the coin: ')
                coin = coin.text.upper()
        else:
            coin = callback_query.data

        # await client.send_message(our_group_id, f'[{current_time}] Buy coin {coin}')
        await callback_query.message.edit_reply_markup(reply_markup=None)

    await app.start()
    await app_bot.start()
    await idle()

uvloop.install()
asyncio.run(main())

Method ask raising [400 USERNAME_INVALID] - The username is invalid (caused by "contacts.ResolveUsername")

i got this error
pyrogram.errors.exceptions.bad_request_400.UsernameInvalid: Telegram says: [400 USERNAME_INVALID] - The username is invalid (caused by "contacts.ResolveUsername")

when i use this code :

Phone_Number = await client.ask(chat,f"- ู‚ู… ุจุฃุฑุณุงู„ ุฑู‚ู… ุงู„ู‡ุงุชู .")

why???

full error:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/pyrogram/dispatcher.py", line 240, in handler_worker
    await handler.callback(self.client, *args)
  File "/usr/local/lib/python3.9/dist-packages/pyromod/listen/listen.py", line 293, in resolve_future
    await self.registered_handler(client, query, *args)
  File "/root/Tmoel/plugins/Main.py", line 554, in Call_Start
    Phone_Number = await client.ask(int(chat),f"- ู‚ู… ุจุฃุฑุณุงู„ ุฑู‚ู… ุงู„ู‡ุงุชู .")
  File "/usr/local/lib/python3.9/dist-packages/pyromod/listen/listen.py", line 99, in ask
    request = await self.send_message(identifier[0], text, *args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/pyrogram/methods/messages/send_message.py", line 128, in send_message
    peer=await self.resolve_peer(chat_id),
  File "/usr/local/lib/python3.9/dist-packages/pyrogram/methods/advanced/resolve_peer.py", line 76, in resolve_peer
    await self.invoke(
  File "/usr/local/lib/python3.9/dist-packages/pyrogram/methods/advanced/invoke.py", line 79, in invoke
    r = await self.session.invoke(
  File "/usr/local/lib/python3.9/dist-packages/pyrogram/session/session.py", line 389, in invoke
    return await self.send(query, timeout=timeout)
  File "/usr/local/lib/python3.9/dist-packages/pyrogram/session/session.py", line 357, in send
    RPCError.raise_it(result, type(data))
  File "/usr/local/lib/python3.9/dist-packages/pyrogram/errors/rpc_error.py", line 91, in raise_it
    raise getattr(
pyrogram.errors.exceptions.bad_request_400.UsernameInvalid: Telegram says: [400 USERNAME_INVALID] - The username is invalid (caused by "contacts.ResolveUsername")

RuntimeError: Task got Future attached to a different loop

Task <Task pending name='Task-30' coro=<Dispatcher.handler_worker() running at /usr/local/lib/python3.8/dist-packages/pyrogram/dispatcher.py:240>> got Future <Future pending cb=[Client.clear_listener(5177820294)()]> attached to a different loop
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/pyrogram/dispatcher.py", line 240, in handler_worker
    await handler.callback(self.client, *args)
  File "/usr/local/lib/python3.8/dist-packages/pyromod/listen/listen.py", line 93, in resolve_listener
    await self.user_callback(client, message, *args)
  File "main.py", line 404, in me
    answer = await client.ask(5177820294, '/rehber')
  File "/usr/local/lib/python3.8/dist-packages/pyromod/listen/listen.py", line 60, in ask
    response = await self.listen(chat_id, filters, timeout)
  File "/usr/local/lib/python3.8/dist-packages/pyromod/listen/listen.py", line 55, in listen
    return await asyncio.wait_for(future, timeout)
  File "/usr/lib/python3.8/asyncio/tasks.py", line 455, in wait_for
    return await fut
RuntimeError: Task <Task pending name='Task-30' coro=<Dispatcher.handler_worker() running at /usr/local/lib/python3.8/dist-packages/pyrogram/dispatcher.py:240>> got Future <Future pending cb=[Client.clear_listener(5177820294)()]> attached to a different loop

Kwargs instead of identifier

Instead of using identifier as tuple using kwargs can be better i think, for example
await client.listen(chat_id = 1234, user_id = 0542)

How to kill client.listen?

Hi!)

Using this patch and pretty happy with it, my thanks to author.

So the question might look a bit wierd, but.

I need to get, how can I stop client.listen process. So I tried to save in not like "answer" as it shown in example, but as attribute of user object of my User class, that collects registering data of users.

Each object of user class is defined with id, so it looks like

user.answer = client.listen(chat_id, timeout=30)

So it causes timeout error in 30 seconds, and I catch it with try except. So far it's pretty fine.

I hoped that if I start some other process I would simply do

`user.answer=None', an process of listening will stop. So... It doesn't)) I guess there is another link somewhere, that keeps this object alive and listening until timeout kills it.

So, with hope I ask. How to kill it manually?)

Problem with pyromod

import pyromod
from pyromod.exceptions import ListenerTimeout
from pyromod import Client

from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
import json, configparser, random

from Andre.buttons import buttons
from Andre.filters import database
from main import Andre

app = Andre
prefixes = app.ALIAS

app1 = True


@app.on_message(filters.command("test", prefixes=prefixes))
async def applications(client, message):
    global app1

    if app1 == True:
        username  = client.ask(chat_id=message.chat_id, text='username:')
        app1 = False
        
    elif app1 == False:
        await client.send_message(message.chat.id, text=f"{username}")

Hello, this is my code. When i do the command /test it says me this in console:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/pyrogram/dispatcher.py", line 226, in handler_worker
    if await handler.check(self.client, parsed_update):
  File "/usr/local/lib/python3.9/dist-packages/pyromod/listen/message_handler.py", line 58, in check
    await self.check_if_has_matching_listener(client, message)
  File "/usr/local/lib/python3.9/dist-packages/pyromod/listen/message_handler.py", line 37, in check_if_has_matching_listener
    listener = client.get_listener_matching_with_data(data, ListenerTypes.MESSAGE)
  File "/usr/local/lib/python3.9/dist-packages/pyrogram/sync.py", line 53, in async_to_sync_wrap
    coroutine = function(*args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/pyromod/listen/client.py", line 123, in get_listener_matching_with_data
    for listener in self.listeners[listener_type]:
AttributeError: 'Client' object has no attribute 'listeners'

Use one structure and naming on all methods

The method wait_for_click only accepts from_user_id & then it throws NoneType error at some point, I think it's better to use one structure for all of them (using kwargs or identifiers, not identifier). It'd be less confusing that way.

Disable startup logs

from pyromod.config import config

config.disable_startup_logs = True

This isn't working because the files having startup logs are already being imported

Pyromod raising AttributeError: 'NoneType' object has no attribute 'id'

I get this error, and from a little investigation it comes from waiting from messages from channels.

Traceback (most recent call last):
  File "/env/lib/python3.11/site-packages/pyrogram/dispatcher.py", line 226, in handler_worker
    if await handler.check(self.client, parsed_update):
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/env/lib/python3.11/site-packages/pyromod/listen/listen.py", line 196, in check
    (message.chat.id, message.from_user.id, message.id),
                      ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'

What does it mean, and can you fix it?

`ask` is blocking another command

i have 2 commands inside my plugins

register.py

async def callback_tutor1(bot: Bot, message: Message):
	profile = bot.mongodb.find_user(message.from_user.id)
	msg = f'{q1.description} \n' f'\n{q1.sort_desc}'
	chat = message.chat
	answer = await chat.ask('please type /profile')
	if answer.text == '/profile':
	    await bot.send_message(chat.id, msg)
	
@Bot.on_message(filters.text & filters.command(['start', 'register']) & filters.private)
async def register(bot: Bot, message: Message):
    # my logic here
     callback(bot, message)

profile.py

@Bot.on_message(filters.text & filters.command('profile') & filters.private)
async def profile(bot: Bot, message: Message):
	p = bot.mongodb.find_user(message.from_user.id)
	msg = f'**{p.username.title()}**''
	await bot.send_message(message.chat.id, msg)

first user will type /start and then bot will ask user to type /profile which is /profile is command from plugins, but command /profile didnt get execute after bot asking to the user, but command /profile work just fine.

i dont know why this happend, and cannot figure out to fix this

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.