NUS Hackers Wiki
NUS Hackers Wiki
  • NUS Hackers Wiki
  • Hackerschool
    • Virtual Machines and Linux
    • Beginners' Guide to the Terminal
      • Introduction to the Terminal
      • Modern Shell Tools
      • Shell Scripting
      • Real World Scripting
      • Resources
    • Self-Hosting: Three Easy Pieces
      • 1. Setting up your server
      • 2. Running Services
      • 3. Monitoring your server
    • Vim
    • Introduction to Zig
      • Language Basics
      • Error Handling
      • Memory Management
      • Working with C
      • Exploring comptime
    • CI/CD with Github Actions
      • Background
      • Basics of Github Actions
        • Target workflow
        • Running unit tests
        • Linting code
        • Deploying to Github Pages
      • Advanced use cases
        • Pollers
        • Github script
        • Executing third-party scripts
        • Reusable workflows
      • Cookbook
    • Lightning Git
      • Git Concepts
      • Getting Started with Git
      • Making your first commit
      • Branching
      • Merge Conflicts
      • Integrating remote repositories
      • Collaborative Workflows
      • Commit Manipulation and Reflog
      • Interactive rebasing
      • filter-repo
  • Orbital
    • JavaScript
      • Browser Developer Tools
      • Getting Started
      • Datatypes
      • Operators and Operations
      • Loops and Conditions
      • Functions
      • Strings
      • Arrays
      • HTML
        • Getting Started
        • Tag Attributes
        • HTML Forms
        • Browser Inspector
      • CSS
        • Selectors
        • Colors in CSS
        • Measurements in CSS
        • The Box Model
        • Adding Styles - Part 1
        • Adding Styles - Part 2
      • Working with the DOM
        • Querying the DOM - Selectors
        • Querying the DOM - Element Attributes
        • Querying the DOM - Element Styles
        • Events with JS and HTML
        • Exercise: Click Counter
        • Editing the DOM
        • Fetch Requests
        • Exercise: The NUSMods API
    • React
      • Setup
      • State
    • React Native
      • Setup
      • Intro to JSX
      • Basic Syntax
      • Handling UI
      • Props
      • State Management
    • Git
      • Setup
      • Command Glossary
      • Fundamental Concepts
        • Getting Started
        • Integrating Remote Repositories
        • Branching
        • Merge Conflicts
      • Collaborative Workflows
        • Fork and PR Workflow
        • Branch and PR Workflow
      • Advanced Concepts
        • Ignoring Files
        • Commit Message Conventions
        • Github Collaborators
        • CI/CD with Github Actions
        • Advanced Git Commands
      • FAQ
    • Telegram Bot
      • Creating a TeleBot
      • API Calls
      • Telebot Basics
      • Integrating API's
    • Relational Database
      • Database Overview
      • Database Design
      • Entity Relationship Diagram
      • SQL Basics & PostgreSQL
    • TypeScript
      • Types and Interfaces
      • Utility Types
      • Typing Component Props, Events, and Hooks
      • Why You Should Avoid Using any (and What to Do Instead)
      • TypeScript Tricks You’ll Use All the Time in React
Powered by GitBook
On this page
  • Commands
  • Custom Commands
  • Initialising and Command Handling
Edit on GitHub
Export as PDF
  1. Orbital
  2. Telegram Bot

Telebot Basics

Commands

Commands in Telegram are messages that start with a slash "/" followed by the command name

e.g. /start or /help

We define a few commands.

  • These usually take in two arguments "update" and "context"

/start Command

Sends a message when the command /start is issued

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    user = update.effective_user
    await update.message.reply_text(text=f'Hello {user.mention_markdown_v2()}\!'
                                         f'\nEnter /help to see the list of '
                                         f'commands for this bot\.',
                                    parse_mode=ParseMode.MARKDOWN_V2)

Your Output will look something like this:

Hello 'Username'! #replaced by your username Enter /help to see the list of commands for this bot.

Code Explanation

  • user = update.effective_user extracts information about the user

  • parse_mode=ParseMode.MARKDOWN_V2 means your telebot will use Telegram's MarkdownV2 formatting for the message

  • user.mention_markdown_v2() is a function that ensures the user is mentioned and displayed correctly

/error Command

The error function is an error handler for your Telegram Bot. It is designed to log and print information about errors during the bot's operation.

async def error(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    print(f'Update {update} caused error {context.error}')
  • Update {update} : Includes information about the update (user input) that was processed when the error occurred

  • caused error {context.error} : Information about the error that was raised

Now, let us move on to something more "custom" for our telebot. Like a quadratic formula!

Custom Commands

Creating a quadratic formula command

The Formula:

import math

async def quadratic(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    
    # extract the message from the user input
    # e.g. /quadratic 1 2 3
    message = update.message.text
    
    # assign each number input to a string
    # e.g. a_string = 1, b_string = 2, c_string = 3
    _, a_string, b_string, c_string = message.split()
    
    # convert from a string to a float
    a = float(a_string)
    b = float(b_string)
    c = float(c_string)
    
    # Calculate the discriminant
    disc = b**2 - 4*a*c

    # Assume 2 real solutions and calculate the roots 
    # Can add conditional statements for imaginary solution etc.
    root1 = (-b + math.sqrt(disc)) / 2*a
    root2 = (-b - math.sqrt(disc)) / 2*a

    # Create the reply text
    reply = f"Your roots are {root1} and {root2}"
    
    update.message.reply_text(reply)
    

Initialising and Command Handling

  1. First, Initialise the Bot with your Token

  • We do this using the 'Application' class from the 'python-telegram-bot' library

  • The TOKEN is your unique bot token obtained from BotFather

if __name__ == '__main__':
    app = Application.builder().token(TOKEN).build()
  1. Register Command Handlers

  • When a user sends /start the 'start' function will be executed

  • When a user sends /help the 'help' function will be executed

  • When a user sends /quadratic the 'quadratic' function will be executed

    app.add_handler(CommandHandler('start', start))
    app.add_handler(CommandHandler('help', help))
    app.add_handler(CommandHandler('quadratic', quadratic))
  1. Register Message Handler

  • Processes all text messages

  • When a user sends a text message, the 'handle_message' function will be executed

    app.add_handler(MessageHandler(filters.TEXT, handle_message))
  1. Register Error Handler

  • Handle error's during a telebot's opertation. If an error occurs, the 'error' function will be executed

    app.add_error_handler(error)
  1. Now, Start Polling

  • Prints 'Polling...' to the console to indicate that the bot is starting

  • Polling is a method for the bot to continuously check for new updates from Telegram

    print('Polling...')
    asyncio.run(app.run_polling())
  1. Putting it all together

Your code should look something like this:

if __name__ == '__main__':
    app = Application.builder().token(TOKEN).build()

    app.add_handler(CommandHandler('start', start))
    app.add_handler(CommandHandler('help', help))
    app.add_handler(CommandHandler('quadratic', quadratic))

    app.add_handler(MessageHandler(filters.TEXT, handle_message))

    app.add_error_handler(error)

    print('Polling...')
    asyncio.run(app.run_polling())
PreviousAPI CallsNextIntegrating API's

Last updated 12 months ago