View full version

A Telegram bot using the Python-Telegram-Bot library: Exchangerate-Bot

Hello everyone, this is my first post in Hive referring to programming things, so I have decided to share a simple code of a Telegram bot made in python using the python-telegram-bot library.

The bot allows in an easy and simple way through Telegram to know the current exchange between the different currencies used in the different countries through the use of an API.

If you want to know more about the API in question you can do it in this link exchangerate-api, where you must also request your keys to be able to use it and configure the requests in the bot.The key you request to access the API must be placed in the GET requests where it says "YourKey". And if you want to learn or deepen your knowledge about the library used in the construction of the bot, you can read the python-telegram-bot official documentation as well as the Telegram Bot API official documentation.



Code

import telegramfrom telegram import ReplyKeyboardMarkupfrom telegram.ext import (    Updater,    CommandHandler,    MessageHandler,    Filters,)import requestsimport osimport sys# request token from bot in environment variablesTOKEN = os.getenv('TELEGRAM_TOKEN')mode = os.getenv('MODE')# local access (developing)if mode == 'dev':    def run(updater):        updater.start_polling()        updater.idle()# access to heroku (production)elif mode == 'prod':    def run(updater):        PORT = int(os.environ.get('PORT', '8443'))        HEROKU_APP_NAME = os.environ.get('HEROKU_APP_NAME')        updater.start_webhook(listen='0.0.0.0', port=PORT, url_path=TOKEN)        updater.bot.set_webhook(f"https://{HEROKU_APP_NAME}.herokuapp.com/{TOKEN}")else:    print('without MODE')    sys.exit()# bot start functiondef start(update, context):    keyboard = [['USD', 'AED', 'AFN', 'ALL', 'AMD'],                ['ANG', 'AOA', 'ARS', 'AUD', 'AWG'],                ['AZN', 'BAM', 'BBD', 'BDT', 'BGN'],                ['BHD', 'BIF', 'BMD', 'BND', 'BOB'],                ['BRL', 'BSD', 'BTN', 'BWP', 'BYN'],                ['BZD', 'CAD', 'CDF', 'CHF', 'CLP'],                ['CNY', 'COP', 'CRC', 'CUC', 'CUP'],                ['CVE', 'CZK', 'DJF', 'DKK', 'DOP'],                ['DZD', 'EGP', 'ERN', 'ETB', 'EUR'],                ['FJD', 'FKP', 'FOK', 'GBP', 'GEL'],                ['GGP', 'GHS', 'GIP', 'GMD', 'GNF'],                ['GTQ', 'GYD', 'HKD', 'HNL', 'HRK'],                ['HTG', 'HUF', 'IDR', 'ILS', 'IMP'],                ['INR', 'IQD', 'IRR', 'ISK', 'JMD'],                ['JOD', 'JPY', 'KES', 'KGS', 'KHR'],                ['KID', 'KMF', 'KRW', 'KWD', 'KYD'],                ['KZT', 'LAK', 'LBP', 'LKR', 'LRD'],                ['LSL', 'LYD', 'MAD', 'MDL', 'MGA'],                ['MKD', 'MMK', 'MNT', 'MOP', 'MRU'],                ['MUR', 'MVR', 'MWK', 'MXN', 'MYR'],                ['MZN', 'NAD', 'NGN', 'NIO', 'NOK'],                ['NPR', 'NZD', 'OMR', 'PAB', 'PEN'],                ['PGK', 'PHP', 'PKR', 'PLN', 'PYG'],                ['QAR', 'RON', 'RSD', 'RUB', 'RWF'],                ['SAR', 'SBD', 'SCR', 'SDG', 'SEK'],                ['SGD', 'SHP', 'SLL', 'SOS', 'SRD'],                ['SSP', 'STN', 'SYP', 'SZL', 'THB'],                ['TJS', 'TMT', 'TND', 'TOP', 'TRY'],                ['TTD', 'TVD', 'TWD', 'TZS', 'UAH'],                ['UGX', 'UYU', 'UZS', 'VES', 'VND'],                ['VUV', 'WST', 'XAF', 'XCD', 'XDR'],                ['XOF', 'XPF', 'YER', 'ZAR', 'ZMW']]    markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True)    update.message.reply_text(        text='''        Hello! 👋🏻        What can this bot do?1️⃣-Select from the keyboard the currency you want to know the exchange value against other currencies. 2️⃣-You can also just type the currency indicator.3️⃣-Use the /exchange command followed by  the currency indicator. 4️⃣-Use /exchange_value followed by the two currencies you want to know their conversion rate.        ''',        reply_markup=markup    )# one-to-many exchange functiondef exchange(update, context):    try:        moneda = context.args[0]    except Exception as e:        print(type(e).__name__)        context.bot.send_message(            chat_id=update.effective_chat.id,            text="""                Please you don't use the command correctly,                you have to send followed by the command the                currency of which you want to know the                conversion rate.                Example:                /exchange usd                 """            )    else:        r = requests.get(f"https://v6.exchangerate-api.com/v6/YourKey/latest/{moneda}")        if r:            r_json = r.json()            text = ""            for key, value in r_json['conversion_rates'].items():                rate = f"{key} : {value}\n"                text += rate            update.message.reply_text(                text=text            )        else:            update.message.reply_text(                text="I don't recognize that currency, please send correctly the identifier of the currency in question."            )# one-to-one exchange functiondef exchange_value(update, context):    try:        currency = context.args[0].upper()        target_currency = context.args[1].upper()    except telegram.TelegramError as e:        print(e.message)        context.bot.send_message(            chat_id=update.effective_chat.id,            text="""                Please you don't use the command correctly,                you have to send followed by the command the                2 currencies of which you want to know the                conversion rate.                Example:                /exchange_value usd eur                > x USD = y EUR                """            )    else:        r = requests.get(f"https://v6.exchangerate-api.com/v6/YourKey/latest/{currency}")        if r:            r_json = r.json()            try:                rate = r_json['conversion_rates'][target_currency]            except Exception as e:                print(type(e).__name__)                update.message.reply_text(                    text="I don't recognize that currency, please send correctly the identifier of the currency in question."                )            else:                update.message.reply_text(                    text=f"1 {currency} = {rate} {target_currency}"                )        else:            update.message.reply_text(                text="I don't recognize that currency, please send correctly the identifier of the currency in question."            )# one-to-many exchange function for messagedef exchange_message(update, context):    currency = update.message.text    r = requests.get(f"https://v6.exchangerate-api.com/v6/YourKey/latest/{currency}")    if r:        r_json = r.json()        text = ""        for key, value in r_json['conversion_rates'].items():            rate = f"{key} : {value}\n"            text += rate        update.message.reply_text(            text=text        )    else:        update.message.reply_text(            text="I don't recognize that currency, please send correctly the identifier of the currency in question."        )def error_handler(update, context):    """    You can define here what to do with the errors raised by the bot.    In this case, we only print those errors to the logs.    """    try:        raise context.error    except telegram.TelegramError as e:        print(e.message)if __name__ == "__main__":    updater = Updater(token=TOKEN, use_context=True, workers=30)    # dispatcher configuration    dp = updater.dispatcher    dp.add_error_handler(error_handler)    command_handlers = {        'start': start,        'exchange': exchange,        'exchange_value': exchange_value    }    message_handlers = [        (Filters.text, exchange_message)    ]    # Init command handlers    for key, value in command_handlers.items():        dp.add_handler(CommandHandler(key, value, run_async=True))    # Init filters    for filter, callback in message_handlers:        dp.add_handler(MessageHandler(filter, callback, run_async=True))    # starting the bot    run(updater)



Examples in Telegram

This is how it would look in telegram once the bot is started, showing a message of what the bot can do and a keyboard to facilitate its use.

Here is one of the functions of the bot that would be the exchange ratio between different currencies, in this specific example it is shown between the USD and the rest of the currencies.

And this other image shows the other function of the bot that would be the exchange ratio between 2 specific currencies, which in this case would be between the USD and EUR.


I just hope this is helpful, if so, let me know in the comments as well as any questions you have about it. Likewise, the bot is quite simple and it is up to you if you want to improve it or do what your imagination allows. Thank you.🙂