gram-js / gramjs Goto Github PK
View Code? Open in Web Editor NEWNodeJS/Browser MTProto API Telegram client library,
License: MIT License
NodeJS/Browser MTProto API Telegram client library,
License: MIT License
I know there's a TODO already, but this is bad:
gramjs/gramjs/network/MTProtoSender.js
Lines 570 to 577 in a5b9864
This is prone to causing 4865 bad_msg_notification
before Telegram errors with 429 Too Many Requests at the transport level.
Forgive me, I am a new developer. Some of my questions may seem obvious.
I couldn't find any information on deployment best practices.
Do you have advice or examples on how to deploy a "User Bot" in production? Preferably via GCP. AWS & Heroku is also fine.
I chose this npm "telegram" package over the more popular & easier to use npm "telegram-bot-api" because I need to ability to query Telegram group member lists. As far as I know, I am unable to do this via the Bot API.
I understand "User Bots" require a phone number to run, as well as a confirmation code sent to that phone number in order to get the "string session" for the client.
Do you know of any services/websites I can use to generate/rent a new phone number for this? I'd prefer not to use my personal phone number for this "User Bot".
How long does a generated "string session" last? How often will I need to re-enter a confirmation code to keep this bot running?
I am building a live tracking application. In short, my app supports various 3rd party Satellite messengers & beacons and I am using Telegram groups to decide who to show on a map. I need to know all the members of a Telegram group at all times. I plan on querying all members of a group when the bot is first added, then using events to detect when a new user has joined, or an old user has left or been kicked.
Thank you
[2020-01-14T13:37:51.082Z] [DEBUG] - [Connecting]
[2020-01-14T13:37:51.737Z] [DEBUG] - [Finished connecting]
[2020-01-14T13:37:51.747Z] [DEBUG] - [Connection success!]
[2020-01-14T13:37:51.877Z] [DEBUG] - [New auth_key attempt ...]
and then node process exit without any log information
the /example/main.js can not work well.
Locally changed
gramjs/gramjs/client/TelegramClient.ts
Line 224 in 4eb6fb0
to
isUserAuthorized() {
return userMethods.isUserAuthorized(this);
}
and I could login
I'm attempting to get started with Telegram API using gramjs but can't seem to get beyond getting started. Specifically, I'm always thrown BOT_METHOD_INVALID
.
const {TelegramClient, Api} = require('telegram');
const {StringSession} = require('telegram/sessions');
const apiId = "my_id"
const apiHash = "my_hash"
const stringSession = '';
const BOT_TOKEN = "my_bot_token";
const session = new StringSession('');
const client = new TelegramClient(session, apiId, apiHash, {connectionRetries: 5});
(async () => {
await client.start({
botAuthToken: BOT_TOKEN
})
.then(() => {
return run()
})
.catch((err) => {
console.log("Err", err)
})
})()
async function run() {
let checkRequest = new Api.messages.CheckChatInvite({hash: "SOME_HASH"})
const result = await client.invoke(checkRequest);
console.log(result);
};
Error message:
[2021-06-05T09:35:24.880Z] [INFO] - [Signed in successfully as MYBOT]
Started...
[2021-06-05T09:35:24.880Z] [DEBUG] - [Assigned msgId = 6970241113245282760 to messages.CheckChatInvite]
[2021-06-05T09:35:24.880Z] [DEBUG] - [Encrypting 1 message(s) in 40 bytes for sending]
[2021-06-05T09:35:24.882Z] [DEBUG] - [Encrypted messages put in a queue to be sent]
[2021-06-05T09:35:24.882Z] [DEBUG] - [Waiting for messages to send...false]
[2021-06-05T09:35:24.882Z] [DEBUG] - [Assigned msgId = 6970241113253282180 to MsgsAck]
[2021-06-05T09:35:24.882Z] [DEBUG] - [Encrypting 1 message(s) in 36 bytes for sending]
[2021-06-05T09:35:24.882Z] [DEBUG] - [Encrypted messages put in a queue to be sent]
[2021-06-05T09:35:24.882Z] [DEBUG] - [Waiting for messages to send...false]
[2021-06-05T09:35:24.968Z] [DEBUG] - [Handling RPC result for message 6970241113245282760]
[2021-06-05T09:35:24.969Z] [DEBUG] - [Receiving items from the network...]
[2021-06-05T09:35:24.969Z] [DEBUG] - [Assigned msgId = 6970241113601282708 to MsgsAck]
[2021-06-05T09:35:24.969Z] [DEBUG] - [Encrypting 1 message(s) in 36 bytes for sending]
Err RPCError: BOT_METHOD_INVALID
at Object.RPCMessageToError (MY_DIR/node_modules/telegram/errors/index.js:24:12)
at MTProtoSender._handleRPCResult (MY_DIR/node_modules/telegram/network/MTProtoSender.js:488:36)
at MTProtoSender.<anonymous> (MY_DIR/node_modules/telegram/network/MTProtoSender.js:412:19)
at Generator.next (<anonymous>)
at fulfilled (MY_DIR/node_modules/telegram/network/MTProtoSender.js:5:58)
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
code: undefined
}
I have checked that CheckChatInvite
can be used by Bot.
I am using node 10 and telegram 1.6.10
Hello
I try to get channel info by Api.channels.GetFullChannel
.
But when I try to invoke this method
const channelInfo = await client.invoke(new Api.channels.GetFullChannel({
channel: new Api.InputChannel({
channelId: `-100${id}`,
accessHash: accessHash,
}),
}))
I get an error
RangeError [ERR_OUT_OF_RANGE]: The value of "value" is out of range. It must be >= -2147483648 and <= 2147483647. Received -1_001_187_737_793
at checkInt (internal/buffer.js:69:11)
at writeU_Int32LE (internal/buffer.js:689:3)
at Buffer.writeInt32LE (internal/buffer.js:858:10)
at argToBytes (/home/administrator/Desktop/telegramtest/node_modules/telegram/tl/api.js:99:15)
at VirtualClass.getBytes (/home/administrator/Desktop/telegramtest/node_modules/telegram/tl/api.js:378:42)
at argToBytes (/home/administrator/Desktop/telegramtest/node_modules/telegram/tl/api.js:122:22)
at VirtualClass.getBytes (/home/administrator/Desktop/telegramtest/node_modules/telegram/tl/api.js:378:42)
at new RequestState (/home/administrator/Desktop/telegramtest/node_modules/telegram/network/RequestState.js:9:29)
at MTProtoSender.send (/home/administrator/Desktop/telegramtest/node_modules/telegram/network/MTProtoSender.js:201:23)
at Object.<anonymous> (/home/administrator/Desktop/telegramtest/node_modules/telegram/client/users.js:41:48) {
code: 'ERR_OUT_OF_RANGE'
}
I got the right channelId and accessHash for sure
I'm trying to login using the test DC, as stated in telegram documentation:
https://core.telegram.org/api/auth#test-phone-numbers
This is my code:
import { Api, TelegramClient } from "telegram";
import { StringSession } from "telegram/sessions";
import { Logger } from "telegram/extensions";
import {
TELEGRAM_API_ID as apiId,
TELEGRAM_API_HASH as apiHash,
} from "./config";
const phoneNumber = "9996627308";
const phoneCode = "22222";
const createClient = async (stringSession?: string) => {
const session = new StringSession(stringSession);
const options = { connectionRetries: 5, baseLogger: new Logger("debug") };
const client = new TelegramClient(session, apiId, apiHash, options);
client.session.setDC(2, "149.154.167.50", 443);
await client.connect();
return client;
};
const getLoginCodeCommand = (phoneNumber: string) => {
const settings = new Api.CodeSettings();
const args = { phoneNumber, apiId, apiHash, settings };
return new Api.auth.SendCode(args);
};
(async () => {
const client = await createClient();
const response = await client.invoke(getLoginCodeCommand(phoneNumber));
const { phoneCodeHash } = response;
const args = { phoneNumber, phoneCode, phoneCodeHash };
const result = await client.invoke(new Api.auth.SignIn(args));
console.log("RESULT", result);
})();
But I keep receiving RPCError: PHONE_CODE_INVALID again and again. Any ideas on why it's not woring?
Thanks.
Argument of type 'StringSession' is not assignable to parameter of type 'string | Session'.
Type 'StringSession' is not assignable to type 'Session'.
Types of property 'authKey' are incompatible.
Type 'import("/home/darda/code/js/telenode/node_modules/telegram/gramjs/crypto/AuthKey").AuthKey | undefined' is not assignable to type 'import("/home/darda/code/js/telenode/node_modules/telegram/dist/crypto/AuthKey").AuthKey | undefined'.
Type 'import("/home/darda/code/js/telenode/node_modules/telegram/gramjs/crypto/AuthKey").AuthKey' is not assignable to type 'import("/home/darda/code/js/telenode/node_modules/telegram/dist/crypto/AuthKey").AuthKey'.
Types have separate declarations of a private property '_key'.
what's wrong? I installed using yarn
With this request:
await this.client.invoke(new functions.messages.SendMessageRequest({
peer,
message: 'Hello world!',
entities: [new types.MessageEntityBold({ offset: 0, length: 5 })],
}));
I get an error (only when i add some entities):
"The input request was too long. This may be a bug in the library as it can occur when serializing more bytes than it should (like appending the vector constructor code at the end of a message) (caused by SendMessageRequest)"
How can I send message with some styled text?
hello,i want to use this project in my code,but it's like doesn't support proxy
> npx webpack
[BABEL] Note: The code generator has deoptimised the styling of .../gramjs/gramjs/tl/types/index.js as it exceeds the max of 500KB.
Version: webpack 4.41.2
Time: 16694ms
Built at: 04/19/2020 8:19:13 PM
Asset Size Chunks Chunk Names
gramjs.js 4.43 MiB main [emitted] main
Entrypoint main = gramjs.js
[./gramjs/Helpers.js] 8.11 KiB {main} [built]
[./gramjs/Password.js] 9.07 KiB {main} [built]
[./gramjs/Utils.js] 40.5 KiB {main} [built]
[./gramjs/Version.js] 25 bytes {main} [built]
[./gramjs/client/TelegramClient.js] 95.7 KiB {main} [built]
[./gramjs/crypto/RSA.js] 3.76 KiB {main} [built]
[./gramjs/errors/Common.js] 11.1 KiB {main} [built]
[./gramjs/errors/RPCBaseErrors.js] 12.4 KiB {main} [built]
[./gramjs/errors/RPCErrorList.js] 208 KiB {main} [built]
[./gramjs/errors/index.js] 3.57 KiB {main} [built]
[./gramjs/events/index.js] 3.64 KiB {main} [built]
[./gramjs/index.js] 559 bytes {main} [built]
[./gramjs/network/index.js] 713 bytes {main} [built]
[./gramjs/sessions/index.js] 227 bytes {main} [built]
[./gramjs/tl/index.js] 383 bytes {main} [built]
+ 318 hidden modules
ERROR in ./node_modules/better-sqlite3/build/better_sqlite3.node 1:0
Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
@ ./node_modules/better-sqlite3/lib/database.js 11:18-57
@ ./node_modules/better-sqlite3/lib/index.js
@ ./gramjs/sessions/SQLiteSession.js
@ ./gramjs/client/TelegramClient.js
@ ./gramjs/index.js
ERROR in ./node_modules/integer/build/integer.node 1:0
Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
@ ./node_modules/integer/lib/index.js 3:31-63
@ ./node_modules/better-sqlite3/lib/index.js
@ ./gramjs/sessions/SQLiteSession.js
@ ./gramjs/client/TelegramClient.js
@ ./gramjs/index.js
After making one raw request through gramjs, it went through and returned the correct response but a few seconds after that I got this error on the console:
{ Error: Invalid checksum (1241442304 when 1399867364 was expected). This packet should be skipped.
at FullPacketCodec.<anonymous> (/home/null/apps/epic-light-bot/node_modules/telegram/dist/network/connection/TCPFull.js:53:23)
at Generator.next (<anonymous>)
at fulfilled (/home/null/apps/epic-light-bot/node_modules/telegram/dist/network/connection/TCPFull.js:5:58)
at process._tickCallback (internal/process/next_tick.js:68:7) checksum: 1241442304, validChecksum: 1399867364 }
Any requests after this, result in an error saying it cannot send requests while disconnected:
Error: Cannot send requests while disconnected
at MTProtoSender.send (/home/null/apps/epic-light-bot/node_modules/telegram/dist/network/MTProtoSender.js:199:19)
at TelegramClient.<anonymous> (/home/null/apps/epic-light-bot/node_modules/telegram/dist/client/users.js:39:50)
at Generator.next (<anonymous>)
at fulfilled (/home/null/apps/epic-light-bot/node_modules/telegram/dist/client/users.js:5:58)
at process._tickCallback (internal/process/next_tick.js:68:7)
I'm not sure if I'm doing something wrong. Everything works well, when I do client.start
again.
Also, is there a way to disable the [DEBUG] logs on the console?
As mentioned in title, I compiled it with npx webpack
and when I inspect the entire gramjs
variable, I don't see any functions/types field inside it. As such I am not able to make these calls on the browser. Any idea?
Also, I notice that on the browser implementation, on line 58, the example should be const { StringSession } = gramjs.sessions
instead of const { StringSession } = gramjs.session
.
Any help is appreciated.
I tried to Run example code from the docs in a Amazon EC2 Instance (Ubuntu)
I ran into this error
[2021-05-01T03:35:37.977Z] [ERROR] - [WebSocket connection failed attempt : 4]
[2021-05-01T03:35:38.977Z] [INFO] - [Connecting to 2001:0b28:f23f:f005:0000:0000:0000:000a:443/TCPFull...]
[2021-05-01T03:35:38.977Z] [DEBUG] - [Connecting]
Error: connect ENETUNREACH 2001:0b28:f23f:f005:0000:0000:0000:000a:443 - Local (:::0)
at internalConnect (node:net:905:16)
at defaultTriggerAsyncIdScope (node:internal/async_hooks:435:18)
at node:net:996:9
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
errno: -101,
code: 'ENETUNREACH',
syscall: 'connect',
address: '2001:0b28:f23f:f005:0000:0000:0000:000a',
port: 443
}
[2021-05-01T03:35:38.978Z] [ERROR] - [WebSocket connection failed attempt : 5]
/home/ubuntu/workspace/typetg/node_modules/telegram/network/MTProtoSender.js:200
throw new Error('Cannot send requests while disconnected');
Hi, I was trying to use channels.createChannel method I found a typo in constructor name in Api class
Api.channels.createChannel the name in code is CreateChannel but in example, it's wrong.
Hi,
I`m trying to download media files from channel messages, but if files were uploaded by me from computer it throws error:
Error: Could not create sender for DC 2
For example, if gif were added from ui telegram - its works fine, but if the same gif added from PC - throwing error for some reason.
How can I fix this?
const client = new TelegramClient(session, api_id, api_hash, {});
await client.start();
const result = await client.invoke(new Api.messages.GetHistory({
peer: 'myChannel',
limit: 10,
}));
for (const msg of result.messages) {
if (msg.media) {
const buffer = await client.downloadMedia(msg.media, {
workers: 1,
});
console.log(buffer)
}
}
};
hi, I cannot find any example to handle event update "NewMessage"
As I googled found this https://painor.gitbook.io/gramjs/getting-started/updates-events
this worked fine.
client.addEventHandler((update) => {
console.log("Received new Update");
console.log(update);
});
this one not working.
do you have any example working code for this ?
async function eventPrint(event) {
const message = event.message;
// Checks if it's a private message (from user or bot)
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}`
});
}
}
}
Thank you.
Thank JS-implementation of Telegram client.
I know even the basic project (Telethon) doesn't support the new generation of MTProto proxies (secret: "ee..."
), but this is just a request (to add full support).
How to call request InviteToChannelRequest? This is my code:
const channelIdInvite = inviteId.value
const InputPeerUser = []
listUsers.forEach(function (user) {
InputPeerUser.push(new types.InputUser({
user_id: user["id"],
access_hash: user["accessHash"],
}))
})
const InputChannel = new types.InputChannel({
channel_id: parseInt(channelIdInvite),
access_hash: 4408054091230359217,
})
const result = await client.invoke(new functions.channels.InviteToChannelRequest(
{
channel: InputChannel,
users: InputPeerUser,
},
))
This is console log error:
Uncaught (in promise) TypeError: bigInt is undefined
readBufferFromBigInt webpack://gramjs/./gramjs/Helpers.js?:62
getBytes webpack://gramjs/./gramjs/tl/types/index.js?:531
getBytes webpack://gramjs/./gramjs/tl/functions/channels.js?:1805
RequestState webpack://gramjs/./gramjs/network/RequestState.js?:13
send webpack://gramjs/./gramjs/network/MTProtoSender.js?:289
_callee7$ webpack://gramjs/./gramjs/client/TelegramClient.js?:691
Babel 10
file:///Users/apple/congviec/WorkSpace/TelegramProject/gramjs-master/examples/simpleLogin.js:206
EventListener.handleEvent* file:///Users/apple/congviec/WorkSpace/TelegramProject/gramjs-master/examples/simpleLogin.js:177
What 's wrong? Anyone help, pls?
Thank good library.
How to disable below useful logs to be outputted in the console:
[2020-04-18T18:31:39.876Z] [DEBUG] - [Assigned msgId = 6817121....5403612 to PingRequest]
[2020-04-18T18:31:39.876Z] [DEBUG] - [Encrypting 1 message(s) in 28 bytes for sending]
[2020-04-18T18:31:39.877Z] [DEBUG] - [Encrypted messages put in a queue to be sent]
[2020-04-18T18:31:39.877Z] [DEBUG] - [Waiting for messages to send...]
[2020-04-18T18:31:39.877Z] [DEBUG] - [Assigned msgId = 68171.......4276 to MsgsAck]
[2020-04-18T18:31:39.877Z] [DEBUG] - [Encrypting 1 message(s) in 68 bytes for sending]
[2020-04-18T18:31:39.878Z] [DEBUG] - [Encrypted messages put in a queue to be sent]
[2020-04-18T18:31:39.878Z] [DEBUG] - [Waiting for messages to send...]
[2020-04-18T18:31:40.004Z] [DEBUG] - [Handling pong for message 68171.......5403612]
[2020-04-18T18:31:40.004Z] [DEBUG] - [Receiving items from the network...]
rnd is 30481.....0298941
[2020-04-18T18:32:39.880Z] [DEBUG] - [Assigned msgId = 68171......9442120 to PingRequest]
[2020-04-18T18:32:39.881Z] [DEBUG] - [Encrypting 1 message(s) in 28 bytes for sending]
[2020-04-18T18:32:39.883Z] [DEBUG] - [Encrypted messages put in a queue to be sent]
[2020-04-18T18:32:39.884Z] [DEBUG] - [Waiting for messages to send...]
[2020-04-18T18:32:39.884Z] [DEBUG] - [Assigned msgId = 68171......15441912 to MsgsAck]
[2020-04-18T18:32:39.884Z] [DEBUG] - [Encrypting 1 message(s) in 36 bytes for sending]
[2020-04-18T18:32:39.886Z] [DEBUG] - [Encrypted messages put in a queue to be sent]
[2020-04-18T18:32:39.886Z] [DEBUG] - [Waiting for messages to send...]
[2020-04-18T18:32:40.010Z] [DEBUG] - [Handling pong for message 68171.....99442120]
[2020-04-18T18:32:40.010Z] [DEBUG] - [Receiving items from the network...]
rnd is 79195.....8965
[2020-04-18T18:33:39.884Z] [DEBUG] - [Assigned msgId = 68171......479672 to PingRequest]
[2020-04-18T18:33:39.884Z] [DEBUG] - [Encrypting 1 message(s) in 28 bytes for sending]
[2020-04-18T18:33:39.886Z] [DEBUG] - [Encrypted messages put in a queue to be sent]
[2020-04-18T18:33:39.887Z] [DEBUG] - [Waiting for messages to send...]
[2020-04-18T18:33:39.887Z] [DEBUG] - [Assigned msgId = 68171......479756 to MsgsAck]
[2020-04-18T18:33:39.888Z] [DEBUG] - [Encrypting 1 message(s) in 36 bytes for sending]
[2020-04-18T18:33:39.889Z] [DEBUG] - [Encrypted messages put in a queue to be sent]
[2020-04-18T18:33:39.890Z] [DEBUG] - [Waiting for messages to send...]
[2020-04-18T18:33:40.013Z] [DEBUG] - [Handling pong for message 6817121642213479672]
[2020-04-18T18:33:40.014Z] [DEBUG] - [Receiving items from the network...]
I know these are useful information that help debug purposes, but I don't want to see them between my own logs, in the general states (or see my own logs between them!).
I try to make a test with api GetChannelsRequest
by below code. But I got error when run on command client.start()
const { TelegramClient } = require('gramjs');
const { functions, types } = require('gramjs/tl');
(async () => {
const client = new TelegramClient(name, apiId, apiHash);
await client.start();
const result = await client.invoke(new functions.channels.GetChannelsRequest(
id=['username']
));
console.log(result.stringify());
})();
Thanks for the great work. What do you think about not generating content for /gramjs/tl/*
but rather parsing and processing the TL schema files in runtime? The folder now is very heavy (2+ mb), and it could be x10 less. All the logic that is used for generating those files can be used the same way during the runtime.
Hi,
When trying to use client.downloadMedia i always get this error message:
RPCError: DC_ID_INVALID at Object.RPCMessageToError (/home/julian/Projects/x-io/telegram-client/node_modules/gramjs/errors/index.ts:21:12) at MTProtoSender._handleRPCResult (/home/julian/Projects/x-io/telegram-client/node_modules/gramjs/network/MTProtoSender.ts:560:27) at MTProtoSender.<anonymous> (/home/julian/Projects/x-io/telegram-client/node_modules/gramjs/network/MTProtoSender.ts:478:15) at Generator.next (<anonymous>) at fulfilled (/home/julian/Projects/x-io/telegram-client/node_modules/telegram/network/MTProtoSender.js:5:58) at processTicksAndRejections (internal/process/task_queues.js:93:5) { code: undefined
Any ideas what could be the problem?
Best,
Julian
I was going to get started with gramjs and tried by installing gramsjs
with npm for a simple nodejs project.
const { TelegramClient } = require('telegram/gramjs');
const { StringSession } = require('telegram/gramjs/sessions');
const api_id = xxxxxxx;
const api_hash = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
const string_session = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...';
export function test(input: any) {
console.log("Running test", input);
(async () => {
console.log('Loading interactive example...')
const sessionName = 'anon'
const apiId = api_id
const apiHash = api_hash
const client = new TelegramClient(new StringSession(string_session), apiId, apiHash)
await client.connect()
console.log('You should now be connected.')
await client.sendMessage('me', "hi");
})()
}
And I get the following terminal output when running it.
Error: Cannot find module './rpcbaseerrors'
Require stack:
- /home/tharindu/playground/gramjs-test/node_modules/telegram/gramjs/errors/RPCErrorList.js
- /home/tharindu/playground/gramjs-test/node_modules/telegram/gramjs/errors/index.js
- /home/tharindu/playground/gramjs-test/node_modules/telegram/gramjs/client/TelegramClient.js
- /home/tharindu/playground/gramjs-test/node_modules/telegram/gramjs/index.js
- /home/tharindu/playground/gramjs-test/index.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)
at Function.Module._load (internal/modules/cjs/loader.js:667:27)
at Module.require (internal/modules/cjs/loader.js:887:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/home/tharindu/playground/gramjs-test/node_modules/telegram/gramjs/errors/RPCErrorList.js:1:144)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module.require (internal/modules/cjs/loader.js:887:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/home/tharindu/playground/gramjs-test/node_modules/telegram/gramjs/errors/RPCErrorList.js',
'/home/tharindu/playground/gramjs-test/node_modules/telegram/gramjs/errors/index.js',
'/home/tharindu/playground/gramjs-test/node_modules/telegram/gramjs/client/TelegramClient.js',
'/home/tharindu/playground/gramjs-test/node_modules/telegram/gramjs/index.js',
'/home/tharindu/playground/gramjs-test/index.js'
]
}
Package.json,
{
...
"dependencies": {
"telegram": "^1.0.0-alpha.2"
}
}
Rollup: Missing Export
'TelegramClient' is not exported by ../gramjs/browser/gramjs.js
And are you planning to add types? It’s very difficult to figure out without them.
So we can avoid build issues if it's not even needed mainly, but it should also improve build speed in cases where people are using other session types.
#26 for reference.
I'm trying to get messages from a group using client.getMessages
and a bot.
I have a Telegram group with three people: myself, a friend and a bot.
I changed the privacy settings for the bot and I made the bot an admin in the group:
const { TelegramClient } = require("telegram")
const { StringSession } = require("telegram/sessions")
const stringSession = ""
const apiId = <redacted>
const apiHash = "<redacted>"
const groupId = <redacted>
const BOT_TOKEN = "<redacted" // put your bot token here
;(async () => {
const client = new TelegramClient(
new StringSession(stringSession),
apiId,
apiHash,
{ connectionRetries: 5 }
)
await client.start({
botAuthToken: BOT_TOKEN,
})
console.log(client.session.save())
const msgs = await client.getMessages(groupId, {
limit: 2,
})
// this works
// await client.sendMessage(groupId, { message: "hello there" })
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)
}
})()
Stack trace:
(node:14525) UnhandledPromiseRejectionWarning: Error: BOT_METHOD_INVALID
at Object.RPCMessageToError (/Users/jp/Dev/pag-messages/node_modules/telegram/errors/index.js:24:12)
at MTProtoSender._handleRPCResult (/Users/jp/Dev/pag-messages/node_modules/telegram/network/MTProtoSender.js:491:36)
at MTProtoSender.<anonymous> (/Users/jp/Dev/pag-messages/node_modules/telegram/network/MTProtoSender.js:415:19)
at Generator.next (<anonymous>)
at fulfilled (/Users/jp/Dev/pag-messages/node_modules/telegram/network/MTProtoSender.js:5:58)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:14525) 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:14525) [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.
What am I doing wrong? Any help is appreciated! Thank you
I try importContacts but it's not working
This is my code
import {Api, TelegramClient} from 'telegram';
import { StringSession } from 'telegram/sessions';
const stringSession = '';
const BOT_TOKEN = '';
const apiId = '';
const apiHash = '';
const session = new StringSession(stringSession);
const client = new TelegramClient(session, apiId, apiHash, {});
export default async (req, res) => {
const result = await client.invoke(
new Api.contacts.importContacts({
contacts: [
new Api.InputContact({
phone_number: '+888xxxx',
first_name: 'mob12',
last_name: 'mob12',
client_id: 0
}),
],
}),
);
console.log(result);
res.status(200).json({ success: true })
}
Then error code
TypeError: telegram__WEBPACK_IMPORTED_MODULE_0__.Api.InputContact is not a constructor
at __webpack_exports__.default (webpack-internal:///./pages/api/hello.js:18:16)
at apiResolver (/Users/vomanhkien/dev/test/gram-bot/node_modules/next/dist/next-server/server/api-utils.js:8:7)
at processTicksAndRejections (node:internal/process/task_queues:93:5)
at async DevServer.handleApiRequest (/Users/vomanhkien/dev/test/gram-bot/node_modules/next/dist/next-server/server/next-server.js:66:462)
at async Object.fn (/Users/vomanhkien/dev/test/gram-bot/node_modules/next/dist/next-server/server/next-server.js:58:580)
at async Router.execute (/Users/vomanhkien/dev/test/gram-bot/node_modules/next/dist/next-server/server/router.js:25:67)
at async DevServer.run (/Users/vomanhkien/dev/test/gram-bot/node_modules/next/dist/next-server/server/next-server.js:68:1042)
at async DevServer.handleRequest (/Users/vomanhkien/dev/test/gram-bot/node_modules/next/dist/next-server/server/next-server.js:32:504)
I expected a sendMessage()
method in TelegramClient
. Like send_message()
in Telethon.
If it hasn't been implemented yet, is there an alternative way to send messages?
const client = new TelegramClient(new StringSession(''), apiId, apiHash)
await client.save()
When I try to compile the project I get errors like
"node_modules/telegram/tl/api.d.ts:3421:63 - error TS2344: Type 'void' does not satisfy the constraint 'AnyLiteral'.
3421 export class ChannelParticipantsAdmins extends VirtualClass<void> {};"
"node_modules/telegram/tl/api.d.ts:3443:65 - error TS2344: Type 'void | { q?: string | undefined; topMsgId?: number | undefined; }'
does not satisfy the constraint 'AnyLiteral'.
Type 'void' is not assignable to type 'AnyLiteral'.
3443 export class ChannelParticipantsMentions extends VirtualClass<{
~
3444 // flags: null;
~~~~~~~~~~~~~~~~~~~
...
3446 topMsgId?: int;
~~~~~~~~~~~~~~~~~~~
3447 } | void> {"
"node_modules/telegram/tl/api.d.ts:3749:13 - error TS2304: Cannot find name 'double'.
3749 rating: double;"
"node_modules/telegram/tl/api.d.ts:9815:70 - error TS1036: Statements are not allowed in ambient contexts.
9815 export class GetState extends Request<void, updates.TypeState> {};"
"node_modules/telegram/tl/api.d.ts:6301:12 - error TS2304: Cannot find name 'future_salt'.
6301 salts: future_salt[];"
"node_modules/telegram/tl/api.d.ts:36:53 - error TS2302: Static members cannot reference class type parameters.
36 static fromReader(reader: Reader): VirtualClass<Args>;"
"node_modules/telegram/tl/custom/message.d.ts:39:59 - error TS2694: Namespace '"C:/Users/ASUS/source/repos/platform/platform/server/server/node_modules/ts-mixer/dist/types/index"' has no exported member 'Class'."
and other....
Throws error when used with node 10.x.x because node 10 doesn't support static class fields.
static DEFAULT_OPTIONS = {
^
SyntaxError: Unexpected token =
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (/private/tmp/telegram-try/node_modules/telegram/gramjs/index.js:4:24)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
Either the source should be transpiled to ES5 syntax on postinstall so that it runs in most JavaScript environments or add an engines field to package.json mentioning compatible node versions.
Note: Works fine with node 12.x.x
I just copied and pasted the code, didn't change, didn't modify.
And when sending several messages, everything was fine, but the next time when sending a message to myself, I got a ban, without explaining the reasons.
I tried it on another account - the result is the same - a ban, but after sending one message.
here is my teamplate:
import { TelegramClient } from 'telegram'
import { StringSession } from 'telegram/sessions'
import input from 'input'; // npm i input
const apiId = 123456
const apiHash = '123456abcdfg'
const stringSession = new StringSession(''); // fill this later with the value from session.save()
(async () => {
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('You should now be connected.');
console.log(client.session.save()) // Save this string to avoid logging in again
await client.sendMessage('me', { message: 'Hello!' });
})()
Following the documentation here to get my messages https://painor.gitbook.io/gramjs/getting-started/available-methods/getmessages
(async () => {
const client = new TelegramClient(new StringSession(stringSession), apiId, apiHash, {connection: ConnectionTCPObfuscated})
await client.connect();
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);
}
})();
But it's throwing a ReferenceError: ConnectionTCPObfuscated is not defined
what am I doing wrong?
I'm trying to retreive all dialogs, but i keep getting an error message
(async function run() {
const result: Api.messages.Dialogs = await client.invoke(new Api.messages.GetDialogs();
console.log(result); // prints the result
})();
node:65944 UnhandledPromiseRejectionWarning: Error: Cannot cast undefined to any kind of undefined
at _raiseCastFail (\node_modules\telegram\Utils.js:21:11)
at Object.getPeer (\node_modules\telegram\Utils.js:836:9)
at Object. (\node_modules\telegram\client\users.js:242:26)
at Generator.next ()
at \node_modules\telegram\client\users.js:8:71
at new Promise ()
at __awaiter (\node_modules\telegram\client\users.js:4:12)
at Object.getInputEntity (\node_modules\telegram\client\users.js:198:12)
at TelegramClient.getInputEntity (\node_modules\telegram\client\TelegramClient.js:198:28)
at \node_modules\telegram\tl\api.js:129:56
I'm running this on my code:
const responseParticipants = await this.gramBot.invoke(
new functions.channels.GetParticipantsRequest({
channel: chat_id,
filter: new types.ChannelParticipantsRecent(),
}),
);
However, while this works on my local computer, in my VPS, I always get this error:
TypeError: Cannot read property 'SUBCLASS_OF_ID' of undefined
at Object.getPeer (/home/ninja/monetizze-gram/node_modules/telegram/gramjs/Utils.js:304:18)
at TelegramClient.getInputEntity (/home/ninja/monetizze-gram/node_modules/telegram/gramjs/client/TelegramClient.js:800:22)
at GetParticipantsRequest.resolve (/home/ninja/monetizze-gram/node_modules/telegram/gramjs/tl/functions/channels.js:253:59)
at TelegramClient.invoke (/home/ninja/monetizze-gram/node_modules/telegram/gramjs/client/TelegramClient.js:253:23)
at Timeout._onTimeout (/home/ninja/monetizze-gram/src/bot.js:49:61)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
(node:20700) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'constructor' of undefined
at _raiseCastFail (/home/ninja/monetizze-gram/node_modules/telegram/gramjs/Utils.js:13:43)
at Object.getPeer (/home/ninja/monetizze-gram/node_modules/telegram/gramjs/Utils.js:333:5)
at TelegramClient.getInputEntity (/home/ninja/monetizze-gram/node_modules/telegram/gramjs/client/TelegramClient.js:800:22)
at GetParticipantsRequest.resolve (/home/ninja/monetizze-gram/node_modules/telegram/gramjs/tl/functions/channels.js:253:59)
at TelegramClient.invoke (/home/ninja/monetizze-gram/node_modules/telegram/gramjs/client/TelegramClient.js:253:23)
at Timeout._onTimeout (/home/ninja/monetizze-gram/src/bot.js:49:61)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
(node:20700) 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: 4)
I have no idea why this is happening.
Want to move from telethon (python) to nodejs but seems the example code from https://painor.gitbook.io/gramjs/ does not work (anymore).
const { StringSession } = require('telegram/sessions')
const input = require('input') // npm i input
const apiId = 111111
const apiHash = 'fcf............................'
const stringSession = new StringSession(''); // fill this later with the value from session.save()
(async () => {
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('You should now be connected.')
console.log(client.session.save()) // Save this string to avoid logging in again
await client.sendMessage('me', { message: 'Hello!' });
})()
Is not able to create the websocket connection.
[2021-05-22T21:17:08.354Z] [DEBUG] - [Connecting]
[2021-05-22T21:17:08.378Z] [DEBUG] - [Finished connecting]
[2021-05-22T21:17:08.379Z] [DEBUG] - [Connection success!]
[2021-05-22T21:17:08.379Z] [DEBUG] - [New auth_key attempt ...]
[2021-05-22T21:17:08.408Z] [ERROR] - [WebSocket connection failed attempt : 1]
[2021-05-22T21:17:09.409Z] [INFO] - [Connecting to 149.154.167.51:80/TCPFull...]
[2021-05-22T21:17:09.410Z] [DEBUG] - [Connecting]
[2021-05-22T21:17:09.433Z] [DEBUG] - [Finished connecting]
[2021-05-22T21:17:09.433Z] [DEBUG] - [Connection success!]
[2021-05-22T21:17:09.433Z] [DEBUG] - [New auth_key attempt ...]
[2021-05-22T21:17:09.455Z] [ERROR] - [WebSocket connection failed attempt : 2]
Why does it try to build the connection over port 80? Also https://my.telegram.org/apps points towards 149.154.167.50:443 for production. Which does not match with the IP shown above.
Telegram version 1.5.23
client.invoke(new functions.messages.GetDialogsRequest({ limit: limit, offsetPeer: new types.InputPeerEmpty(), }));
error1: Received msg_key doesn't match with expected one
error2: Server replied with an invalid auth key
error3: Handshake inactivity timeout
How to solve these errors?
put some working javascript examples
Hi, I want to get all messages and updates realtime in a group, which method should I use and how?
Also how should I fill "InputChannel" ?
[new Api.InputChannel({...})] ??
Cheers
head to api/ directory and create a copy of the settings_example file, naming it settings (lowercase!). Then fill the file with the corresponding values (your api_id, api_hash and phone number in international format).
I've tested the same session string with telethon and it worked. No clue why I'm getting this on gramjs:
(node:5682) UnhandledPromiseRejectionWarning: Error: No more data left to read (need 23404, got 260: 8p�o��GAT.�@/��˥�o7Q�ʬ�L�`�v�#<o�E�I�L7
9s��?�����~_גt�o�f��ٱi�N��<�g�$���^���i�D��k�x���4���ʌ�����Hv�b�o>l{�������=
�؛O�ʨ��Խ �)�§��2O;H��&�
M����.٬��(�$7); last read [l
at BinaryReader.read (/home/zero/apps/epic-light-bot-old/epic-light-bot/node_modules/telegram/dist/extensions/BinaryReader.js:85:19)
at new StringSession (/home/zero/apps/epic-light-bot-old/epic-light-bot/node_modules/telegram/dist/sessions/StringSession.js:46:49)
at Object.<anonymous> (/home/zero/apps/epic-light-bot-old/epic-light-bot/gramjs.js:6:22)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Module.require (internal/modules/cjs/loader.js:1026:19)
at require (internal/modules/cjs/helpers.js:72:18)
at /home/zero/apps/epic-light-bot-old/epic-light-bot/testgram.js:2:23
My code is:
var string_session = new StringSession(STRING_SESSION);
const client = new TelegramClient(string_session, API_ID, API_HASH);
After compiling everything and trying to run the index.js file, it doesn't finish loading. In the HTML file the phone number box is disabled. I tried to start all the .js files and none of them initialize the connection.
When running /examples/main.js
(async () => {
^
TypeError: require(...) is not a function
at Object.<anonymous> (/mnt/c/Users/Isco/Desktop/gramjs-master/examples/main.js:4:1)
When running /examples/simpleLogin.js
const phoneDiv = document.getElementById('phoneDiv')
^
ReferenceError: document is not defined
at Object.<anonymous> (/mnt/c/Users/Isco/Desktop/gramjs-master/examples/simpleLogin.js:1:18)
Does anyone know what that might be?
Hello, Could someone help me figure out how to set appropriate type for parameter accessHash
in Api.InputChannel
API ?
Here is the example of my code, all parameters are pseudo numbers but of the same digits as the real one
const result = await client.invoke(
new Api.channels.GetParticipants({
channel: new Api.InputChannel({channelId: 1306372915, accessHash: BigInt(-2089358348472948573)})
})
But I got the following error:
(node:32673) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'getBytes' of undefined
at argToBytes (/Users/swen/Downloads/Repository/telebot/node_modules/telegram/tl/api.js:122:22)
at VirtualClass.getBytes (/Users/swen/Downloads/Repository/telebot/node_modules/telegram/tl/api.js:378:42)
It seems that accessHash cannot be parsed by getBytes
method in telegram/tl/api.js
, and I also tried import big-integer
dependency as type suggested.
import bigInt from 'big-integer'
const result = await client.invoke(
new Api.channels.GetParticipants({
channel: new Api.InputChannel({channelId: 1306372915, accessHash: bigInt(-2089358348472948573)})
})
which results in the same error.
So how to correctly parse accessHash
parameter in this case ?
Thanks in advance
When I try to import the project directly from GitHub:
➜ project git:(master) ✗ yarn add https://github.com/gram-js/gramjs
yarn add v1.22.10
[1/4] 🔍 Resolving packages...
[2/4] 🚚 Fetching packages...
warning Pattern ["mime-types@latest"] is trying to unpack in the same destination "/Users/camille/Library/Caches/Yarn/v6/npm-mime-types-2.1.28-1160c4757eab2c5363888e005273ecf79d2a0ecd-integrity/node_modules/mime-types" as pattern ["mime-types@^2.1.12","mime-types@^2.1.12","mime-types@~2.1.19","mime-types@^2.1.12"]. This could result in non-deterministic behavior, skipping.
[3/4] 🔗 Linking dependencies...
[4/4] 🔨 Building fresh packages...
[3/3] ⢀ telegram
[-/3] ⢀ waiting...
error /Users/camille/Desktop/project/node_modules/telegram: Command failed.
Exit code: 2
Command: npm run tsc
Arguments:
Directory: /Users/camille/Desktop/project/node_modules/telegram
Output:
> [email protected] tsc
> tsc
gramjs/extensions/PromisedWebSockets.ts(1,28): error TS7016: Could not find a declaration file for module 'websocket'. '/Users/camille/Desktop/project/node_modules/websocket/index.js' implicitly has an 'any' type.
Try `npm i --save-dev @types/websocket` if it exists or add a new declaration (.d.ts) file containing `declare module 'websocket';`
gramjs/Helpers.ts(1,22): error TS7016: Could not find a declaration file for module 'browser-or-node'. '/Users/camille/Desktop/project/node_modules/browser-or-node/lib/index.js' implicitly has an 'any' type.
Try `npm i --save-dev @types/browser-or-node` if it exists or add a new declaration (.d.ts) file containing `declare module 'browser-or-node';`
gramjs/tl/core/GZIPPacked.ts(2,23): error TS7016: Could not find a declaration file for module 'pako'. '/Users/camille/Desktop/project/node_modules/pako/index.js' implicitly has an 'any' type.
Try `npm i --save-dev @types/pako` if it exists or add a new declaration (.d.ts) file containing `declare module 'pako';`
gramjs/Utils.ts(8,18): error TS7016: Could not find a declaration file for module 'mime-types'. '/Users/camille/Desktop/project/node_modules/mime-types/index.js' implicitly has an 'any' type.
Try `npm i --save-dev @types/mime-types` if it exists or add a new declaration (.d.ts) file containing `declare module 'mime-types';`
gramjs/Utils.ts(755,17): error TS2322: Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
npm ERR! code 2
npm ERR! path /Users/camille/Desktop/project/node_modules/telegram
npm ERR! command failed
npm ERR! command sh -c tsc
Installing @types/websocket solves the error, but other type error pop up.
I think that it does not install the required dev dependencies when installing directly from GitHub
➜ project git:(master) ✗ yarn add telegram
yarn add v1.22.10
[1/4] 🔍 Resolving packages...
[2/4] 🚚 Fetching packages...
[3/4] 🔗 Linking dependencies...
[4/4] 🔨 Building fresh packages...
[1/4] ⠄ puppeteer
[-/4] ⠄ waiting...
[4/4] ⠄ telegram
error /Users/camille/Desktop/project/node_modules/telegram: Command failed.
Exit code: 2
Command: npm run tsc
Arguments:
Directory: /Users/camille/Desktop/project/node_modules/telegram
Output:
> [email protected] tsc
> tsc
gramjs/client/auth.ts(198,17): error TS2794: Expected 1 arguments, but got 0. Did you forget to include 'void' in your type argument to 'Promise'?
npm ERR! code 2
npm ERR! path /Users/camille/Desktop/project/node_modules/telegram
npm ERR! command failed
npm ERR! command sh -c tsc
I believe that my strict tsconfig might cause this error:
{
"compilerOptions": {
"module": "CommonJS",
"target": "ES6",
"strictFunctionTypes": true,
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"removeComments": true,
"outDir": "dist",
"allowJs": true,
"lib": ["esnext.asynciterable", "DOM", "ES2016"]
},
"typeAcquisition": {
"enable": true,
"include": ["jest", "jest-chain", "jest-extended"]
}
}
put some working javascript examples :|
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.