Giter Club home page Giter Club logo

python-telegram-bot-calendar's Introduction

python-telegram-bot-calendar

PyPI version CodeFactor cock

Very simple inline calendar for your bot.

Getting Started

This library is tested on Python 3.6 and 3.7.

Installation

pip install python-telegram-bot-calendar

Usage

There is one main class - DetailedTelegramCalendar that can be used as follows. This is the example for pyTelegramBotAPI library. Other libraries are also supported.

from telegram_bot_calendar import DetailedTelegramCalendar, LSTEP

...
@bot.message_handler(commands=['start'])
def start(m):
    calendar, step = DetailedTelegramCalendar().build()
    bot.send_message(m.chat.id,
                     f"Select {LSTEP[step]}",
                     reply_markup=calendar)


@bot.callback_query_handler(func=DetailedTelegramCalendar.func())
def cal(c):
    result, key, step = DetailedTelegramCalendar().process(c.data)
    if not result and key:
        bot.edit_message_text(f"Select {LSTEP[step]}",
                              c.message.chat.id,
                              c.message.message_id,
                              reply_markup=key)
    elif result:
        bot.edit_message_text(f"You selected {result}",
                              c.message.chat.id,
                              c.message.message_id)

In start handler the calendar is created. Several arguments can be passed:

  • calendar_id - small integer or string, used for calendar identification. It used when you need several different calendars (default - 0)
  • current_date - datetime.date object, initial date value (default - today date)
  • additional_buttons - 1D list of buttons that will be added to the bottom of the calendar
  • locale - either en, ru, or eo, can be added more
  • min_date and max_date - both are used as min and max values for the calendar

As you can see, special function that is provided should be passed to callback query handler. It will automatically work. The function takes only one argument - calendar_id that is 0 by default.

In the body of the handler function you need to call process function on callback data. WARNING! You need to create the calendar object again if it was not saved before.

The function process return tuple of size 3 - result, keyboard, step.

  • result - datetime.date object if user finished selecting. Otherwise None
  • keyboard - inline keyboard markup if the result is not ready. Otherwise None
  • step - YEAR, MONTH, or DAY if not ready. None is also possible if there is no change in keyboard.

Advanced use

Several calendars

You can create as many calendars as you want. However, in order to handle them properly set different calendar_id's when you want to distinguish them. Take a look at examples.

Date ranges

In the class constructor min_date and max_date - both are used as min and max values for the calendar. If you add them, the calendar will not show undesired dates. Example: 3

Custom style

You can also write your own code. One of the examples is redefining the steps order.

In the package you can find WMonthTelegramCalendar and WYearTelegramCalendar that start from day and month selecting, not from year.

You can also redefine style parameters. Example:

class MyStyleCalendar(DetailedTelegramCalendar):
    # previous and next buttons style. they are emoji now!
    prev_button = "⬅️"
    next_button = "➡️"
    # you do not want empty cells when month and year are being selected
    empty_month_button = ""
    empty_year_button = ""

You will get:

4

Custom Translation

your_translation_months = list('abcdefghijkl')
your_translation_days_of_week = list('yourtra')

class MyTranslationCalendar(DetailedTelegramCalendar):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.days_of_week['yourtransl'] = your_translation_days_of_week
        self.months['yourtransl'] = your_translation_months

5

Examples

Contributing

Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are greatly appreciated.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/yourFeature)
  3. Commit your Changes (git commit -m 'Add some yourFeature')
  4. Push to the Branch (git push origin feature/yourFeature)
  5. Open a Pull Request

Authors

License

This project is licensed under the MIT License - see the LICENSE file for details

python-telegram-bot-calendar's People

Contributors

artembakhanov avatar sudormrfbin avatar tarasrudnyk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

python-telegram-bot-calendar's Issues

My callback_data through calendar

Возможно ли пробрасывать свои параметры через колбэки календаря? Вижу что из коробки нельзя, быстро вкрутить не получилось, может есть идеи как ничего не сломав это сделать?
Смысл в том, чтобы имея цепочку выборов передать предыдущие выборы через календарь, хотя бы в виде строки

Спасибо за труд!

Data extraction

Hello! A very good calendar. But I have a problem with extracting the date. Can you tell me how to extract the date for further use?

Customize calendar

Hi!

Is it possible to specify the initial step as an argument to DetailedTelegramCalendar?

Is it possible to disable the transition to selecting the month and year?

I need to display only the days of the month, without the ability to select the month and year.

Currently, I specified first_step = DAY in the DetailedTelegramCalendar class (detailed.py), but I couldn’t figure out how to succinctly disable the transition to month and year.

You can, of course, track m and y in c.data, but it seems that this is not quite the right solution.

Time select

Thanks for the calendar!

It would be cool to have an opportunity to add one more STEP with custom range of time. Like every 30 or 15 minutes to pick exact time.
So output will be: Selected date: 2022-15-10 22:15.

And the buttons on Time level:
22:00
22:15
22:30....etc.

Date ranges should be exclusive

The method _valid_date from class TelegramCalendar checks if the date is included in a given range.
It includes the last date in a range. It is popular to have exclusive ranges in Python.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.