How to add bot to telegram
How to add bot to telegram
How to Add a Bot in Telegram
A feature that makes popular instant messaging app Telegram stand out is the option to use bots in group chats. Their purpose is to essentially enhance the Telegram experience through convenience and entertainment. If you’re an admin for a Supergroup and want to know how to add a bot, we’ve covered the steps on how-to in this article.
We’ll be adding bots to chat groups via different operating systems, learning more about their usefulness and how they differ from human members in chats. Plus, our FAQs include how to create your own unique bot.
How to Add Bots on Telegram?
A Telegram bot is a third-party application used to improve its functionality by performing specific functions, follow instructions, and interact with other members. The following sections are the steps for adding a bot to a Supergroup.
Add a Bot to a Supergroup Chat Using an iPhone
Add a Bot to a Supergroup Chat Using an Android
Add a Bot to a Supergroup Chat Using Mac
Add a Bot to a Supergroup Chat Using Windows 10
Bot Perks
Using bots in Telegram can be practical:
How Are Bots Different Than Humans?
The following are differences between human members and bots in Telegram:
BotFather
“BotFather is the one bot to rule them all.”
BotFather is the bot used to create new bots and manage existing ones via Telegram. To contact the BotFather, you can either search for him under username @Botfather or navigate to https://telegram.me/botfather to start a conversation. BotFather will introduce himself and a “Start” button will be available for you to talk back.
Additional FAQs
How to Remove Bots on Telegram?
To remove a Telegram bot from your conversation list via Android:
Note: Removing a bot will also remove the conversation.
1. Launch the Telegram app.
2. Press down and hold on to the bot’s name to display a menu at the bottom of the screen.
3. Select “Delete and stop.”
4. Click on “OK” to confirm.
1. Launch the Telegram app.
2. Locate the bot you wish to remove and swipe left on the conversation.
3. Click on the “Delete” icon from the set of icons that slide out from the right.
4. Select “Delete and Stop” from the option displayed at the bottom of the screen.
How to Add a Bot to a Telegram Group?
To add a bot to a chat group using an Android or iPhone device:
1. Launch the Telegram app.
2. At the bottom of the screen, click on the Contacts icon.
3. At the top of the screen, click on the search bar.
4. Type in the name of the bot you wish to add @[botname].
5. Click on the bot name to display it in the chat.
6. From the top-right hand corner of the chat window, select the bot’s profile image.
7. Locate and select the “Add to Group” option below the “Send Message” option to access a list of groups to add members to.
8. Select the group you wish to add the bot to.
9. Click on “Yes” to confirm.
To add a bot to a chat group using a Mac or PC:
1. Navigate to the Applications folder (Mac) or Windows menu (PC) to locate and launch the Telegram app.
2. In the search field, at the top left-hand corner of the screen, enter the name of the bot you wish to add.
3. Hit the return key for a list of bot search results matching your query.
4. Click on the bot you wish to add to the group, the bot will open and display on the right.
5. To bring up the bot’s profile, select the bot’s name from the top of the window.
6. Towards the top-right hand corner of the window, select the “Add to Group” option.
7. Select which Supergroup you want to add the bot to.
8. Click “OK” to confirm.
How to Create a New Telegram Bot?
1. First, start up a conversation with BotFather either by searching for him under the username @Botfather or by navigating to https://telegram.me/botfather.
2. Then enter and send the command “ /newbot. ”
3. BotFather will ask for a name and username. Provide a friendly name and unique username.
· BotFather will generate an authorization token.
4. Copy the token to your clipboard and navigate to your bot’s “Channels” section via the Azure portal then click on “Telegram.”
5. Paste the authorization token into the “Access Token” field then “Save.”
· Your bot is now created successfully; single, and ready to mingle with other Telegram members.
· Enable “Inline queries” so users can call your bot by entering its username and the query into any chat.
· Check out the Bot API manual to find out what you can teach your bot to do.
Telegram’s Little Virtual Assistants
AI-inspired bots in Telegram are used to enhance the messaging experience by essentially performing admin tasks, connecting people, and providing entertainment. Bots in messaging apps have become increasingly common and the option to use them is available via several popular apps.
Now that you know how to add a bot to a chat, create a bot, and other bot information; do you think the bot did a great job at enhancing your experience? How did the bot serve the group – and did it work as expected? Let us know what you think generally about the use of bots in messaging apps in the comments section below.
Боты: информация для разработчиков
Боты — специальные аккаунты в Telegram, созданные для того, чтобы автоматически обрабатывать и отправлять сообщения. Пользователи могут взаимодействовать с ботами при помощи сообщений, отправляемых через обычные или групповые чаты. Логика бота контролируется при помощи HTTPS запросов к нашему API для ботов.
Общие сведения
Что могут делать боты?
Вот несколько примеров использования ботов:
Как работают боты?
Как уже было сказано ранее, роботы — особые аккаунты, которые не требуют номера телефона при создании. По сути, эти аккаунты играют роль интерфейса к вашему сервису, который работает на удалённом сервере.
Самое интересное в роботах это то, что для их создания вам не нужно изучать низкоуровневые методы работы с MTProto и шифрованием — общение с роботом организовано при помощи обычного HTTPS интерфейса с упрощёнными методами Telegram API. Мы назвали его Bot API.
Рекомендуем также ознакомиться с подробным описанием Bot API.
Как создать бота?
Для этого есть. Бот. Просто напишите пользователю @BotFather и следуйте его инструкциям. Как только вы создали бота и получили свой ключ (токен) авторизации, переходите в раздел документации Bot API, чтобы начать настраивать вашего бота.
Чем бот отличается от обычного аккаунта?
Суперспособности
У роботов Telegram есть много уникальных возможностей — например, кастомизированные клавиатуры, дополнительные интерфейсы для команд по умолчанию, внешнее связывание и специальные режимы приватности для групп.
Инлайн-режим
Пользователи могут общаться с вашим ботом напрямую из поля ввода сообщения — из любого чата или группы. Для этого нужно всего лишь набрать имя пользователя вашего бота и запрос для поиска. Получив запрос, бот может возвратить какие-либо результаты. Как только пользователь нажмёт на один из них, он сразу же отправится в чат. Таким образом можно запрашивать контент от бота в чатах, группах или каналах.
С помощью ботов пользователи могут играть в HTML5-игры в группах или приватных чатах. Игровая платформа Telegram поможет составить таблицу рекордов и оповещать пользователей об изменении рейтинга.
Под капотом у игр — HTML5, поэтому вы можете создавать игры любой сложности. На данный момент командой Telegram созданы несколько демо-игр:
Клавиатуры
Одна из самых необычных возможностей Bot API — кастомизированные клавиатуры. При передаче сервером ответа есть возможность передать команду на отображение специальной клавиатуры с предустановленными вариантами ответа (см. ReplyKeyboardMarkup). Клиент Telegram, получив сообщение, отобразит пользователю вашу клавиатуру. Нажатие на клавишу сразу же отправит на сервер соответствующую команду. Таким образом можно значительно упростить взаимодействие робота с пользователем. На данный момент для отображения на клавише могут использоваться эмодзи и текст. Вот несколько примеров таких клавиатур:
За более подробной информацией обращайтесь к описанию метода sendMessage.
Команды
Команды представляют собой более гибкий способ общения с ботом. Рекомендуется следующий синтаксис:
Команда должна начинаться с символа косой черты «/» и не может быть длиннее 32 символов. Команды могут состоять из букв латинского алфавита, цифр и подчёркивания. Несколько примеров:
Сообщения, начинающиеся с косой черты, будут всегда доставляться боту (точно также, как и при ответе на его сообщения и на @упоминания бота в чате). Приложения Telegram будут:
Если в группе есть несколько ботов, вы можете дописать после команды имя бота, чтобы избежать коллизий в общих командах:
Это происходит автоматически, если вы выбираете команду из списка доступных.
Глобальные команды
Чтобы пользователям было проще работать с ботами, мы просим всех разработчиков реализовывать поддержку нескольких простых команд. В интерфейсе приложений Telegram будут ярлыки (быстрые ссылки) для этих команд.
При попытке начать общение с роботом, пользователь увидит кнопку СТАРТ. На странице профиля бота также будут доступны ссылки Помощь и Настройки.
Режим приватности
Ботов часто добавляют в группы, чтобы получать различную информацию — новости, уведомления и т.д. Однако, при добавлении бота вы наверняка спрашивали себя: «А что если этот маленький засранец пересылает всю групповую переписку куда-то “налево”?» Именно поэтому у роботов есть режимы приватности.
Робот с включенным режимом приватности не будет получать всех сообщений, а только сообщения, удовлетворяющие этим условиям:
Это хорошо со всех сторон: во первых, некоторые люди будут спать спокойно (в своих шапочках из фольги), не опасаясь, что их будут прослушивать. Во-вторых, режим приватности избавляет разработчиков от необходимости обрабатывать сотни ненужных сообщений из групповых чатов.
Мы рекомендуем отключать режим приватности только в случаях крайней необходимости. В подавляющем большинстве случаев, запроса принудительного ответа на сообщение бота будет достаточно.
Внешнее связывание
Боты имеют механизм внешнего связывания, которые позволяет передать дополнительные параметры при запуске. Например, для передачи авторизационного токена пользователя, чтобы соединить его аккаунт с каким-либо внешним сервисом.
Переход по ссылке с параметром start начнет чат с ботом, при этом в поле ввода текста будет отображаться кнопка СТАРТ. При переходе по ссылке с параметром startgroup пользователю будет предложено добавить бота в одну из доступных групп. Как только пользователь подтвердит своё действие (нажмёт на кнопку СТАРТ или выберет группу), бот получит сообщение следующего формата:
Пример реализации внешнего связывания
BotFather
BotFather — один бот, чтобы править всеми. При помощи него меняются настройки у существующих ботов и создаются новые.
Создание бота
Имя (name) будет отображаться в контактах и чатах.
Username — короткое имя на латинице, которое используется для упоминаний бота и в ссылках на профиль в telegram.me. Username должен состоять из букв латинского алфавита, подчёркиваний и цифр и быть длиной от 5 до 32 символов. Также имя пользователя обязательно должно заканчиваться на «bot», например: «tetris_bot» или «TetrisBot».
Создание токена
Настройки
Пожалуйста, имейте в виду, что для применения настроек на сервере, возможно, потребуется некоторое время.
Сайт про Telegram на русском (неофициальный).
Здесь собраны приложения на базе MTProto, переведена некоторая документация с официального сайта, а также работает Webogram.
How to Add a Telegram Bot to Telegram Group
By Joren Wouters • Updated on Apr 5, 2022
In this tutorial, I will explain how you can add a Telegram chatbot to your Telegram group and automatically reply to messages in your group.
I will show you:
P.S. In my Telegram Chatbots guide, I already explained how you can can create a chatbot (without using any code), so if you haven’t already seen that one, I highly recommend to read it 🙂
Table of Contents
Create a Telegram Group
As already mentioned in the beginning, I created my own Telegram chatbot which can reply to simple questions such as “Can I order a pizza”:
So the first step we need to do, is create our own Telegram group.
If you are on a desktop, just install Telegram, click on the Pen icon in the top-left corner and select New group:
Here, you need to select the members you want to add (probably some friends/colleagues of yours), give a name to the group (for example “Bot Test”) and click on Create:
Add Telegram Chatbot to the group
Now we’ve created our Telegram group and we need to add our chatbot.
So, you can just go to your Telegram chatbot (mine is called “Pizza-DF-Bot”) and click on the Top Bar:
Then, you need to click on “More” and select Add to Group:
And select the Telegram group you want to add the chatbot to:
Only reply if you mention the Telegram Chatbot
Once you’ve added your Telegram chatbot to your Telegram group, and you mention it, you will probably see that the chatbot doesn’t automatically respond:
This is because the chatbot is not an admin of the group.
So, you need to click on the top bar of your Telegram group:
Click on Edit:
And then choose for Administrators:
Click on Add admin:
Select your chatbot:
And then give it all the rights it needs:
When you’ve done this, and you will ask a question and mention the chatbot again, you will see that it is responding now:
Let Telegram Bot respond to all messages in the group
Now, the chatbot is only responding when you mention it.
But what if you want the chatbot to respond to all messages in the group?
Then, we need to have a talk with the BotFather.
In Telegram, you need to search for “BotFather” and start a conversation with him:
The BotFather immediately gives you a list of commands that you can use to change the settings of your chatbot:
Now, you need to type “/setprivacy”, which is a command we can use to change the privacy settings in Telegram groups.
Then, you can select which bot you want to change:
Then, you will see that the privacy settings are set to Enable (by default), which means the bot only replies to commands and mentions. Now, if you just type in “Disable” or click on the button, you can disable this setting:
And if you go back to your Telegram group and say something (without mentioning the bot), you will see that the chatbot automatically responds:
Now It’s Your Turn
And that’s how you add a Telegram chatbot to your Telegram group.
Now I have a question for you:
Do you already use Telegram Bots in your Groups? And if not, why not?
Let me know by leaving a comment below!
Want to generate leads and get more customers?
Get access to my new course: Lead Generation System.
A proven, step-by-step on generating leads and converting them into actual-paying customers.
The Lead Generation System is now available for only €49 and covered by a 30-Day Money-Back Guarantee.
Learn more about Telegram automation
Telegram Chatbots: The Ultimate Guide (2022)
Comments (31)
Hi,
Thanks for information it was very helpful. Please help me how I can add bots to telegram chennel.
Thanks
Hey Raphael! Currently, there is not a way to add a bot to a Telegram channel, other than manually coding it…
Hi,
How to add a bot to a public telegram channel by manually coding it?
Hey Prabhat! I personally don’t have any experience with manually coding this, so I honestly do not know. I would just try a Google search and maybe you can find anything!
Is there a way to create a bot and send messages from a group which you are not the owner to your own group?
No, that is not possible. The bot needs to be the admin of the group.
Hi,
Is this possible to filter chat messages from a telegram group and only get notifications when a certain word matches in the chat for the group?
Hey Vin! Yes, you can. In the second chapter of my Telegram Chatbots guide, I explain on how you can do this.
HI! I created a bot with Activechat but when I put it in the group he doesn’t respond to messages or words that should trigger him. He does it in private chat though. I’ve done everything you said in the video but that still does not work. Help!!
Hey Chloe! Good question! This probably is because of ActiveChat itself, they do not provide that functionality with their platform. If I were you, I should contact ActiveChat and ask whether you can do this with their platform.
Hi.
How can I add like and dislike on my subject as a comment
Hey Emmanuel! What do you mean with a like and dislike? And I think as a comment you mean the message someone sends in a Telegram group?
Almost same as Chloe above, no response in group but appears in the bot. Of course I’ve followed the steps. How to debug?
Hey Paul! This is because with ActiveChat you cannot use Telegram chatbots in groups, they don’t provide that functionality with their platform.
Confused. Isn’t that tutorial teach us use in telegram group?
I’m with you. i follow exactly as in the tutorial but the bot did not respond in the group chat but appears in the bot. is this something to do with setting or functionality? @Joren your tutorial seems to work tho. any insight will be appreciated.
Hey Sai! Did you use ActiveChat to create your chatbot? If that’s the case, you cannot add your Telegram bot to a group, because ActiveChat does not provide that functionality. If you want a chatbot builder that is able to do this, I would recommend using Xenioo.
I’ve added @language_translator_bot to a private and made it an admin so that it can reply when I mention it.
Now I want it to respond to all messages. But when I talk to the BotFather and /setprivacy, he tells me “You don’t have any bots yet. Use the /newbot command to create a new bot first.”
I don’t want to create a new bot, I just want the existing bot to respond within my group.
What to do?
When you go to the Botfather and type “/mybots”, what do you get?
Great post!! Thanks for sharing this with us. Keep up!
Thank you, Jonathan!
Hi, I’m struggling with some thing. I use telegram bot cooperating with home assistant. HA sends me via telegram bot some notifications. But it can also work opposite way. I can set up HA receiving message from telegram bot (for example “/something”) to trigger some action. The first trouble is that Google Assistant can’t send a message on telegram to telegram bot, because it’s not possible to set telegram number for the telegram bot as common telegram user. So I tried to use IFTTT and created New group and also New channel in telegram and added my bot to those places (set bot as administrator). Well, I can say to Google assistent something and IFTTT succesfully sends set up text to both places – telegram group and telegram chat group as well. But it’s not enought. If I forward message from “New group” (or “New chat”) manualy to the telegram bot than everything works perfekt. So I have to solve resending messages from “New groups” or “New chat” to my bot automatically. But I don’t know how. Can you help me? Thank’s a lot Jarda
Wow, seems like an awesome setup you’ve thought out. Could you tell me which chatbot builder you used to create the integration between Google Assistant and Telegram? And what is IFTTT?
Thanks for helping us Sir. I have a problem. How can i share my personal Bot so that everyone can receive bot messagges? I create a group with bot admin permission, but not worked for me.
Thanks in advance
Hey Alex! What is exactly not working? And with what chatbot builder did you create your Telegram chatbot?
Hi, thanks for the awesome article!
I’m using @BardeenBot from Bardeen. Would I need to disable privacy settings so it can see all messages in group?
How do I add my bot to a Telegram channel?
I’m using my bot to tell important news, but when I use sendMessage to the channel I’m receiving the following error:
In the Change Log they mention it’s not possible via the client to send a message to a channel, but then what is the other way to do that?
So, the question is, how to add my bot to the channel?
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Now all clients allow to do it, but it’s not pretty simple.
In any Telegram client:
This is how I’ve added a bot to my channel and set up notifications:
telegram.me/whateverIWantAndAvailable
the channel id will be @whateverIWantAndAvailable
Now set up your bot to send notifications by pusshing the messages here:
the message which bot will notify is: Test
I strongly suggest an urlencode of the message like
https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Testing%20if%20this%20works
in php you can use urlencode(«Test if this works»); in js you can encodeURIComponent(«Test if this works»);
I hope it helps
To add the bot to your channel:
click on the channel name:
click on admins:
click on Add Admin:
search for your bot like @your_bot_name, and click add:**
* In some platforms like mac native telegram client it may look like that you can add bot as a member, but at the end it won’t work.
** the bot doesn’t need to be in your contact list.
Are you using the right chat_id and including your bot’s token after «bot» in the address? (api.telegram.org/bottoken/sendMessage)
In order to use the sendMessage method we need to use the proper chat_id.
First things first let’s send the /start command to our bot via a Telegram client.
After sent this command let’s perform a getUpdates commands.
The response will be like the following
We are interested in the property result.message[0].chat.id, save this information elsewhere.
Where chat_id is the piece of information saved before.
Инструкция: Как создавать ботов в Telegram
24 июня разработчики Telegram открыли платформу для создания ботов. Новость кого-то обошла стороной Хабр, однако многие уже начали разрабатывать викторины. При этом мало где указаны хоть какие-то примеры работающих ботов.
Прежде всего, бот для Telegram — это по-прежнему приложение, запущенное на вашей стороне и осуществляющее запросы к Telegram Bot API. Причем API довольное простое — бот обращается на определенный URL с параметрами, а Telegram отвечает JSON объектом.
Рассмотрим API на примере создания тривиального бота:
1. Регистрация
Прежде чем начинать разработку, бота необходимо зарегистрировать и получить его уникальный id, являющийся одновременно и токеном. Для этого в Telegram существует специальный бот — @BotFather.
Пишем ему /start и получаем список всех его команд.
Первая и главная — /newbot — отправляем ему и бот просит придумать имя нашему новому боту. Единственное ограничение на имя — оно должно оканчиваться на «bot». В случае успеха BotFather возвращает токен бота и ссылку для быстрого добавления бота в контакты, иначе придется поломать голову над именем.
Для начала работы этого уже достаточно. Особо педантичные могут уже здесь присвоить боту аватар, описание и приветственное сообщение.
Не забудьте проверить полученный токен с помощью ссылки /getMe»>api.telegram.org/bot /getMe, говорят, не всегда работает с первого раза.
2. Программирование
Создавать бота буду на Python3, однако благодаря адекватности этого языка алгоритмы легко переносятся на любой другой.
Telegram позволяет не делать выгрузку сообщений вручную, а поставить webHook, и тогда они сами будут присылать каждое сообщение. Для Python, чтобы не заморачиваться с cgi и потоками, удобно использовать какой-нибудь реактор, поэтому я для реализации выбрал tornado.web. (для GAE удобно использовать связку Python2+Flask)
Здесь мы при запуске бота устанавливаем вебхук на наш адрес и отлавливаем сигнал выхода, чтобы вернуть поведение с ручной выгрузкой событий.
Приложение торнадо для обработки запросов принимает класс tornado.web.RequestHandler, в котором и будет логика бота.
Здесь CMD — словарь доступных команд, а send_reply — функция отправки ответа, которая на вход принимает уже сформированный объект Message.
Собственно, её код довольно прост:
Теперь, когда вся логика бота описана можно начать придумывать ему команды.
3. Команды
Перво-наперво, необходимо соблюсти соглашение Telegram и научить бота двум командам: /start и /help:
Структура message[‘from’] — это объект типа User, она предоставляет боту информацию как id пользователя, так и его имя. Для ответов же полезнее использовать message[‘chat’][‘id’] — в случае личного общения там будет User, а в случае чата — id чата. В противном случае можно получить ситуацию, когда пользователь пишет в чат, а бот отвечает в личку.
Команда /start без параметров предназначена для вывода информации о боте, а с параметрами — для идентификации. Полезно её использовать для действий, требующих авторизации.
После этого можно добавить какую-нибудь свою команду, например, /base64:
Для пользователей мобильного Telegram, будет полезно сказать @BotFather, какие команды принимает наш бот:
I: /setcommands
BotFather : Choose a bot to change the list of commands.
I: @******_bot
BotFather: OK. Send me a list of commands for your bot. Please use this format:
C таким описанием, если пользователь наберет /, Telegram услужливо покажет список всех доступных команд.
4. Свобода
Как можно было заметить, Telegram присылает сообщение целиком, а не разбитое, и ограничение на то, что команды начинаются со слеша — только для удобства мобильных пользователей. Благодаря этому можно научить бота немного говорить по-человечески.
UPD: Как верно подсказали, такое пройдет только при личном общении. В чатах боту доставляются только сообщения, начинающиеся с команды (/ ) (https://core.telegram.org/bots#privacy-mode)
Чтобы бот получал все сообщения в группах пишем @BotFather команду /setprivacy и выключаем приватность.
Для начала в Handler добавляем обработчик:
А потом в список команд добавляем псевдо-речь:
Здесь эмпирическая константа 75 относительно неплохо отражает вероятность того, что пользователь всё-таки хотел сказать. А format_map — удобна для одинакового описания строк как требующих подстановки, так и без нее. Теперь бот будет отвечать на приветствия и иногда даже обращаться по имени.
5. Не текст.
Боты, как и любой нормальный пользователь Telegram, могут не только писать сообщения, но и делиться картинками, музыкой, стикерами.
Для примера расширим словарь RESPONSES:
И будем отлавливать текст :
Видно, что теперь структура Message уже не содержит текст, поэтому необходимо модифицировать send_reply:
И все, теперь бот будет время от времени присылать стикер вместо времени:
6. Возможности
Благодаря удобству API и быстрому старту боты Telegram могут стать хорошей платформой для автоматизации своих действий, настройки уведомлений, создания викторин и task-based соревнований (CTF, DozoR и прочие).
Вспоминая статью про умный дом, могу сказать, что теперь извращений меньше, а работа прозрачнее.
7. Ограничения
К сожалению, на данный момент существует ограничение на использование webHook — он работает только по https и только с валидным сертификатом, что, например для меня пока критично за счет отсутствия поддержки сертифицирующими центрами динамических днс.
К счастью, Telegram также умеет работать и по ручному обновлению, поэтому не меняя кода можно создать еще одну службу Puller, которая будет выкачивать их и слать на локальный адрес:
P.S. По пункту 7 нашел удобное решение — размещение бота не у себя, а на heroku, благо все имена вида *.herokuapp.com защищены их собственным сертификатом.
UPD: Telegram улучшили Бот Апи, из-за чего, теперь не обязательно иметь отдельную функцию для отправки сообщений при установленном вебхуке, а в ответ на POST запрос можно отвечать тем же сформированным JSON с ответным сообщением, где одно из полей устанавливается как ч ‘method’: ‘sendMessage’ (или любой другой метод, используемый ботом).