0 / 0 / 0
Регистрация: 17.07.2022
Сообщений: 3
1

Telegramerror: 403: forbidden: bot was blocked by the user и бот рухнет

17.07.2022, 13:47. Показов 882. Ответов 4

Юзер заблокировал бота и теперь он рухнет с такими сообщениями в консоле
Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
TypeError: Cannot read properties of undefined (reading 'name')
      at C:\Users\sashuha\Desktop\botjs\bot.js:34:57
      at C:\Users\sashuha\Desktop\botjs\node_modules\telegraf\composer.js:143:56
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
      at async Promise.all (index 0)
 
Failed to process updates. TypeError: Cannot read properties of undefined (reading 'name')
    at C:\Users\sashuha\Desktop\botjs\bot.js:34:57
    at C:\Users\sashuha\Desktop\botjs\node_modules\telegraf\composer.js:143:56
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Promise.all (index 0)
C:\Users\sashuha\Desktop\botjs\node_modules\telegraf\core\network\client.js:281
          throw new TelegramError(data, { method, payload })
                ^
 
TelegramError: 403: Forbidden: bot was blocked by the user
    at C:\Users\sashuha\Desktop\botjs\node_modules\telegraf\core\network\client.js:281:17
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 403,
  response: {
    ok: false,
    error_code: 403,
    description: 'Forbidden: bot was blocked by the user'
  },
  description: 'Forbidden: bot was blocked by the user',
  parameters: {},
  on: {
    method: 'sendMessage',
    payload: {
      chat_id: 5315931205,
      text: 'Hello',
      reply_markup: {
        keyboard: [
          [ ' Отправить архив ', ' Профиль ' ],
          [ ' Контакты  ' ]
        ],
        resize_keyboard: true
      }
    }
  }
}
 
Node.js v18.6.0
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
17.07.2022, 13:47
Ответы с готовыми решениями:

Joomla 403 Forbidden Access is forbidden to the requested page
Добрый день. Начал учится устанавливать сайт. сразу к проблеме: первый рас установил джумлу,...

403 Forbidden
Здравствуйте. Сайт DDOSят уже второй день. Его либо не грузит либо выдает такую ошибку:...

403 Forbidden
Почему когда я открываю сайт пишет 403 Forbidden CMS-Joomla Хостинг-fre.1gb.ru

403 Forbidden
Установил bitnami wamp на windows 10. Сам wamp на C, а хосты на D. Виртуальный хост описан так: ...

4
Модератор
Эксперт JS
4957 / 3142 / 952
Регистрация: 07.09.2019
Сообщений: 4,945
17.07.2022, 14:00 2
Я раньше не сталкивался с тем, чтобы ошибка Telegramerror: 403 блокировала процесс выполнения кода, вызывая другие ошибки; покажите сам код бота, файл bot.js.
0
0 / 0 / 0
Регистрация: 17.07.2022
Сообщений: 3
17.07.2022, 15:58  [ТС] 3
Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
const config = require("./config");
const telegraf = require("telegraf");
const bot = new telegraf(config.token); // bot login
const Stage = require("telegraf/stage");
const request = require("request");
const stage = new Stage();
const path = require("path");
const fs = require("fs");
const fetch = require("node-fetch");
const Scene = require("telegraf/scenes/base");
const users = require("./users.json");
const session = require("telegraf/session");
const { send } = require("q");
let keyboard = [
  [" Отправить архив ", "*♂️ Профиль *♂️"],
  [" Контакты  "],
];
var callbackQiwi = require("node-qiwi-api").callbackApi;
var asyncQiwi = require("node-qiwi-api").asyncApi;
 
var callbackWallet = new callbackQiwi(config.qiwiToken);
var asyncWallet = new asyncQiwi(config.qiwiToken);
let moneyLogger = {};
 
