How to stop my telegram bot replying to a message multiple times
You can use memcache in PHP or simply use a database.
Store the last update_id in memcache or your database. That way you know what message has already been answered. For the next time you can get the last update_id , increment it, and then get new message for response.
According to Telegram api document, You can pass last update_id +1 as offset param to getUpdates .
Not the answer you're looking for? Browse other questions tagged bots or ask your own question.
-
The Overflow Blog
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2022.8.30.42948
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How to stop the bot in Telegram in 3 seconds?
You have launched the bot in Telegram and left, but after a while, it started spamming you with messages. Sounds familiar?
If yes, then in this article, we will show you how to manage bot notifications properly and disable annoying bots forever.
Why is this happening?
A chatbot is pretty much like an application on your phone. We discussed this in our previous article.
In most cases, the notifications you receive from chatbots tell you about important updates. For example, your order completed or a character in the game has reached a new level.
But sometimes, developers fall for notifications, and they start being annoying. Refer to the “Configuring Notifications” section below to learn how to deal with this.
The second typical case is advertising messages. It is no secret that to maintain the bot and improve it further, the owners have to bear the costs of infrastructure, salaries, rent, etc. If the bot is free of charge, most of the developers resort to the adware model, when users receive ads from time to time. In most applications, this is a reasonable compromise. Still, sometimes developers go too far, and advertising begins to shower. Tips from the section “Ad Management” can help with this.
Finally, the third, and the most dangerous, case is hacking and sending false notifications to bot users. It occurs when the bot authorization token leaks and the attacker can take control of the communication channel with users (deface). The “Hacked Bot” chapter will tell you what to do if you encounter this case.
What to do?
Configuring notifications
Usually, the following steps are sufficient:
1. Go to the bot
2. Find the page with the notification settings (usually it is located in the Account or Settings section)
3. Select the notifications you want to receive and their frequency
If there is no such page, then do the following:
1. Find the bot in the chat list
2. Swipe it to the left to reveal the buttons as in the picture below:
3. Tap Mute to put notifications in silent mode
4. Go to the bot page in the Bots Club and leave a comment to the developers about a large number of messages
5. If the developer does not respond for a long time, try to find his contact in the bot description in Telegram and write to him personally
Be polite and constructive — often, the bot owners will be happy to help you and gain your trust.
Advertising management
Advertising can be annoying; it’s true. However, try to keep your cool and follow these steps:
1. Put the bot in muted mode, as described above
2. Leave a review with a low rating on the bot page in Bots Club. The dynamics of the app rating is a very significant factor for developers, and its sharp decrease will attract their attention
3. If the problem has been resolved, do not forget to thank and give a good rating
Hacked bot
If it seemed to you that the bot does not look the same as always, and someone hacked it, then here’s what you need to do:
1. Stop using the bot and put it in muted mode
2. Check the release notes and comments from other users on the bot page in the Bots Club — perhaps the developers just rolled out a major update
3. If suspicions persist, leave feedback to the developers — this way, you will warn other users and give a timely signal
Most importantly, remember that if a bot is defaced, it will not be able to receive more information from you than you provide yourself. It means, at the slightest suspicion, immediately stop using the bot and notify developers!
Damn the details, which planet?
If you nevertheless decide to end your relationship with the bot, stop it and remove it from your chat list, then here’s what you need to do:
1. Ask bot support to delete your account. If it’s operated from the EU, they are obliged to do so by law.
2. Find the bot in the chat list, swipe left and tap Delete
3. Choose Delete and Stop
After 5 seconds, the bot will be permanently stopped, and the chat history with it will be removed.
⚠️ However, it is crucial to understand that:
1. Message history can remain on servers of the bot developers
2. If you have not deleted your account via the support, then when you re-launch the bot, it may “recognize” you and, most probably, will continue from the point at which you stopped
[PHP] Создание простого Telegram-бота на простой библиотеке.
Здравствуйте, жители KotOFF.NET!
Как-то меня заинтересовала тема ботов на Телеграм и я удивился, насколько это можно просто сделать даже тому, кто мало разбирается в PHP. Соответственно, я принялся за это дело и готов поделится с вами этой вещью, чтобы вы точно знали, как такое делается.
Создание бота у BotFather.
Исток истоков — это регистрация бота у BotFather.
Ничего страшного нет. Просто следуйте простой инструкции.
1. Начинаем диалог с t.me/botfather.
2. Пишем /newbot, а следом имя боту.
3. Пишем айди боту. Заметьте, он должен обязательно оканчиваться на bot.
Всё. Регистрация окончена!
По желанию можно добавить аватарку боту через /setuserpic, описание через /setdescription или/и краткое «О боте» через /setabouttext. Совершенно сложного тут нет, поддерживается кириллица, кстати, как и у имени бота.
Главное «но» при создании бота на Телеграм.
Читаешь себе документацию, всё тебе ясно, пытаешься сам вебхук установить и видишь, что вебхуки-то проходят лишь с SSL-сертификатами! Что делать-то? Без паники. Тут есть два пути, или даже больше решению этого вопроса.
Можно взять да просто платить за хостинг, а к любому современному хостингу сейчас идёт SSL-сертификат. Но платить не хочется, верно?
Тогда можно подключиться к CloudFlare, если получится, однако я вам дам спойлер: мало где это получится. Так что и этот вариант не наш.
Значит, надо искать бесплатные хостинги с SSL, и таких я знаю два: darkhost.pro и 000webhost.com. Последний вариант я терпеть не могу — медленный, что жуть, хотя SSL есть, и домен тоже бесплатный… Но из-за медленности второго варианта буду использовать первый. И нет, это не реклама — я никак не управляю ни тем, ни тем хостом.
Настройка хостинга, его получение.
Делается всё элементарно и просто. Выполняйте понятную инструкцию, ничего не пропуская, желательно, и всё будет отлично.
1. Заходим на darkhost.pro, регистрируем себе аккаунт и подтверждаем его через подтверждение e-mail. Данные можно указывать не свои, но старайтесь вводить их похожими на правду, ладно? Чтобы вопросов никаких не было уже тут.
2. После регистрации и входа в кабинет личный, нажимаем на «Услуги»->«Заказать новую услугу», а на появившейся странице заказываем тариф «Light-MINI».
3. Выбираем «субдомен darkhost.pro» и вводим в свободное поле что угодно на латинице, после чего на следующей странцие просто жмём «Оформить», а далее уж жмём «Завершить заказ».
После этого вам на почту придут данные для входа в панель управления и FTP-сервер. 4. Нажимаем на «Услуги» и выбираем «Продукты/услуги». Там ищем свой сайт, что вы только что создали и нажимаете по нему. На открывшейся странице выбираем «Вход в панель управления» и ждём, пока нас перекинет и авторизирует в ISPmanager-е.
5. Слева есть панель. Там выбираем «SSL-сертификаты». В открывшейся странице нажимаем «Let’s Encrypt» и просто нажимаем далее.
6. Пока ставится сертификат Let’s Encrypt, который работает, кстати, три месяца, настроим PHP. Просто заходим в «WWW-домены», находим свой сайт там, двойным кликом открываем его (или нажимаем на «Изменить») и выбираем версию PHP, промотав ниже. Желательно ставить PHP или 7.0, или выше.
Если сайт ваш выдаёт ошибку после того, как поменяли версию PHP — подождите. Заработает само.
Вот и всё. Мы настроили хостинг для работы с ним.
А теперь как бота написать-то?!
Всё просто. Скачайте архив и просто перекиньте через FTP или на через ISPmanager файлы на ваш хостинг.
telelibon-master.zip
Нам же там надо файлик «tgLib.php» и именно его вкладывать в ваш основной файл бота.
А вот как загружать файлы через ISPmanager:(1 — перейти в Менеджер файлов; 2 — пройти по этому пути (последняя папка будет вашим доменом); 3 — нажать на закачать (далее надо будет просто выбрать файлы. также можно сделать папку через «Создать», если вам надо))
Разбор самого кода главного файла: bot.php.
А как вообще прикрепить вебхук-то к боту? Ты нам не сказал!
Да, я дико извиняюсь, что это пишу под конец, конечно, поста, но я просто хотел сперва показать, как это всё делается, чтобы вы определились, надо ли вам это.
А так, просто выполните запрос какой-то такой:
Удачного денька.
Пост подходит к концу. Если что — задавайте вопросы. Отвечу на них по возможности.
P. S. Если ответа нет довольно долго, значит либо не заметил, либо нет времени, но вероятен сценарий банальности ошибки вашей или вопроса.
Архив с библиотекой и исходным кодом:
telelibon-master.zip
Нео Метал
- 02.12.2019
- 15 738
- 17
- 10