Returned language will be set to context language variable. If you need to get translation with user's actual language you don't have to pass it manually It will be automatically passed from context language value. However if you need some other language you can always pass it. """ user_id = obj.from_user.id if user_id not in users_lang: users_lang[user_id] = 'en' return users_lang[user_id] storage = StateMemoryStorage() bot = AsyncTeleBot("", state_storage=storage) i18n = I18NMiddleware(translations_path='locales', domain_name='messages') _ = i18n.gettext # for singular translations __ = i18n.ngettext # for plural translations # These are example storages, do not use it in a production development users_lang = {} users_clicks = {} @bot.message_handler(commands='start') async def start_handler(message: types.Message): text = _("Hello, {user_fist_name}!\n" "This is the example of multilanguage bot.\n" "Available commands:\n\n"
import telebot from telebot.async_telebot import AsyncTeleBot import logging logger = telebot.logger telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console. class ExceptionHandler(telebot.ExceptionHandler): def handle(self, exception): logger.error(exception) bot = AsyncTeleBot('TOKEN', exception_handler=ExceptionHandler()) @bot.message_handler(commands=['photo']) async def photo_send(message: telebot.types.Message): await bot.send_message(message.chat.id, 'Hi, this is an example of exception handlers.') raise Exception('test') # Exception goes to ExceptionHandler if it is set import asyncio asyncio.run(bot.polling())
from telebot.async_telebot import AsyncTeleBot from telebot import formatting bot = AsyncTeleBot('token') @bot.message_handler(commands=['start']) async def start_message(message): await bot.send_message( message.chat.id, # function which connects all strings formatting.format_text( formatting.mbold(message.from_user.first_name), formatting.mitalic(message.from_user.first_name), formatting.munderline(message.from_user.first_name), formatting.mstrikethrough(message.from_user.first_name), formatting.mcode(message.from_user.first_name), separator=" " # separator separates all strings ), parse_mode='MarkdownV2') # just a bold text using markdownv2 await bot.send_message(message.chat.id, formatting.mbold(message.from_user.first_name), parse_mode='MarkdownV2') # html await bot.send_message( message.chat.id, formatting.format_text( formatting.hbold(message.from_user.first_name),
from telebot.async_telebot import AsyncTeleBot import telebot bot = AsyncTeleBot('TOKEN') # Chat id can be private or supergroups. @bot.message_handler(chat_id=[12345678], commands=['admin'] ) # chat_id checks id corresponds to your list or not. async def admin_rep(message): await bot.send_message(message.chat.id, "You are allowed to use this command.") @bot.message_handler(commands=['admin']) async def not_admin(message): await bot.send_message(message.chat.id, "You are not allowed to use this command") # Do not forget to register bot.add_custom_filter(telebot.asyncio_filters.ChatFilter()) import asyncio asyncio.run(bot.polling())
# -*- coding: utf-8 -*- """ This Example will show you an advanced usage of CallbackData. In this example calendar was implemented """ import asyncio from datetime import date from filters import calendar_factory, calendar_zoom, bind_filters from keyboards import generate_calendar_days, generate_calendar_months, EMTPY_FIELD from telebot import types from telebot.async_telebot import AsyncTeleBot API_TOKEN = '' bot = AsyncTeleBot(API_TOKEN) @bot.message_handler(commands='start') async def start_command_handler(message: types.Message): await bot.send_message( message.chat.id, f"Hello {message.from_user.first_name}. This bot is an example of calendar keyboard." "\nPress /calendar to see it.") @bot.message_handler(commands='calendar') async def calendar_command_handler(message: types.Message): now = date.today() await bot.send_message(message.chat.id, 'Calendar', reply_markup=generate_calendar_days(
# Just a little example of middleware handlers from telebot.asyncio_handler_backends import BaseMiddleware, CancelUpdate from telebot.async_telebot import AsyncTeleBot bot = AsyncTeleBot('TOKEN') class SimpleMiddleware(BaseMiddleware): def __init__(self, limit) -> None: self.last_time = {} self.limit = limit self.update_types = ['message'] # Always specify update types, otherwise middlewares won't work async def pre_process(self, message, data): if not message.from_user.id in self.last_time: # User is not in a dict, so lets add and cancel this function self.last_time[message.from_user.id] = message.date return if message.date - self.last_time[message.from_user.id] < self.limit: # User is flooding await bot.send_message(message.chat.id, 'You are making request too often') return CancelUpdate() self.last_time[message.from_user.id] = message.date async def post_process(self, message, data, exception): pass bot.setup_middleware(SimpleMiddleware(2))
from telebot import types, util from telebot.async_telebot import AsyncTeleBot bot = AsyncTeleBot('TOKEN') #chat_member_handler. When status changes, telegram gives update. check status from old_chat_member and new_chat_member. @bot.chat_member_handler() async def chat_m(message: types.ChatMemberUpdated): old = message.old_chat_member new = message.new_chat_member if new.status == "member": await bot.send_message(message.chat.id, "Hello {name}!".format(name=new.user.first_name) ) # Welcome message #if bot is added to group, this handler will work @bot.my_chat_member_handler() async def my_chat_m(message: types.ChatMemberUpdated): old = message.old_chat_member new = message.new_chat_member if new.status == "member": await bot.send_message(message.chat.id, "Somebody added me to group" ) # Welcome message, if bot was added to group await bot.leave_chat(message.chat.id) #content_Type_service is: #'new_chat_members', 'left_chat_member', 'new_chat_title', 'new_chat_photo', 'delete_chat_photo', 'group_chat_created', #'supergroup_chat_created', 'channel_chat_created', 'migrate_to_chat_id', 'migrate_from_chat_id', 'pinned_message',
from telebot.async_telebot import AsyncTeleBot bot = AsyncTeleBot('TOKEN') async def start_executor(message): await bot.send_message(message.chat.id, 'Hello!') bot.register_message_handler(start_executor, commands=['start']) # Start command executor # See also # bot.register_callback_query_handler(*args, **kwargs) # bot.register_channel_post_handler(*args, **kwargs) # bot.register_chat_member_handler(*args, **kwargs) # bot.register_inline_handler(*args, **kwargs) # bot.register_my_chat_member_handler(*args, **kwargs) # bot.register_edited_message_handler(*args, **kwargs) # And other functions.. import asyncio asyncio.run(bot.polling())
from telebot import asyncio_filters from telebot.async_telebot import AsyncTeleBot # list of storages, you can use any storage from telebot.asyncio_storage import StateMemoryStorage # new feature for states. from telebot.asyncio_handler_backends import State, StatesGroup # default state storage is statememorystorage bot = AsyncTeleBot('TOKEN', state_storage=StateMemoryStorage()) # Just create different statesgroup class MyStates(StatesGroup): name = State() # statesgroup should contain states surname = State() age = State() # set_state -> sets a new state # delete_state -> delets state if exists # get_state -> returns state if exists @bot.message_handler(commands=['start']) async def start_ex(message): """ Start command. Here we are starting state """ await bot.set_state(message.from_user.id, MyStates.name, message.chat.id)
from telebot.async_telebot import AsyncTeleBot import telebot bot = AsyncTeleBot('TOKEN') # AdvancedCustomFilter is for list, string filter values class MainFilter(telebot.asyncio_filters.AdvancedCustomFilter): key = 'text' @staticmethod async def check(message, text): return message.text in text # SimpleCustomFilter is for boolean values, such as is_admin=True class IsAdmin(telebot.asyncio_filters.SimpleCustomFilter): key = 'is_admin' @staticmethod async def check(message: telebot.types.Message): result = await bot.get_chat_member(message.chat.id, message.from_user.id) return result.status in ['administrator', 'creator'] @bot.message_handler(is_admin=True, commands=['admin']) # Check if user is admin async def admin_rep(message): await bot.send_message(message.chat.id, "Hi admin")
# -*- coding: utf-8 -*- """ This Example will show you usage of TextFilter In this example you will see how to use TextFilter with (message_handler, callback_query_handler, poll_handler) """ import asyncio from telebot import types from telebot.async_telebot import AsyncTeleBot from telebot.asyncio_filters import TextMatchFilter, TextFilter, IsReplyFilter bot = AsyncTeleBot("") @bot.message_handler(text=TextFilter(equals='hello')) async def hello_handler(message: types.Message): await bot.send_message(message.chat.id, message.text) @bot.message_handler(text=TextFilter(equals='hello', ignore_case=True)) async def hello_handler_ignore_case(message: types.Message): await bot.send_message(message.chat.id, message.text + ' ignore case') @bot.message_handler(text=TextFilter(contains=['good', 'bad'])) async def contains_handler(message: types.Message): await bot.send_message(message.chat.id, message.text) @bot.message_handler(text=TextFilter(contains=['good', 'bad'],
from telebot.async_telebot import AsyncTeleBot bot = AsyncTeleBot('TOKEN') @bot.message_handler(commands=['start', 'help']) async def send_welcome(message): await bot.reply_to(message, "Howdy, how are you doing?") @bot.message_handler(func=lambda message: True) async def echo_all(message): await bot.reply_to(message, message.text) import asyncio asyncio.run(bot.polling(skip_pending=True)) # to skip updates
from telebot.async_telebot import AsyncTeleBot import telebot bot = AsyncTeleBot('TOKEN') # Check if message starts with @admin tag @bot.message_handler(text_startswith="@admin") async def start_filter(message): await bot.send_message(message.chat.id, "Looks like you are calling admin, wait...") # Check if text is hi or hello @bot.message_handler(text=['hi', 'hello']) async def text_filter(message): await bot.send_message( message.chat.id, "Hi, {name}!".format(name=message.from_user.first_name)) # Do not forget to register filters bot.add_custom_filter(telebot.asyncio_filters.TextMatchFilter()) bot.add_custom_filter(telebot.asyncio_filters.TextStartsFilter()) import asyncio asyncio.run(bot.polling())
#!/usr/bin/python # This is a simple echo bot using the decorator mechanism. # It echoes any incoming text messages. # Example on built-in function to receive and process webhooks. from telebot.async_telebot import AsyncTeleBot import asyncio bot = AsyncTeleBot('TOKEN') WEBHOOK_SSL_CERT = './webhook_cert.pem' # Path to the ssl certificate WEBHOOK_SSL_PRIV = './webhook_pkey.pem' # Path to the ssl private key DOMAIN = '1.2.3.4' # either domain, or ip address of vps # Quick'n'dirty SSL certificate generation: # # openssl genrsa -out webhook_pkey.pem 2048 # openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem # # When asked for "Common Name (e.g. server FQDN or YOUR name)" you should reply # with the same value in you put in WEBHOOK_HOST # Handle '/start' and '/help' @bot.message_handler(commands=['help', 'start']) async def send_welcome(message): await bot.reply_to(message, """\ Hi there, I am EchoBot. I am here to echo your kind words back to you. Just say anything nice and I'll say the exact same thing to you!\ """)
WEBHOOK_SSL_CERT = './webhook_cert.pem' # Path to the ssl certificate WEBHOOK_SSL_PRIV = './webhook_pkey.pem' # Path to the ssl private key WEBHOOK_URL_BASE = "https://{}:{}".format(WEBHOOK_HOST, WEBHOOK_PORT) WEBHOOK_URL_PATH = "/{}/".format(API_TOKEN) # Quick'n'dirty SSL certificate generation: # # openssl genrsa -out webhook_pkey.pem 2048 # openssl req -new -x509 -days 3650 -key webhook_pkey.pem -out webhook_cert.pem # # When asked for "Common Name (e.g. server FQDN or YOUR name)" you should reply # with the same value in you put in WEBHOOK_HOST logger = telebot.logger telebot.logger.setLevel(logging.INFO) bot = AsyncTeleBot(API_TOKEN) # Process webhook calls async def handle(request): if request.match_info.get('token') == bot.token: request_body_dict = await request.json() update = telebot.types.Update.de_json(request_body_dict) asyncio.ensure_future(bot.process_new_updates([update])) return web.Response() else: return web.Response(status=403) # Handle '/start' and '/help' @bot.message_handler(commands=['help', 'start'])
from telebot.async_telebot import AsyncTeleBot # Update listeners are functions that are called when any update is received. bot = AsyncTeleBot(token='TOKEN') async def update_listener(messages): for message in messages: if message.text == '/start': await bot.send_message(message.chat.id, 'Hello!') bot.set_update_listener(update_listener) import asyncio asyncio.run(bot.polling())
from telebot.async_telebot import AsyncTeleBot from telebot import asyncio_filters bot = AsyncTeleBot('TOKEN') # Handler @bot.message_handler(chat_types=['supergroup'], is_chat_admin=True) async def answer_for_admin(message): await bot.send_message(message.chat.id, "hello my admin") # Register filter bot.add_custom_filter(asyncio_filters.IsAdminFilter(bot)) import asyncio asyncio.run(bot.polling())
# multi-language bots with middleware handler. # # Also, you could check language code in handler itself too. # But this example just to show the work of middlewares. import telebot from telebot.async_telebot import AsyncTeleBot from telebot import asyncio_handler_backends import logging logger = telebot.logger telebot.logger.setLevel(logging.DEBUG) # Outputs debug messages to console. TRANSLATIONS = {'hello': {'en': 'hello', 'ru': 'привет', 'uz': 'salom'}} bot = AsyncTeleBot('TOKEN') class LanguageMiddleware(asyncio_handler_backends.BaseMiddleware): def __init__(self): self.update_types = [ 'message' ] # Update types that will be handled by this middleware. async def pre_process(self, message, data): data['response'] = TRANSLATIONS['hello'][ message.from_user.language_code] async def post_process(self, message, data, exception): if exception: # You can get exception occured in handler. logger.exception(str(exception))
from telebot.async_telebot import AsyncTeleBot import telebot bot = AsyncTeleBot('TOKEN') @bot.chat_join_request_handler() async def make_some(message: telebot.types.ChatJoinRequest): await bot.send_message(message.chat.id, 'I accepted a new user!') await bot.approve_chat_join_request(message.chat.id, message.from_user.id) import asyncio asyncio.run(bot.polling())
def register_handlers(bot: AsyncTeleBot): bot.register_message_handler(hello_handler, func=lambda message: message.text == 'Hello', pass_bot=True) bot.register_message_handler(echo_handler, pass_bot=True)