Skip to main content

Creating a simple Telegram Bot

Well first what is a bot?
     A bot is a piece of software that can execute commands, reply to messages, or perform routine tasks, as online searches, either automatically or with minimal human intervention

Now how to create one?
    Here i have created a bot that run in telegram and i will show you how to do

Steps in creating a Telegram Bot 
  • Create a account in telegram 
  • Search for @botfather ( a bot that will assist you in creating new bot )
  • Inside BotFather chat type /newbot and it will ask name for the bot and username for the bot once you completed above things successfully then botfather gives you Token id which is essential to create a bot
          
In this image you can able to find the token id strike out by red color

  • Well now we have everything we need , we can able to create a bot using python ( you can able to create in any language ) 
  • In command line
                    pip install python-telegram-bot
       Bot can get update from user using two methods
  •  Long Polling
  •  Webhooks
      Here we use long polling methods ( every x period of second we check whether we received any updates)

Here i have created a bot which download the file to the computer. you need to pass the url download command 

Eg: [  /download <<url>> ]

The concept is simple we get the url from the message and pass it to the wget ( command line downloader ) which can be done in python by

        command = "wget " + << download url >> + "&" ( '&' -> to run the program in background )
        os.system(command)

To implement the above concept we will pass the Token id to the updater and then add handler to the updater 

In our scenario the handler is "download" so we will create a dispatcher then set handler to the dispathcer and set a function that execute when we encounter this handler this can be done using

    updater = Updater("<<Your Bot Id>>")
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("<< handler name >>", Function to be executed ))
    
Add the above code to create a simple telegram app and the complete source code look alike

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Simple Telegram bot in which you can pass the url to the download the computer will download for you
# Reference : https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples
# My Blog : Thangaayyanar.blogspot.in

from telegram.ext import Updater, CommandHandler
import logging
import os

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)


def start(bot, update):
    update.message.reply_text('Hi! Use /download <download url> to download the file')


def initiate_download(bot, update, args, job_queue, chat_data):
    
    chat_id = update.message.chat_id
    
    try:
        
      command = "wget " + args[0] + "&"
        os.system(command)
      update.message.reply_text('Download process started')

    except (IndexError, ValueError):
        update.message.reply_text('Usage: /download <download url>')


def error(bot, update, error):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, error)


def main():
    """Run bot."""
    updater = Updater("<<Your Bot Id>>")

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", start))
    dp.add_handler(CommandHandler("download", initiate_download,
                                  pass_args=True,
                                  pass_job_queue=True,
                                  pass_chat_data=True))


    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()
 
 
 
Adding few error handling code  to the program to work better

Run the bot and pass the data

             /download < url >

the file will be download to the computer 


Cheers you have created a Bot







Comments

Popular posts from this blog

Ecosia

ECOSIA - A Green search engine “ Ecosia donates 80% profits to planting trees” Site: www.ecosia.org Lauched on 7 th December 2009 and created by Christian Kroll available in more than 26 language. It is located in Berlin, Germany.It is also called as CO2-neutral company.Ecosia has donated to different tree-planting programs. Until December 2010 Ecosia’s donations went to a program by WWF Germany that protected the Juruena-National park in the Amazonas. In order to make sure the protection was kept up, the program also drew up and financed plans with timber companies and the  local communities. According to B-labs, as of January 2015, "In donating 80 percent of its ad revenue, the search engine has raised over $1.5 million for rainforest protection since its founding in December 2009." According to Ecosia, by 2015, the search engine had almost 2.5 million active users, and searches through it had resulted in more than 2 million trees being planted.Since October 201...

codefest-ctf-18 writeup

Codefest is online CTF challenge conducted by Hackerrank on August 31 2018 6:00 PM IST to September 1 2018 12:00 PM IST. They have given dozens of challenges.  link: https://www.hackerrank.com/contests/codefest-ctf-18/challenges I manage to complete two challenges in this article i will explain how i solved the two  Typing Master Question If you think you have it in you, connect now to 34.216.132.109 9093 and prove your mettle. You will be presented with a simple typing task which is meant to check your typing speed. For example, Can you type 'Z' 10 times followed by 'u' 6 times, followed by the sum of their ASCII values? ZZZZZZZZZZuuuuuu207 Input Format Regarding input to the server - The question was designed keeping netcat in mind. Some users who are using other tools/language (eg, Python, PuTTY, TELNET) to connect to the server please note that they do not terminate the strings like netcat does. If you choose not to use netcat, t...

C program jackpot

/*Program to show sum of 10 elements of array & show the average.*/ #include<stdio.h> int main () { int a[ 10 ],i,sum = 0 ; float av; printf( "enter elements of an aaray: " ); for (i = 0 ;i < 10 ;i ++ ) scanf( "%d" , & a[i]); for (i = 0 ;i < 10 ;i ++ ) sum = sum + a[i]; printf( "sum=%d" ,sum); av = sum / 10 ; printf( "average=%.2f" ,av); return 0 ; } Output: enter elements of an array : 4 4 4 4 4 4 4 4 4 4 sum = 40 average = 4.00 /*Program to find the maximum no. in an array.*/ #include<stdio.h> void main () { int a[ 5 ],max,i; printf( "enter element for the array: " ); for (i = 0 ;i < 5 ;i ++ ) scanf( "%d" , & a[i]); max = a[ 0 ]; for (i = 1 ;i < 5 ;i ++ ) { if (max < a[i]) max = a[i]; } printf( "maximum no= %d" ,max); } Output: enter elements for array : 5 4 7 1 2 maximum no = 7 /*Swapp...