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.
import telegram
from telegram import ReplyKeyboardMarkup
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
)
import requests
import os
import sys
# request token from bot in environment variables
TOKEN = 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 function
def 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 function
def 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 function
def 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 message
def 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)