# Telebot Basics

### Commands

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

e.g. `/start` or `/help`

We define a few commands.&#x20;

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

#### &#x20;**/start Command**

Sends a message when the command /start is issued

{% code overflow="wrap" %}

```python
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)
```

{% endcode %}

&#x20;Your Output will look something like this:&#x20;

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

#### &#x20;/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.

```python
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:**

![](/files/JstyATJxckLW28HxhrEg)

<pre class="language-python" data-overflow="wrap"><code class="lang-python">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

<strong>    # Assume 2 real solutions and calculate the roots 
</strong><strong>    # Can add conditional statements for imaginary solution etc.
</strong>    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)
    
</code></pre>

### 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

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

2. 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

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

3. Register Message Handler

* Processes all text messages
* When a user sends a text message, the 'handle\_message' function will be executed

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

4. Register Error Handler

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

```python
    app.add_error_handler(error)
```

5. 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

```python
    print('Polling...')
    asyncio.run(app.run_polling())
```

6. Putting it all together

Your code should look something like this:

```python
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())
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wiki.nushackers.org/orbital/telegram-bot/telebot-basics.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
