Search code examples
telegramtelethon

@client.on(events.NewMessage not working :(


im trying to code a bot who spams a message on another bot, i tried reading the docs but it just won't work :/ this is the message i get when i get paired with a user:


📧 Sei stato inserito in chat con un utente!

📃 DATI DELL'UTENTE

👉🏻 Scrivigli subito un messaggio

button 1

button 2


i need to respond to this text with a message i type in input and another one after a sec or two, but the code just stops and doesn't even respond.. here's the code:

import asyncio 
from telethon.sync import TelegramClient
from telethon import TelegramClient, events, sync
from telethon.errors.rpcerrorlist import PeerFloodError
from telethon.tl.types import InputPeerUser
import time

api_id = xxx
api_hash = 'xxx'
messaggio = input("inserisci messaggio: ")
comando = input("inserisci comando: ")
client = TelegramClient('session_name', api_id, api_hash)
client.start()

time.sleep(5)


@client.on(events.NewMessage(from_users=<botname>, pattern='📧 Sei stato inserito in chat con un utente!.+'))
async def handler(event):
    await event.respond("messaggio")
    time.sleep(5)
    await event.respond("comando")
    time.sleep(10)


Solution

  • There are some issues here. First of all, using time.sleep() with asyncio is not reccomended. Then, the client is not running so you need to run it.

    You can do something like this:

    import asyncio 
    from telethon.sync import TelegramClient
    from telethon import TelegramClient, events, sync
    from telethon.errors.rpcerrorlist import PeerFloodError
    from telethon.tl.types import InputPeerUser
    import time
    
    api_id = 123456
    api_hash = "gwudshojia24153124321"
    messaggio = input("inserisci messaggio: ")
    comando = input("inserisci comando: ")
    client = TelegramClient('session_name', api_id, api_hash)
    client.start()
    
    @client.on(events.NewMessage(from_users=<bot_name>, pattern='📧 Sei stato inserito in chat con un utente!.+'))
    async def handler(event):
        await event.respond(messaggio)
        await asyncio.sleep(5)
        await event.respond(comando)
        await asyncio.sleep(10)
    
    client.run_until_disconnected()