This is the simplest telegram bot that answers with the phrase you sent him. The Chat Bot is a component of a Smart Home. We will therefore execute this code on our home Raspberry Pi. The code of this bot can be modified for your projects, for example, such as Internet radio. First, find the @BotFather on Telegram and get the token to access the HTTP API for your bot from it by following the instructions. The best way is to put the bot code in a separate directory using the Python virtual environment.
install python virtual environment
sudo pip3 install virtualenv
mkdir /home/pi/bot && cd /home/pi/bot
python3 –m venv env
activate the virtual environment
source env/bin/activate
install telegram bot library
pip install python-telegram-bot
create a file with bot settings
touch ./settins.py
write to the file this line
TELEGRAM_API_KEY = <your token to access the HTTP API>
Full echo-bot code is under the spoiler. Write cod to the file echo-bot.py .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import settings from telegram.ext import * from telegram import * def start(update, context): update.message.reply_text('you chat_id is {}. Remember it!!!'.format(update.message.chat_id)) update.message.reply_text("I am the simplest echo bot. Write me something.") def echo(update, context): update.message.reply_text(update.message.text) def main(): updater = Updater(settings.TELEGRAM_API_KEY, use_context=True) dp = updater.dispatcher dp.add_handler(CommandHandler("start", start)) dp.add_handler(MessageHandler(Filters.text, echo)) # Start the Bot updater.start_polling() updater.idle() if __name__ == '__main__': main() |
run echo bot
python ./echo-bot.py

Remember your chat_id.
This code will be the basis for creating our other bots, which I will describe in this section.