Skip to content

Instantly share code, notes, and snippets.

@nonchris
Created June 9, 2022 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nonchris/7c7e93889f1d19d4174a2819fa1befa9 to your computer and use it in GitHub Desktop.
Save nonchris/7c7e93889f1d19d4174a2819fa1befa9 to your computer and use it in GitHub Desktop.
A very simple inline telegram bot as starting point (it tells you the time if you ask)
# pip3 install python-telegram-bot~=13.12
import datetime as dt
import os
from telegram import Bot, Update, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import Updater, CallbackQueryHandler, CallbackContext, MessageHandler, Filters
# inline keyboard sent with messages
main_menu = InlineKeyboardMarkup([[InlineKeyboardButton('time', callback_data='time'),
InlineKeyboardButton('bar_cmd', callback_data='bar'),
]])
def handle_message(update: Update, context: CallbackContext):
""" Will be called if bot gets a simple message - replies with inline buttons and greeting"""
context.bot.send_message(chat_id=update.message.chat_id,
reply_markup=main_menu,
text="Hi, choose one of the options below")
def handle_callback(update: Update, context: CallbackContext):
""" Handle callbacks from inline buttons """
query: CallbackQuery = update.callback_query
query.answer("Your add could be placed here...")
key = query.data
if key == "time":
# answer query with current time, send same keyboard again
query.edit_message_text(f"It's {dt.datetime.now().strftime('%Y/%m/%d %H:%M:%S')}", reply_markup=main_menu)
if __name__ == '__main__':
API_Key = os.environ["API_KEY"]
updater = Updater(API_Key, use_context=True)
dispatcher = updater.dispatcher
bot = Bot(token=API_Key)
# add on message listener
dispatcher.add_handler(MessageHandler(Filters.text & (~Filters.command), handle_message))
# responsible for all inline commands
dispatcher.add_handler(CallbackQueryHandler(handle_callback))
# start bot
updater.start_polling()
updater.idle()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment