Skip to content

Commit d8350dd

Browse files
author
windka
committed
fixed #1
1 parent 89bf314 commit d8350dd

File tree

5 files changed

+126
-50
lines changed

5 files changed

+126
-50
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
# Changelog
22
All notable changes to this project will be documented in this file.
33

4+
# [0.1.1] - 2023-10-08
5+
### login with bot token added - [#1](https://github.com/windkh/node-red-node-telegrambot/issues/1)
6+
47
## [0.1.0]
58
### Added readme and examples, tested echo flow
69

README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
...
1414

1515

16-
This package contains a node which act as a Telegram Client. It is based on gramjs which implements the mtproto mobild protocol. (see https://core.telegram.org/mtproto). Unlike node-red-contrib-telegrambot it does not support the telegram bot api. The package can be used to create so-called userbots or selfbots which to automate things under your own user-name. However you should be aware of the fact, that if you cause flooding and other havoc telegram will quickly ban your account either for 24h or even forever. It is recommended to use a test account while developing.
16+
This package contains a node which act as a Telegram Client. It is based on gramjs which implements the mtproto mobile protocol. (see https://core.telegram.org/mtproto). Unlike node-red-contrib-telegrambot it does not support the telegram bot api. The package can be used to create so-called userbots or selfbots which to automate things under your own user-name. However you should be aware of the fact, that if you cause flooding and other havoc telegram will quickly ban your account either for 24h or even forever. It is recommended to use a test account while developing.
1717

1818

1919
# Thanks for your donation
@@ -53,14 +53,15 @@ Changes can be followed [here](/CHANGELOG.md).
5353
## Basics
5454
### Authentication
5555
The *Telegram client receiver* node receives messages from like a telegram client. You need to login with a phone-number and an API ID and API Hash in order to be able to receive message under your own user name.
56+
In addition to that you can also login using a bot token retrieved from @botfather.
5657

5758
You can create an API ID and Hash when you login to your telegram account here https://my.telegram.org/auth
5859
Then go to 'API Development Tools' and create your API ID and API Hash. Both are required when configuring your nodes. The nodes login only once to create a so-called session string. This string can be created from within
5960
the config node or as an alternative you can also create it online here https://tgsnake.js.org/login
6061
This session string is used instead of interactive login (where you need to enter a phone-code and your password if set).
6162

6263
### Receiver Node
63-
The *Telegram client receiver* node receives message which are sent to your account. Just add a debug node to the
64+
The *Telegram client receiver* node receives message which are sent to your account or bot. Just add a debug node to the
6465
output and investigate the objects in `msg.payload`.
6566

6667
### Sender Node

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "node-red-node-telegrambot",
3-
"version": "0.1.0",
3+
"version": "0.1.1",
44
"description": "Telegram userbot nodes for Node-RED",
55
"dependencies": {
66
"telegram": "^2.18.38"

telegrambot/telegrambot.html

Lines changed: 41 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,37 +8,59 @@
88
defaults: {
99
botname: { value: "", required: true },
1010
verboselogging: { value: false, required: false },
11+
loginmode: { value: "user", required: true },
1112
},
1213
credentials: {
1314
apiid: { value: 0, required: true, validate:function(v) { return ((v === "") || (RED.validators.number(v) && (v >= 0) && (v <= 4294967295))) }},
1415
apihash: { value: "", required: true },
1516
session: { value: "", required: true, validate:function(v) { return v.length > 0;}},
1617
phonenumber: { value: "", required: true },
1718
password: { value: "", required: false },
19+
bottoken: { type: "text" }
1820
},
1921
label: function () {
2022
return this.botname;
2123
},
2224
oneditprepare: function() {
25+
// polling or webhook
26+
var updateLoginMode = function() {
27+
var mode = $("#node-config-input-loginmode").val();
28+
if (mode == "user") {
29+
$("#phonenumber").show();
30+
$("#password").show();
31+
$("#bottoken").hide();
32+
} else {
33+
$("#phonenumber").hide();
34+
$("#password").hide();
35+
$("#bottoken").show();
36+
}
37+
};
38+
updateLoginMode();
39+
$("#node-config-input-loginmode").change(updateLoginMode);
40+
2341
var login = function() {
2442

2543
let apiId = $("#node-config-input-apiid").val();
2644
let apiHash = $("#node-config-input-apihash").val();
2745
let phoneNumber = $("#node-config-input-phonenumber").val();
2846
let password = $("#node-config-input-password").val();
29-
30-
if (apiId !== '' && apiHash !== '' && phoneNumber !== '') {
47+
let botToken = $("#node-config-input-bottoken").val();
48+
let loginMode = $("#node-config-input-loginmode").val();
49+
50+
if (apiId !== '' && apiHash) {
3151
let parameters = {
3252
apiId : apiId,
3353
apiHash : apiHash,
3454
phoneNumber : phoneNumber,
35-
password : password
55+
password : password,
56+
botToken : botToken,
57+
loginMode : loginMode
3658
}
3759

3860
$("#loginbuttontip").text("Login started: enter code in field below.");
3961
$("#node-config-input-phonecode").val('');
4062
$("#node-config-input-session").val('');
41-
$.getJSON('node-red-node-telegrambot-loginuser', parameters, function(data) {
63+
$.getJSON('node-red-node-telegrambot-login', parameters, function(data) {
4264
if(data.session){
4365
debugger
4466
$("#node-config-input-session").val(data.session);
@@ -118,9 +140,22 @@
118140
</div>
119141

120142
<div class="form-row">
121-
<div class="form-row">
143+
<label for="node-config-input-loginmode"><i class="fa fa-link"></i> Login Mode</label>
144+
<select id="node-config-input-loginmode">
145+
<option value="user">User</option>
146+
<option value="bot">Bot</option>
147+
</select>
148+
</div>
149+
150+
<div class="form-row">
151+
<div class="form-row hidden" id="phonenumber">
122152
<label for="node-config-input-phonenumber"><i class="fa fa-mobile"></i> Phone-Number</label>
123153
<input type="text" id="node-config-input-phonenumber" placeholder="(+49...)">
154+
</div>
155+
<div class="form-row hidden" id="bottoken">
156+
<label for="node-config-input-bottoken"><i class="fa fa-key"></i> Bot-Token</label>
157+
<input type="text" id="node-config-input-bottoken" placeholder="(Enter the bot token from botfather here)">
158+
<div class="form-tips" style="width: auto"><b>Tip:</b> If you don't have a token yet, you can create a new one here: <a href="https://t.me/BotFather">@BotFather</a>.</div>
124159
</div>
125160
<div class="form-row">
126161
<label for="node-config-input-apiid"><i class="fa fa-key"></i> ApiID</label>
@@ -155,7 +190,7 @@
155190
<input type="text" id="node-config-input-phonecode" placeholder="(Enter phone code here)">
156191
</div>
157192

158-
<div class="form-row">
193+
<div class="form-row hidden" id="password">
159194
<label for="node-config-input-password"><i class="fa fa-lock"></i> Password</label>
160195
<input type="text" id="node-config-input-password" placeholder="(Only needed if Two-Step-Verification is on)">
161196
</div>

telegrambot/telegrambot.js

Lines changed: 78 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,15 @@ module.exports = function (RED) {
3131
return getPassword;
3232
}
3333

34-
async function loginUser(parameters, getPhoneCode, getPassword, sessionCreated, error) {
34+
async function login(parameters, getPhoneCode, getPassword, sessionCreated, error) {
3535
try {
3636
let apiId = Number(parameters.apiId);
3737
let apiHash = parameters.apiHash;
3838
let phoneNumber = parameters.phoneNumber;
39+
let botToken = parameters.botToken;
3940
let password = parameters.password;
41+
let loginMode = parameters.loginMode;
42+
4043
if (password === undefined || password === '') {
4144
password = async () => await getPassword;
4245
}
@@ -49,17 +52,27 @@ module.exports = function (RED) {
4952

5053
// client.setLogLevel('debug');
5154

52-
let authParams = {
53-
phoneNumber: phoneNumber,
54-
phoneCode: async () => await getPhoneCode,
55-
password: password,
56-
onError: (err) => {
57-
console.log(err);
58-
// if (err.errorMessage === 'PHONE_CODE_INVALID') {
59-
// }
60-
return true; // abort
61-
},
62-
};
55+
let authParams;
56+
if (loginMode === 'user') {
57+
authParams = {
58+
phoneNumber: phoneNumber,
59+
phoneCode: async () => await getPhoneCode,
60+
password: password,
61+
onError: (err) => {
62+
console.log(err);
63+
// if (err.errorMessage === 'PHONE_CODE_INVALID') {
64+
// }
65+
return true; // abort
66+
},
67+
};
68+
} else if (loginMode === 'bot') {
69+
authParams = {
70+
botAuthToken: botToken,
71+
};
72+
} else {
73+
throw 'LoginMode ' + loginMode + ' is not supported';
74+
}
75+
6376
await client.start(authParams);
6477

6578
let session = client.session.save();
@@ -103,14 +116,14 @@ module.exports = function (RED) {
103116
res.json('ok');
104117
});
105118

106-
RED.httpAdmin.get('/node-red-node-telegrambot-loginuser', function (req, res) {
119+
RED.httpAdmin.get('/node-red-node-telegrambot-login', function (req, res) {
107120
let parameters = req.query;
108121

109122
let getPhoneCode = createPhoneCodePromise();
110123
let getPassword = createPasswordPromise();
111124

112125
try {
113-
loginUser(
126+
login(
114127
parameters,
115128
getPhoneCode,
116129
getPassword,
@@ -149,6 +162,10 @@ module.exports = function (RED) {
149162
this.client = null;
150163
this.logLevel = 'warn'; // 'none', 'error', 'warn','info', 'debug'
151164
this.verbose = n.verboselogging;
165+
this.loginMode = n.loginmode;
166+
if (!this.loginMode) {
167+
this.loginMode = 'user';
168+
}
152169

153170
if (this.verbose) {
154171
this.logLevel = 'info';
@@ -162,7 +179,7 @@ module.exports = function (RED) {
162179
this.phoneNumber = this.credentials.phonenumber || '';
163180
}
164181

165-
this.createTelegramClient = async function createTelegramClient(node, apiId, apiHash, session, phoneNumber, logLevel) {
182+
this.createTelegramClient = async function createTelegramClient(node, apiId, apiHash, session, phoneNumber, botToken, logLevel) {
166183
let client;
167184
try {
168185
if (apiId !== undefined && apiId !== '' && session !== undefined && session !== '') {
@@ -174,13 +191,21 @@ module.exports = function (RED) {
174191

175192
client.setLogLevel(logLevel);
176193

177-
let authParams = {
178-
phoneNumber: phoneNumber,
179-
onError: (err) => {
180-
console.log(err);
181-
return true; // abort
182-
},
183-
};
194+
let authParams;
195+
if (botToken === undefined) {
196+
authParams = {
197+
phoneNumber: phoneNumber,
198+
onError: (err) => {
199+
console.log(err);
200+
return true; // abort
201+
},
202+
};
203+
} else {
204+
authParams = {
205+
botAuthToken: botToken,
206+
};
207+
}
208+
184209
await client.start(authParams);
185210
} else {
186211
node.warn('No session: login first.');
@@ -195,7 +220,7 @@ module.exports = function (RED) {
195220
// Activates the client or returns the already activated bot.
196221
this.getTelegramClient = async function (node) {
197222
if (!this.client) {
198-
this.client = await this.createTelegramClient(node, this.apiId, this.apiHash, this.session, this.phoneNumber, this.logLevel);
223+
this.client = await this.createTelegramClient(node, this.apiId, this.apiHash, this.session, this.phoneNumber, this.botToken, this.logLevel);
199224
}
200225

201226
return this.client;
@@ -242,15 +267,19 @@ module.exports = function (RED) {
242267
};
243268

244269
const start = async () => {
245-
let client = await node.config.getTelegramClient(node);
246-
if (client) {
247-
node.status({
248-
fill: 'green',
249-
shape: 'ring',
250-
text: 'connected',
251-
});
270+
if (node.config) {
271+
let client = await node.config.getTelegramClient(node);
272+
if (client) {
273+
node.status({
274+
fill: 'green',
275+
shape: 'ring',
276+
text: 'connected',
277+
});
252278

253-
client.addEventHandler(eventHandler, new NewMessage({}));
279+
client.addEventHandler(eventHandler, new NewMessage({}));
280+
}
281+
} else {
282+
// no config node?
254283
}
255284
};
256285
start();
@@ -271,13 +300,17 @@ module.exports = function (RED) {
271300
this.config = RED.nodes.getNode(this.bot);
272301

273302
const start = async () => {
274-
let client = await node.config.getTelegramClient(node);
275-
if (client) {
276-
node.status({
277-
fill: 'green',
278-
shape: 'ring',
279-
text: 'connected',
280-
});
303+
if (node.config) {
304+
let client = await node.config.getTelegramClient(node);
305+
if (client) {
306+
node.status({
307+
fill: 'green',
308+
shape: 'ring',
309+
text: 'connected',
310+
});
311+
}
312+
} else {
313+
// no config node?
281314
}
282315
};
283316
start();
@@ -314,9 +347,13 @@ module.exports = function (RED) {
314347

315348
this.on('input', async function (msg, nodeSend, nodeDone) {
316349
if (msg.payload) {
317-
let client = await node.config.getTelegramClient(node);
318-
if (client) {
319-
this.processMessage(client, msg, nodeSend, nodeDone);
350+
if (node.config) {
351+
let client = await node.config.getTelegramClient(node);
352+
if (client) {
353+
this.processMessage(client, msg, nodeSend, nodeDone);
354+
}
355+
} else {
356+
// no config node?
320357
}
321358
}
322359
});

0 commit comments

Comments
 (0)