Python telegram bot pattern

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A design pattern for python Telegram Bots with a clean structure and middlewares

lucaoflaif/telegram-bot-design-pattern

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Telegram Bot design pattern

Are you interested in a clean telegram bot’s structure? This pattern allows you to organize all your function, db connections, models, env files in a pretty and organised way.

This pattern uses the fabolous pyTelegramBotAPI library as its message handler.

You need pyTelegramBotAPI, python-dotenv installed on your computer, as specified in the requirements.txt file.

git clone https://github.com/lucaoflaif/telegram-bot-design-pattern

Then install the necessary dependencies using pip command-line tool:

cd telegram-bot-design-pattern [sudo] pip install -r requirements.txt

And copy the .env.sample file to .env to fill it with the needed data:

Читайте также:  Cast from string to boolean java

Obviously, the pattern will handle the Bot function’s, simply, all your functions must be saved in the functions folder, each function will be a class in a python file that must start with one or more underscore symbol. Let’s open the Example function file.

class ExampleReply(object): """This function reply to every new incoming message""" def __init__(self, env, bot, db): # self.env = env useless here self.bot = bot # self.db = db useless here @staticmethod def info(): """This method returns the info for function's routing, the first string could be 'message', 'inline_query' or 'callback_query'. the second element is a dict with parameters that'll be passed through the handler (in our case this dict is like commands=['example',]) """ return ("message", "commands": ["example",]>) @classmethod def init(cls, env, bot, db): """This method returns the function passed to the handler :param env, through this param you can access the environment variables :param bot is an istance of the Bot class """ istance = cls(env, bot, db) return istance.main def main(self, message): """This is the function's starting point. :param message, it's the incoming message object """ self.bot.reply_to(message, "It works!")

as you can see the code is well commented:

__init__() : to the constructor function the core mechanism will pass:

env bot db
The object thanks to wich you’ll be able to access your .env file The Telegram Bot object instance (See the pyTelegramBotAPI doc’s ‘TeleBot’ section) Te object that will allow you to use your database connection object

info(): here you can specify all the info allowing the Bot instance to handle your message. I.E. the statement:

return ("message", "commands": ["example",]>)

let the bot trigger the current function through the /example command, in fact it’s perfectly equals to

@bot.message_handler(commands=['example',])

See the pyTelegramBotAPI doc’s ‘a simple echo bot’ section.

Читайте также:  Php security file permissions

init(): nothing to see or modify here, it returns to the core mechanism the main function.

main(): your function’s logic lies here, you can access the Bot methods through the self.bot local variable, and the incoming message object through the message param.

Once your function class is ready, import it in the function/__init__.py and add its name in the __all__ array:

# functions/__init__.py file from ._example_function import ExampleReply __all__ = ['ExampleReply',]

«Okay, now, for every message, I’d want to display the text of the message in my terminal, how can I implement this in my function?»

Simply, don’t, God gave us Middlewares. A middleware is executed before every message. Let’s see a middleware structure opening the middlewares/_example_middleware.py file. (Like functions, every middleware file must start with one or more underscore symbol.)

class ExampleMiddleware: """Middleware Example""" def __init__(self, message): self.message = message @classmethod def init(cls, message): istance = cls(message) return istance.main(message) def main(self, message): # starting point: # param message: telebot.types.Message object # this function must return the message print("Message %(msg_text)s seen by the %(class_name)s middleware!" % (< 'msg_text': message.text, 'class_name': self.__class__.__name__ >)) return message

init: we initialize our message object as a class variable.

init(): nothing to see here, this method return our middleware to the core mechanism.

main(): your middleware’s logic lies here. the main method must always return the message object

So now, if we want to display, for each request, the text of the message, our middleware will simply contain:

. def main(self, message): # starting point: # param message: telebot.types.Message object # this function must return the message print (message.text) return message

The message text will be printed and then the core mechanism will pass the message object to all the other middlewares first, and to the functions then.

Once your middleware class is ready, import it in the middlewares/__init__.py and add its name in the __all__ array:

# middlewares/__init__.py file from ._example_middleware import ExampleMiddleware __all__ = ['ExampleMiddleware',]

telegram-bot-design-pattern is mantained by Luca Di Vita — GitHub — Telegram

Читайте также:  Html select option bootstrap

telegram-bot-design-pattern is released under MIT license.

About

A design pattern for python Telegram Bots with a clean structure and middlewares

Источник

Какой паттерн проектирования использовать для телеграм бота

Пишу бот-каталог одежды своего магазина в телеграме на python с помощью aiogram, сейчас задумался о паттерне проектирования своего проекта. Может кто уже писал подобное, подскажите пожалуйста какой паттерн использовать mvp mvc или mvvm. Или может какой-нибудь другой, я просто первый раз с этим столкнулся

Какой паттерн проектирования использовать для обхода файла *.xml?
Всем привет! Я понимаю, что тема не совсем для Qt-хаба, но я планирую реализацию именно на Qt. .

какой это паттерн проектирования?
Кусок кода из hex-rays: CMyClass1 *__stdcall CMyClass1__GetInstance() < return g_pCMyClass1;.

Подскажите какой паттерн использовать для запоминания расположения категории товара
Товар может находиться в подкатегории например, техника/цифровая техника/фотоаппараты — вложенность.

А все таки, какой паттерн лучше использовать для проверки данных формы?
Да так что бы избежать дублирования html кода и не смешивать логику модели и представления?

Паттерн проектирования для сервера
Всем привет, столкнулся с проблемой правильного подхода к проектированию проекта. У меня есть C#.

Какой паттерн использовать?
Здравствуйте. Есть задача: создавать пользователей с разным уровнем доступа (user, moderator.

Какой паттерн использовать?
Какой паттерн использовать (и использовать ли) в такой ситуации: Существует множество.

Какой паттерн использовать в данном случае?
Есть у меня паттерн абстрактная фабрика. Но в этой абстрактной фабрике мне потребовалось сделать.

Какой паттерн использовать в такой ситуации?
Клиент переводит деньги на счет в банк, ему выдают кредитную карточку, по которой он может получить.

Какой паттерн в данном случае лучше использовать?
Всем привет! Пишу форум и сейчас у меня стоит задача создания секции в разделе. Проблема в том,что.

Календарь для телеграм бота
Есть 2 функции: реализации календаря и выбора даты. @bot.message_handler(commands=) def.

Источник

Оцените статью