try{bot.use(session());
bot.use(stage.middleware());
bot.start(startHandler);
bot.command(`setmoney`, async (ctx) => {
  let args = ctx.message.text.split(/ +/);
  if (!args[1] || !args[2]) return ctx.reply(`Не верно введена команда`)
  let user = args[1];
  let sum = args[2];
  ctx.reply(
    `✅ К балансу *пользователя:* [${users[Number(user)].name}](tg://user?id=${
      users[Number(user)].id
    }) добавлено *${sum} RUB*`,
    { parse_mode: "Markdown" }
  );
  users[Number(user)].balance = users[Number(user)].balance + Number(sum);
  bot.telegram.sendMessage(
    Number(user),
    ` ✅ К вашему *балансу* добавлено *${sum} RUB*`,
    { parse_mode: "Markdown" }
  );
  fs.writeFile("./users.json", JSON.stringify(users, null, 2), (err) => {
    if (err) console.log(err);
  });
});
bot.hears(" Отправить архив ", (ctx) => ctx.scene.enter("sendZip"));
bot.hears(` Контакты  `, async (ctx) => {
  ctx.reply(`Админы:\n\n@shelovesmypain`);
});
bot.hears(`*♂️ Профиль *♂️`, async (ctx) => {
  ctx.reply(
    ` Профиль *пользователя:* [${ctx.from.first_name}](tg://user?id=${
      ctx.from.id
    })\n\n Баланс: *${users[ctx.from.id].balance}* RUB`,
    {
      parse_mode: "Markdown",
      reply_markup: {
        inline_keyboard: [[{ text: " Вывести", callback_data: "getMoney" }]],
      },
    }
  );
});
bot.launch().then(() => {
  console.log("[BOT] Запущен");
});
const download = (url, path, callback) => {
  request.head(url, (err, res, body) => {
    request(url).pipe(fs.createWriteStream(path)).on("close", callback);
  });
};
const getMoneyByUser = new Scene("getMoneyByUser");
getMoneyByUser.enter((ctx) => {
  ctx.reply(` Введите сумму, которую хотите получить:`, {
    reply_markup: { keyboard: [[" Назад"]], resize_keyboard: true },
  });
});
getMoneyByUser.on("text", async (ctx) => {
  if (ctx.message.text == " Назад") {
    ctx.scene.leave();
    return ctx.reply(`◀️ Возвращаемся в меню`, {
      reply_markup: { keyboard: keyboard, resize_keyboard: true },
    });
  }
  if (users[ctx.from.id].balance < ctx.message.text)
    return ctx.reply(`У вас недостаточно денег`);
  moneyLogger[ctx.from.id] = { sum: ctx.message.text.toString(), req: "" };
  ctx.scene.enter("enterRequizits");
});
stage.register(getMoneyByUser);
const enterRequizits = new Scene("enterRequizits");
enterRequizits.enter((ctx) => {
  ctx.reply(
    ` Сумма: *${
      moneyLogger[ctx.from.id].sum
    } RUB*\n\nВведите реквизиты: *(номер)*, н.п.*+79261234567*`,
    { parse_mode: "Markdown" }
  );
});
enterRequizits.on("text", async (ctx) => {
  if (ctx.message.text == " Назад") {
    ctx.scene.leave();
    return ctx.reply(`◀️ Возвращаемся в меню`, {
      reply_markup: { keyboard: keyboard, resize_keyboard: true },
    });
  }
  if (!ctx.message.text.startsWith("+") || ctx.message.text.length < 12)
    return ctx.reply(`Не верно указаны реквизиты`);
  moneyLogger[ctx.from.id].req = ctx.message.text;
  ctx.reply(`Ожидайте выплаты!`, { reply_markup: { keyboard: keyboard } });
  ctx.scene.leave()
  users[ctx.from.id].balance =
    users[ctx.from.id].balance - Number(moneyLogger[ctx.from.id].sum);
  fs.writeFile("./users.json", JSON.stringify(users, null, 2), (err) => {
    if (err) console.log(err);
  });
  await callbackWallet.toWallet(
    {
      amount: moneyLogger[ctx.from.id].sum,
      comment: "test",
      account: ctx.message.text,
    },
    (err, data) => {
      if (err) {
        console.log(err);
      }
      console.log(data);
    }
  );
});
stage.register(enterRequizits);
const sendZip = new Scene("sendZip");
sendZip.enter((ctx) => {
  ctx.reply(` Отправьте архив`, {
    reply_markup: { keyboard: [[" Назад"]], resize_keyboard: true },
  });
});
sendZip.on("document", async (ctx) => {
  if (!ctx.message.document.file_name.includes(".zip"))
    return ctx.reply(`Отправьте архив!`);
  if (users[ctx.from.id].status == "wait")
    return ctx.reply(`Вы уже отправляли архив! Подождите`);
  let num = Math.floor(Math.random() * 999999);
  bot.telegram
    .sendDocument(config.chatID, ctx.message.document.file_id.toString(), {
      caption: `Пользователь: [${ctx.from.first_name}](tg://user?id=${ctx.from.id})\nНомер: *${num}*\nID: \`${ctx.from.id}\` `,
      parse_mode: "Markdown",
    })
    .then((msg) => {
      users[ctx.from.id].status = "wait";
      users[ctx.from.id].docID = msg.message_id;
      users[ctx.from.id].num = num;
      users[ctx.from.id].fileID = ctx.message.document.file_id.toString();
      fs.writeFile("./users.json", JSON.stringify(users, null, 2), (err) => {
        if (err) console.log(err);
      });
      bot.telegram
        .sendMessage(
          config.chatID,
          `Пользователь: [${ctx.from.first_name}](tg://user?id=${ctx.from.id})\nНомер: *${num}*\nID: ${ctx.from.id}`,
          {
            parse_mode: "Markdown",
            reply_markup: {
              inline_keyboard: [
                [{ text: "✅ Принять архив", callback_data: `acceptArchive` }],
                [
                  {
                    text: "❌ Отклонить архив",
                    callback_data: "refuseArchive",
                  },
                ],
              ],
            },
          }
        )
        .then((msg) => {
          users[ctx.from.id].msg = msg.message_id;
          fs.writeFile(
            "./users.json",
            JSON.stringify(users, null, 2),
            (err) => {
              if (err) console.log(err);
            }
          );
        });
    });
  ctx.reply(`Архив принят! Ожидайте! Номер архива: *#${num}*`, {
    parse_mode: "Markdown",
    reply_markup: { keyboard: keyboard, resize_keyboard: true },
  });
});
sendZip.hears(" Назад", async (ctx) => {
  ctx.reply(`◀️ Возвращаемся в меню`, {
    reply_markup: { keyboard: keyboard, resize_keyboard: true },
  });
});
stage.register(sendZip);
bot.on("callback_query", async (ctx) => {
  if (ctx.update.callback_query.data == "acceptArchive") {
    ctx.deleteMessage();
    for (var i in users) {
      if (
        users[i].msg == ctx.update.callback_query.message.message_id.toString()
      ) {
        bot.telegram.sendMessage(
          users[i].id,
          `✅ Ваш архив *#${users[i].num}* принят! Ожидайте начисления средств!`,
          { parse_mode: "Markdown" }
        );
        users[ctx.from.id].status = "start";
        ctx.reply(
          `✅ Архив *#${users[i].num}* был принят. Не забудьте выдать выплату пользователю\n\n\`/setmoney id sum\`!`,
          { parse_mode: "Markdown" }
        );
        bot.telegram.editMessageCaption(
          config.chatID,
          users[i].docID,
          null,
          `Пользователь: [${users[i].name}](tg://user?id=${users[i].id})\nНомер: ${users[i].num}\nID: ${users[i].id}\n\n✅ Архив принят`,
          { parse_mode: "Markdown", reply_markup: null }
        );
      }
    }
    fs.writeFile("./users.json", JSON.stringify(users, null, 2), (err) => {
      if (err) console.log(err);
    });
  } else if (ctx.update.callback_query.data == "refuseArchive") {
    ctx.deleteMessage();
    for (var i in users) {
      if (
        users[i].msg == ctx.update.callback_query.message.message_id.toString()
      ) {
        bot.telegram.sendMessage(
          users[i].id,
          `❌ Ваш архив *#${users[i].num}* не принят!`,
          { parse_mode: "Markdown" }
        );
        users[ctx.from.id].status = "start";
        ctx.reply(`❌ Архив *#${users[i].num}* не был принят.`, {
          parse_mode: "Markdown",
        });
        bot.telegram.editMessageCaption(
          config.chatID,
          users[i].docID,
          null,
          `Пользователь: [${users[i].name}](tg://user?id=${users[i].id})\nНомер: ${users[i].num}\nID: ${users[i].id}\n\n❌ Архив не принят`,
          { parse_mode: "Markdown", reply_markup: null }
        );
      }
    }
    fs.writeFile("./users.json", JSON.stringify(users, null, 2), (err) => {
      if (err) console.log(err);
    });
  } else if (ctx.update.callback_query.data == "getMoney") {
    ctx.deleteMessage();
    ctx.scene.enter("getMoneyByUser");
  }
});
async function startHandler(ctx) {
  if (!users[ctx.from.id]) {
    users[ctx.from.id] = {
      username: ctx.from.username,
      name: ctx.from.first_name,
      id: ctx.from.id,
      fileID: "",
      docID: 0,
      msg: 0,
      status: "start",
      num: 0,
      balance: 0,
    };
  }
  ctx.reply(`Hello`, {
    reply_markup: { keyboard: keyboard, resize_keyboard: true },
  });
  fs.writeFile("./users.json", JSON.stringify(users, null, 2), (err) => {
    if (err) console.log(err);
  });
}}catch{
  console.log("hello")
}
0
Модератор
Эксперт JS
4957 / 3142 / 952
Регистрация: 07.09.2019
Сообщений: 4,945
17.07.2022, 16:25 4
Не уверен, что ошибка связана с 403 ошибкой.
А если юзер введёт в команде setmoney такой id, которого нет ни у какого из существующих юзеров? Вам в любом случае нужно проверять ввод перед тем как начинать реагировать.
0
0 / 0 / 0
Регистрация: 17.07.2022
Сообщений: 3
17.07.2022, 16:26  [ТС] 5
да кстати в setmoney ввели не id и бот сломался,я не знаю как его починить
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
17.07.2022, 16:26
Помогаю со студенческими работами здесь

403 Forbidden
Несколько дней назад развернул сервер настроил виртуалхост и https, по инструкции которую бережно...

403 Forbidden
Понимаю, что тема обсуждалась 100500 раз, но порыскав по форумам я так и не нашла свою ошибку(...

403 Forbidden
Есть чат, залил я его на modulus.io, http://chat-46736.onmodulus.net/chat, но вылазит ошибка 403...

403 - forbidden
http://thetriumphofgood.us.ms/ вот сайт.что делать??я поставил имиджбордовый движок kusaba x все...

403 Forbidden
Всем доброго времени суток.У меня такая проблема.Захожу на сайт http://google-androids.ru и выдает...

403 Forbidden
Подскажите пожалуйста. Имеется сайт Когда я захожу на него все нормально, но как только ввожу...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru