lowLevel.js 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. const express = require("express"); // npm i express
  2. const bodyParser = require("body-parser"); // npm i body-parser
  3. const { Api, TelegramClient, utils } = require("telegram");
  4. const { StoreSession } = require("telegram/sessions");
  5. const app = express();
  6. app.use(bodyParser.urlencoded({ extended: false }));
  7. app.use(bodyParser.json());
  8. const port = 8080; // default port to listen
  9. const BASE_TEMPLATE = `
  10. <!DOCTYPE html>
  11. <html>
  12. <head>
  13. <meta charset='UTF-8'>
  14. <title>GramJS + Express</title>
  15. </head>
  16. <body>{{0}}</body>
  17. </html>
  18. `;
  19. const PHONE_FORM = `
  20. <form action='/' method='post'>
  21. Phone (international format): <input name='phone' type='text' placeholder='+34600000000'>
  22. <input type='submit'>
  23. </form>
  24. `;
  25. const CODE_FORM = `
  26. <form action='/' method='post'>
  27. Telegram code: <input name='code' type='text' placeholder='70707'>
  28. <input type='submit'>
  29. </form>
  30. `;
  31. const PASSWORD_FORM = `
  32. <form action='/' method='post'>
  33. Telegram password: <input name='password' type='text' placeholder='your password (leave empty if no password)'>
  34. <input type='submit'>
  35. </form>
  36. `;
  37. const API_ID = -1; // Fill your API ID
  38. const API_HASH = ""; // Fill your API Hash
  39. // Single client; can use an object if you want to store multiple clients
  40. const client = new TelegramClient(
  41. new StoreSession("session_name"),
  42. API_ID,
  43. API_HASH,
  44. {}
  45. );
  46. let phone;
  47. let phoneCodeHash; // needed for sign in
  48. // define a route handler for the default home page
  49. app.get("/", async (req, res) => {
  50. if (await client.isUserAuthorized()) {
  51. const dialog = (await client.getDialogs({ limit: 1 }))[0];
  52. let result = `<h1>${dialog.title}</h1>.`;
  53. for (const m of await client.getMessages(dialog.entity, { limit: 10 })) {
  54. result += formatMessage(m);
  55. }
  56. return res.send(BASE_TEMPLATE.replace("{{0}}", result));
  57. } else {
  58. return res.send(BASE_TEMPLATE.replace("{{0}}", PHONE_FORM));
  59. }
  60. });
  61. app.post("/", async (req, res) => {
  62. //To access POST variable use req.body()methods.
  63. if ("phone" in req.body) {
  64. phone = req.body.phone;
  65. const result = await client.sendCode(
  66. {
  67. apiId: API_ID,
  68. apiHash: API_HASH,
  69. },
  70. phone
  71. );
  72. phoneCodeHash = result.phoneCodeHash;
  73. return res.send(BASE_TEMPLATE.replace("{{0}}", CODE_FORM));
  74. }
  75. if ("code" in req.body) {
  76. try {
  77. await client.invoke(
  78. new Api.auth.SignIn({
  79. phoneNumber: phone,
  80. phoneCodeHash,
  81. phoneCode: req.body.code,
  82. })
  83. );
  84. } catch (err) {
  85. if (err.errorMessage === "SESSION_PASSWORD_NEEDED") {
  86. return res.send(BASE_TEMPLATE.replace("{{0}}", PASSWORD_FORM));
  87. }
  88. }
  89. }
  90. if ("password" in req.body) {
  91. await client.signInWithPassword(
  92. {
  93. apiId: API_ID,
  94. apiHash: API_HASH,
  95. },
  96. {
  97. password: req.body.password,
  98. onError: (err) => {
  99. throw err;
  100. },
  101. }
  102. );
  103. }
  104. res.redirect("/");
  105. });
  106. function formatMessage(message) {
  107. let content = (message.text || "(action message or media)").replace(
  108. "\n",
  109. "<br>"
  110. );
  111. return `<p><strong>${utils.getDisplayName(
  112. message.sender
  113. )}</strong>: ${content}<sub>${message.date}</sub></p>`;
  114. }
  115. // callbacks for code and password also
  116. // then inside your grammy code when use sends phone do the following
  117. // start the Express server
  118. app.listen(port, async () => {
  119. client.session.setDC(2, "149.154.167.40", 80);
  120. client.setParseMode("html");
  121. // Connect before fully starting the server
  122. await client.connect();
  123. console.log(`server started at http://localhost:${port}`);
  124. });