Automação
12 min leitura
15 MAR 2026
Como criar um bot para Telegram com Python
Crie um bot funcional para Telegram do zero com python-telegram-bot. Do token até o deploy.
Por que criar um bot para Telegram?
Bots do Telegram podem responder mensagens, enviar notificações, criar enquetes, buscar informações e automatizar praticamente qualquer coisa. E o melhor: com Python, você faz isso em poucas linhas.
Preparação
1. Criar o bot no Telegram
Abra o Telegram e converse com o @BotFather:
- Envie
/newbot - Escolha um nome (ex: "Meu Bot Python")
- Escolha um username (deve terminar em
bot, ex:meu_python_bot) - O BotFather vai te dar um token — guarde-o com segurança
2. Instalar a biblioteca
pip install python-telegram-bot
Seu primeiro bot
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
TOKEN = "SEU_TOKEN_AQUI"
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Ola! Eu sou um bot feito com Python!")
app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
print("Bot rodando...")
app.run_polling()
Execute o script e envie /start para o seu bot no Telegram. Ele vai responder!
Respondendo a mensagens de texto
from telegram import Update
from telegram.ext import Application, MessageHandler, filters, ContextTypes
TOKEN = "SEU_TOKEN_AQUI"
async def responder(update: Update, context: ContextTypes.DEFAULT_TYPE):
texto = update.message.text.lower()
if "oi" in texto or "ola" in texto:
await update.message.reply_text("Oi! Como posso ajudar?")
elif "horas" in texto:
from datetime import datetime
agora = datetime.now().strftime("%H:%M")
await update.message.reply_text(f"Agora sao {agora}")
else:
await update.message.reply_text("Nao entendi. Tente perguntar as horas!")
app = Application.builder().token(TOKEN).build()
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, responder))
app.run_polling()
Comandos personalizados
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
import random
TOKEN = "SEU_TOKEN_AQUI"
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"Comandos disponiveis:\n"
"/moeda - Cara ou coroa\n"
"/dado - Rola um dado\n"
"/frase - Frase motivacional"
)
async def moeda(update: Update, context: ContextTypes.DEFAULT_TYPE):
resultado = random.choice(["Cara!", "Coroa!"])
await update.message.reply_text(resultado)
async def dado(update: Update, context: ContextTypes.DEFAULT_TYPE):
numero = random.randint(1, 6)
await update.message.reply_text(f"Voce tirou: {numero}")
async def frase(update: Update, context: ContextTypes.DEFAULT_TYPE):
frases = [
"A melhor hora para comecar foi ontem. A segunda melhor e agora.",
"Codigo ruim que funciona > codigo perfeito que nao existe.",
"Todo expert ja foi iniciante.",
]
await update.message.reply_text(random.choice(frases))
app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("moeda", moeda))
app.add_handler(CommandHandler("dado", dado))
app.add_handler(CommandHandler("frase", frase))
app.run_polling()
Recebendo argumentos nos comandos
async def saudacao(update: Update, context: ContextTypes.DEFAULT_TYPE):
if context.args:
nome = " ".join(context.args)
await update.message.reply_text(f"Ola, {nome}! Bem-vindo!")
else:
await update.message.reply_text("Use: /oi SeuNome")
app.add_handler(CommandHandler("oi", saudacao))
O usuário digita /oi Maria e o bot responde "Olá, Maria! Bem-vindo!".
Botões inline
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes
TOKEN = "SEU_TOKEN_AQUI"
async def menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
teclado = [
[InlineKeyboardButton("Python", callback_data="python")],
[InlineKeyboardButton("Flask", callback_data="flask")],
[InlineKeyboardButton("Django", callback_data="django")],
]
markup = InlineKeyboardMarkup(teclado)
await update.message.reply_text("Escolha um tema:", reply_markup=markup)
async def botao_clicado(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer()
respostas = {
"python": "Python e otimo para iniciantes!",
"flask": "Flask e perfeito para sites pequenos e APIs.",
"django": "Django e ideal para projetos grandes.",
}
await query.edit_message_text(respostas.get(query.data, "Opcao desconhecida"))
app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler("menu", menu))
app.add_handler(CallbackQueryHandler(botao_clicado))
app.run_polling()
Enviando imagens e documentos
async def foto(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_photo(
photo="https://picsum.photos/400/300",
caption="Uma imagem aleatoria para voce!"
)
async def documento(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_document(
document=open("relatorio.pdf", "rb"),
caption="Aqui esta o relatorio!"
)
Protegendo o token
Nunca coloque o token direto no código. Use variáveis de ambiente:
import os
TOKEN = os.environ["TELEGRAM_TOKEN"]
E defina antes de executar:
export TELEGRAM_TOKEN="seu_token_aqui"
python bot.py
Exemplo completo: bot de consulta de CEP
import os
import requests
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
TOKEN = os.environ["TELEGRAM_TOKEN"]
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"Consulte qualquer CEP!\n"
"Use: /cep 01001000"
)
async def cep(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not context.args:
await update.message.reply_text("Use: /cep 01001000")
return
numero = context.args[0].replace("-", "")
try:
r = requests.get(f"https://viacep.com.br/ws/{numero}/json/", timeout=10)
dados = r.json()
if "erro" in dados:
await update.message.reply_text("CEP nao encontrado.")
return
msg = (
f"Logradouro: {dados.get('logradouro', '-')}\n"
f"Bairro: {dados.get('bairro', '-')}\n"
f"Cidade: {dados.get('localidade', '-')}\n"
f"Estado: {dados.get('uf', '-')}"
)
await update.message.reply_text(msg)
except requests.RequestException:
await update.message.reply_text("Erro ao consultar o CEP.")
app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("cep", cep))
print("Bot rodando...")
app.run_polling()
Resumo
| Recurso | Como usar |
|---|---|
| Comando | CommandHandler("nome", funcao) |
| Mensagem de texto | MessageHandler(filters.TEXT, funcao) |
| Botões inline | InlineKeyboardButton + CallbackQueryHandler |
| Argumentos | context.args |
| Enviar foto | reply_photo(photo=url) |
| Enviar arquivo | reply_document(document=file) |
Com Python e a API do Telegram, você pode criar bots que automatizam desde consultas simples até fluxos completos de atendimento. O limite é a sua criatividade.