Unit 12.4A · Term 4

APIs & Configuration

To build a chatbot, your code needs to talk to a messaging platform (like Telegram) using an API (Application Programming Interface). This requires setting up an account, getting a secret API Token, and choosing a connection method.

Learning Objectives

  • 12.6.4.3 Configure the chat bot API
  • 12.6.4.4 Connect the development environment to the API

Lesson Presentation

12.4A-api-configuration.pdf · Slides for classroom use

Conceptual Anchor

The API Token Key

Think of the messaging platform as a secure building. Your bot is a delivery person. To enter the building and deliver messages, the bot needs a unique access badge (API Token). If you lose this badge, anyone can pretend to be your bot!

Rules & Theory

Obtaining a Token (Telegram Example)

  1. Open Telegram and search for @BotFather.
  2. Send the command /newbot.
  3. Follow instructions to name your bot and give it a username.
  4. BotFather will give you a Token (e.g., 123456:ABC-DefGhi...).
  5. Save this securely! Do not share it.

Connection Methods

Method How it Works Best For
Polling Your code constantly asks server: "Any new messages? ... Any new messages?" Development, simple bots used by few people.
Webhook Server tells your code: "Hey, here is a new message!" (Requires a public web server). Production, bots with millions of users.

Worked Examples

We will use the telebot library (pyTelegramBotAPI) for simplicity. Install it with: pip install pyTelegramBotAPI.

1 Basic Connection (Echo Bot)

import telebot # 1. Configuration API_TOKEN = 'YOUR_TOKEN_HERE' bot = telebot.TeleBot(API_TOKEN) # 2. Define Command Handler @bot.message_handler(commands=['start', 'help']) def send_welcome(message): bot.reply_to(message, "Hello! I am a bot.") # 3. Define Text Handler (Echo) @bot.message_handler(func=lambda message: True) def echo_all(message): # Reply with the same text bot.reply_to(message, message.text) # 4. Start Polling (Infinite Loop) print("Bot is running...") bot.infinity_polling()

2 Secure Configuration (Environment Variables)

Never hardcode tokens in your code! Use a .env file.

# .env file content: # BOT_TOKEN=123456:ABC-DefGhi... import telebot import os from dotenv import load_dotenv # Load variables from .env load_dotenv() token = os.getenv('BOT_TOKEN') if not token: print("Error: BOT_TOKEN not found!") exit() bot = telebot.TeleBot(token)

Common Pitfalls

Token Leaks

If you upload your code to GitHub with the token inside, scanners will find it and hackers will use your bot for spam. Always use environment variables or separate config files ignored by Git.

Polling Conflict

You cannot run two instances of the same bot script at once using polling. Detailed error: Conflict: terminated by other getUpdates request.

Tasks

Apply

Create a new bot with BotFather, get the token, and write a script that replies "Pong!" when you send "Ping".

Apply

Modify the echo bot to reply in ALL CAPS (use message.text.upper()).

Analyze

Research: Why is 'Polling' bad for battery life on mobile devices? (Hint: imagine checking your mailbox update every second).

Self-Check Quiz

Q1: Which bot gives you the API Token in Telegram?

@BotFather

Q2: What function starts the bot loop in telebot?

bot.infinity_polling() (or bot.polling())

Q3: Why should you not hardcode your token?

Security risk. If code is shared, anyone can control your bot.