~jshsj/telegram_bot_unitconversion

ref: ea2098e385de152ae2c5923226fab72e0ba215ec telegram_bot_unitconversion/bot.py -rw-r--r-- 1.4 KiB
ea2098e3 — JSH initial commit 1 year, 11 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging

import pint

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

ureg = pint.UnitRegistry()
Q_ = ureg.Quantity

TOKEN = "YOUR TELEGRAM BOT TOKEN"

def help(bot, update):
    bot.send_message(
        chat_id=update.message.chat_id,
        text=f"""
        Let me help you with unit conversions.

To convert, please type <quantity unit> to <unit>.
Ex.: 1 cup to ml
        """,
    )


def convert(bot, update):
    user_input = update.message.text
    try:
        try:
            src, dst = user_input.split(" to ")
        except ValueError:
            bot.send_message(
                chat_id=update.message.chat_id,
                text="I can only convert units into one another. If you need a friend, please go somewhere else. Or try /help",
            )
            return
        answer = f"{Q_(src).to(dst)}"
        bot.send_message(chat_id=update.message.chat_id, text=answer)
    except pint.errors.DimensionalityError:
        bot.send_message(
            chat_id=update.message.chat_id,
            text="These units don't make sense together.",
        )


updater = Updater(TOKEN)
help_handler = CommandHandler("help", help)
updater.dispatcher.add_handler(help_handler)
updater.dispatcher.add_handler(MessageHandler(Filters.text, convert))

updater.start_polling()
updater.idle()