gram-js / gramjs

NodeJS/Browser MTProto API Telegram client library,
MIT License
1.28k stars 179 forks source link

Can't make addEventHandler work with NewMessage #94

Closed CryptosWizard closed 3 years ago

CryptosWizard commented 3 years ago

Hello, I tried to make the EventHandler works for new message but didn't succeed.

Here is my code, i just do some basic send and loading before the handler to be sure the connection is working.

I checked https://painor.gitbook.io/gramjs/getting-started/updates-events , https://github.com/gram-js/gramjs/issues/74 and https://github.com/gram-js/gramjs/pull/12 to understand how NewMessage works, i'm using Telethon also so the lib is not too foreign but can t make that Handler works.

If i put client.addEventHandler(eventPrint); the code is working fine but got too much event to filter. }

const { TelegramClient,events } = require('telegram')
const { StringSession } = require('telegram/sessions')
const input = require('input') // npm i input

const apiId = ***********
const apiHash = '*************'
string_save = "********************************************"
const stringSession = new StringSession(string_save); // fill this later with the value from session.save()

async function eventPrint(event) {
    console.log("Enter evenPrint")
    const message = event.message;
    //console.log(message)
    if (event.isPrivate){
        // prints sender id
        console.log(message.senderId);
        // read message
        if (message.text == "hello"){
            const sender = await message.getSender();
            console.log("sender is",sender);
            await client.sendMessage(sender,{
                message:`hi your id is ${message.senderId}`
            });
        }
    }
}

const init = async () => {
    // --------------------------------------------------------------------
    // Simple connection
    // --------------------------------------------------------------------
    console.log('Loading interactive example...')
    const client = new TelegramClient(stringSession, apiId, apiHash, { connectionRetries: 5 })
    await client.start({
        phoneNumber: async () => await input.text('number ?'),
        password: async () => await input.text('password?'),
        phoneCode: async () => await input.text('Code ?'),
        onError: (err) => console.log(err),
    });
    //console.log(client.session.save()) // Save this string to avoid logging in again

    // --------------------------------------------------------------------
    // Test sending and loading messages
    // --------------------------------------------------------------------
    console.log('You should now be connected.')
    await client.sendMessage('me', { message: 'Hello!' });

    const msgs = await client.getMessages("me", {
        limit: 10,
    });
    console.log("the total number of msgs are", msgs.total);
    console.log("what we got is ", msgs.length);
    for (const msg of msgs) {
        //console.log("msg is",msg); // this line is very verbose but helpful for debugging
        console.log("msg text is : ", msg.text);
    }
    // --------------------------------------------------------------------
    // Test event handle new messages
    // --------------------------------------------------------------------
    list_channel = [111111111111,-22222222222]
    //MyMessage = new events.NewMessage({"chats" : [111111111111, -22222222222]})
    //MyMessage = new events.NewMessage(chats = list_channel)
    client.addEventHandler(eventPrint, new events.NewMessage(chats = list_channel) );
}

init();

The message is send then i load the 10 messages and then i got the Error :


    at init (******************************\telegram_read.js:63:51)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:45944) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:45944) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```
painor commented 3 years ago

I think you're misusing javascript. the correct way to pass args with names is as follows. new NewMessage({chats: [1,2,3]} but it's better to filter the chat ids inside the event than to use in the args because the library needs to have seen it first and that's not possible with using string session. so change the event to something like

async function eventPrint(event) {
    console.log("Enter evenPrint")
    if ([-10014564654,-1005468654].includes(event.chatId)){
        return;
    }
}

chatId would return bot API style ids so make sure to use -100 if it's a channel/supergorup

CryptosWizard commented 3 years ago

I think you're misusing javascript. the correct way to pass args with names is as follows. new NewMessage({chats: [1,2,3]}

Yeah i tried that, then i got desperated and tried strange way of doing it just in case. client.addEventHandler(eventPrint, new events.NewMessage({chats : [1111111, -2222222]}) is not working with same error and you said to put nothing inside i wanted to do that but when i doclient.addEventHandler(eventPrint, new events.NewMessage({}) same error and client.addEventHandler(eventPrint, new NewMessage({})say NewMessage is not defined so i imported events and put it in front as in the #74

painor commented 3 years ago

it doesn't matter how you import it as long as you import it.

CryptosWizard commented 3 years ago

That doesn't change the fact that

client.addEventHandler(eventPrint, new events.NewMessage({})
client.addEventHandler(eventPrint, new events.NewMessage({chats : [1111111, -2222222]})

are both sending


(node:35192) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'NewMessage' of undefined
    at init (*******************\js-botbsc-348\telegram_read.js:64:51)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:35192) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:35192) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
painor commented 3 years ago

well that's really more like a javascript/typescript issue. make sure to import it correctly const { NewMessage } = require('telegram/events') or import { NewMessage } from "telegram/events"

CryptosWizard commented 3 years ago

Ok indeed that was an import problem const { events } = require('telegram') is not enough to use events.NewMessage my bad Thank you for taking the time !