send_error(m.chat.id) def callback_listener(call): logger.info(call) try: message_dispatched = dispatch(bot, chats, call.from_user.id, call.data, call.message.message_id) if not message_dispatched: logging.warning(u'Message2 is not dispatched (chat id - {0}) | message: {1}'.format(call.from_user.id, call.data)) send_error(call.from_user.id) except Exception as e: if chats.get(call.from_user.id) is not None: del chats[call.from_user.id] logging.error(u'Error2 by chat with id {0} | error: {1}'.format(call.from_user.id, e)) send_error(call.from_user.id) if __name__ == '__main__': bot = TeleBot(config.token) bot.set_update_listener(listener) @bot.callback_query_handler(func=lambda call: True) def test_callback(call): callback_listener(call) bot.polling(none_stop=True) while True: time.sleep(200)
#!/usr/bin/env python3 import os from telebot import TeleBot from utils import TokenNotDefined TOKEN = os.environ.get('TOKEN') if not TOKEN: raise TokenNotDefined('TOKEN must be defined') bot = TeleBot(TOKEN) @bot.message_handler(commands=['start', 'help']) def send_welcome(message): bot.reply_to(message, 'Welcome to {{ cookiecutter.bot_name | title }} Bot') @bot.message_handler(func=lambda message: True) def echo_message(message): bot.reply_to(message, message.text) if __name__ == '__main__': bot.polling()
class TestTelebot: def setup(self): self.app = TeleBot(__name__) def teardown(self): self.app = None def test_no_config(self): ''' Verify polling can't start without api_key set. ''' pytest.raises(ValueError, self.app.poll) def test_parrot_registered(self): ''' Verify route decorator registers within the update rules. ''' @self.app.route('(?!/).+') def parrot(message): return "testing {}".format(message) assert len(self.app.update_rules) == 1 assert self.app.update_rules[0]['rule'] == re.compile('(?!/).+') assert self.app.update_rules[0]['endpoint'] is None assert self.app.update_rules[0]['options'] == {} assert self.app.update_rules[0]['view_func']('it') == "testing it" @my_vcr.use_cassette('telegram.yaml') def test_start(self): self.app.config['api_key'] = '123:abc' self.app._start() assert self.app.whoami == { 'first_name': 'Test-Bot', 'id': 123, 'username': '******', } @my_vcr.use_cassette('telegram.yaml') def test_start_existing(self): ''' Make sure start doesn't override whoami when previously set. ''' self.app.config['api_key'] = '123:abc' self.app.whoami = {'id': 111} self.app._start() assert self.app.whoami == {'id': 111} @my_vcr.use_cassette('telegram.yaml') def test_parrot_app(self): test_messages = [] @self.app.route('/command ?(.*)') def example_command(message, cmd): chat_dest = message['chat']['id'] msg = "Command Received: {}".format(cmd) self.app.send_message(chat_dest, msg) test_messages.append([message, cmd, chat_dest, msg]) @self.app.route('(?!/).+') def parrot(message): chat_dest = message['chat']['id'] user_msg = message['text'] msg = "Parrot Says: {}".format(user_msg) self.app.send_message(chat_dest, msg) test_messages.append([message, chat_dest, msg]) self.app.config['api_key'] = '123:abc' pytest.raises(ValueError, self.app.poll, debug=True) assert test_messages == [ [ { 'chat': { 'first_name': 'Test', 'id': 8282, 'last_name': 'User', 'type': 'private', 'username': '******', }, 'date': 1462057648, 'from': { 'first_name': 'Test', 'id': 8282, 'last_name': 'User', 'username': '******', }, 'message_id': 73, 'text': 'Test 1', }, 8282, 'Parrot Says: Test 1', ], [ { 'chat': { 'first_name': 'Test', 'id': 8282, 'last_name': 'User', 'type': 'private', 'username': '******', }, 'date': 1462057662, 'entities': [ {'length': 8, 'offset': 0, 'type': 'bot_command'}, ], 'from': { 'first_name': 'Test', 'id': 8282, 'last_name': 'User', 'username': '******', }, 'message_id': 75, 'text': '/command test', }, 'test', 8282, 'Command Received: test', ], [ { 'chat': { 'first_name': 'Test', 'id': 8282, 'last_name': 'User', 'type': 'private', 'username': '******', }, 'date': 1462057676, 'from': { 'first_name': 'Test', 'id': 8282, 'last_name': 'User', 'username': '******', }, 'message_id': 77, 'text': 'End test', }, 8282, 'Parrot Says: End test' ], ]
def setup(self): self.app = TeleBot(__name__)
"""Telegram bot.""" import locale import re from time import sleep from datetime import datetime, timedelta from telebot import TeleBot, types from config import token from parser import get_films_data from logger import log_request_messages, log_uncorrect_messages bot = TeleBot(token) film_dict = {} cinema_dict = {'Forum': 'http://planetakino.ua/lvov2/ua/showtimes/xml/', 'Kingcross': 'http://planeta-kino.com.ua/lvov/ua/showtimes/xml/'} class FilmSession: """Class that represent film session data.""" def __init__(self): """Initialize data.""" self.today = today self.cinema = None self.period = None @bot.message_handler(commands=['help']) def handle_help_command(message):
def process_message(session, update): bot = TeleBot(eloop, **update) response = yield from bot.get_response() r = yield from send_reply(session, response) return r
from telebot import types, TeleBot from dynaconf import settings as _settings import pyowm bot = TeleBot(_settings.SECRET_KEY) keyboard = types.InlineKeyboardMarkup() key_yes = types.InlineKeyboardButton(text='Что у нас по погоде?', callback_data='weather') keyboard.add(key_yes) key_no = types.InlineKeyboardButton(text='Пока не надо', callback_data='bye') keyboard.add(key_no) @bot.message_handler(commands=["weather"]) def weather_handler(message): chat_id = message.chat.id city = bot.send_message(chat_id, "В каком городе Вам показать погоду?") bot.register_next_step_handler(city, weather) def weather(message): chat_id = message.chat.id city = message.text.lower() owm = pyowm.OWM(_settings.API_KEY, language="ru") city_weather = owm.weather_at_place(city) w = city_weather.get_weather() temperature = w.get_temperature("celsius")["temp"] wind = w.get_wind()["speed"] hum = w.get_humidity() desc = w.get_detailed_status()
from telebot import TeleBot, types import logging import sqlite3 from sqlite3 import Error import time import ast # import to the impport, this somewhere before logic logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) # logger.warning('Error: "%s" caused error "%s"', message.text, db_add_list_check) # put before the logic bot = TeleBot("1529560161:AAFhykAK52eMxbavAyF8hMt2QR-F2fhtMzQ") named_tuple = time.localtime() time_string = time.strftime('%H:%M, %m.%d.%y', named_tuple) today = str(time_string) list_name_to_add = '' list_id = 0 item_name = '' list_lists = '' pcs_of_items = 0 list_of_items = '' # connecting to DB and further executing queries def post_sql_query(sql_query): with sqlite3.connect('telebot.db', check_same_thread=True) as connection: cursor = connection.cursor()
def delete_message(bot: telebot.TeleBot, chat_id: int, message_id: int) -> Any: return bot.delete_message(chat_id, message_id)
from telebot import apihelper from config import TELEGRAM_TOKEN, CHAT_ID import csv from datetime import datetime import uuid import re # proxy settings # apihelper.proxy = {'http': 'http://45.55.53.22844578'} bot = TeleBot(TELEGRAM_TOKEN) user_dict = dict() # for check email validity regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$' FILENAME = 'output.csv' class Request: def __init__(self, chat_id): self.chat_id = chat_id self.uuid = str(uuid.uuid4()) self.user_id = None self.datetime = None
from core import minus_of_pompa from core import to_order_pompa import core import time from dictionary import prices from flask import Flask, request # Testbot # token = '' # bot = TeleBot(token) # bot = TeleBot('') # SV19bot token = '' bot = TeleBot(token) # # WEBHOOK_HOST = '' # WEBHOOK_PORT = 8443 # 443, 80, 88 или 8443 (порт должен быть открыт!) # LOCAL_PORT = 9001 # # LOCAL_LISTEN = '127.0.0.1' # WEBHOOK_LISTEN = '' # # # WEBHOOK_SSL_CERT = '/root/ssl/webhook_cert.pem' # Путь к сертификату # WEBHOOK_SSL_CERT = '/home/iman/ssl/webhook_pkey.pem' # Путь к сертификату # # WEBHOOK_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, WEBHOOK_PORT) # LOCAL_URL_BASE = "https://%s:%s" % (WEBHOOK_HOST, LOCAL_PORT) # WEBHOOK_URL_PATH = "/%s/" % token
def __init__(self, token: str): self.__bot = TeleBot(token) self.__api_worker = ApiWorker()
def __init__(self, token: str): self.bot = TeleBot(token) self.handler = HandlerBuilder(self.bot)
from telebot import TeleBot, types from config import TOKEN, BUTTONS bot = TeleBot(TOKEN) @bot.message_handler(commands=['start']) def begin(message): kb = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) buttons = [ types.KeyboardButton(text=BUTTONS['go_to_inline']), types.KeyboardButton(text=BUTTONS['contact'], request_contact=True), types.KeyboardButton(text=BUTTONS['location'], request_location=True) ] kb.add(*buttons) bot.send_message( message.chat.id, 'Hello', reply_to_message_id=message.message_id, reply_markup=kb ) @bot.message_handler(func=lambda m: m.text == BUTTONS['go_to_inline'], content_types=['text']) def hello_handler(message): kb = types.InlineKeyboardMarkup(row_width=1)
def __init__(self, botid, chatid): self.botid = botid self.chatid = chatid self.bot = TeleBot(self.botid)