usingStart.js 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. const express = require("express"); // npm i express
  2. const bodyParser = require("body-parser"); // npm i body-parser
  3. const { 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. // define a route handler for the default home page
  48. app.get("/", async (req, res) => {
  49. if (await client.isUserAuthorized()) {
  50. const dialog = (await client.getDialogs({ limit: 1 }))[0];
  51. let result = `<h1>${dialog.title}</h1>.`;
  52. for (const m of await client.getMessages(dialog.entity, { limit: 10 })) {
  53. result += formatMessage(m);
  54. }
  55. return res.send(BASE_TEMPLATE.replace("{{0}}", result));
  56. } else {
  57. client.start({
  58. phoneNumber: async () => {
  59. return phoneCallback.promise;
  60. },
  61. phoneCode: async () => {
  62. return codeCallback.promise;
  63. },
  64. password: async () => {
  65. return passwordCallback.promise;
  66. },
  67. onError: (err) => console.log(err),
  68. });
  69. return res.send(BASE_TEMPLATE.replace("{{0}}", PHONE_FORM));
  70. }
  71. });
  72. app.post("/", async (req, res) => {
  73. //To access POST variable use req.body()methods.
  74. if ("phone" in req.body) {
  75. phone = req.body.phone;
  76. phoneCallback.resolve(phone);
  77. return res.send(BASE_TEMPLATE.replace("{{0}}", CODE_FORM));
  78. }
  79. if ("code" in req.body) {
  80. codeCallback.resolve(req.body.code);
  81. return res.send(BASE_TEMPLATE.replace("{{0}}", PASSWORD_FORM));
  82. }
  83. if ("password" in req.body) {
  84. passwordCallback.resolve(req.body.code);
  85. res.redirect("/");
  86. }
  87. console.log(req.body);
  88. });
  89. function callbackPromise() {
  90. // helper method for promises
  91. let resolve, reject;
  92. const promise = new Promise((res, rej) => {
  93. resolve = res;
  94. reject = rej;
  95. });
  96. return { promise, resolve, reject };
  97. }
  98. function formatMessage(message) {
  99. let content = (message.text || "(action message or media)").replace(
  100. "\n",
  101. "<br>"
  102. );
  103. return `<p><strong>${utils.getDisplayName(
  104. message.sender
  105. )}</strong>: ${content}<sub>${message.date}</sub></p>`;
  106. }
  107. const phoneCallback = callbackPromise();
  108. const codeCallback = callbackPromise();
  109. const passwordCallback = callbackPromise();
  110. // callbacks for code and password also
  111. // then inside your grammy code when use sends phone do the following
  112. // start the Express server
  113. app.listen(port, async () => {
  114. client.session.setDC(2, "149.154.167.40", 80);
  115. client.setParseMode("html");
  116. // Connect before fully starting the server
  117. await client.connect();
  118. console.log(`server started at http://localhost:${port}`);
  119. });