Exemple #1
0
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

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())
Exemple #3
0
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),
Exemple #4
0
        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

# 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 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)
Exemple #8
0
# -*- 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'],
Exemple #9
0
from gtts import gTTS
from telebot.async_telebot import AsyncTeleBot

from logger import get_logger
from models import BotTable, Lang
from models.db import async_session
from photo import PhotoWorker
from string_constant import rus as str_const

# constants
TOKEN = os.getenv("TOKEN")
PHOTO_URL = "https://api.telegram.org/file/bot{0}/{1}"
LOADING = {"\\": "|", "|": "/", "/": "-", "-": "\\"}


bot = AsyncTeleBot(TOKEN)
log = get_logger(__name__)


@bot.message_handler(commands=['help'])
async def handle_help(message: telebot.types.Message):
    """ Handle for processing message /help """
    log.info("Handling /help")
    log.debug(str(message))
    await bot.send_message(message.chat.id, str_const.help_message)


@bot.message_handler(commands=['start'])
async def handle_start(message: telebot.types.Message):
    """ Handle for processing message /start """
    log.info("Handling /start")