def start(config: Config): bot = TeleBot(config.TELE_TOKEN) Handler( bot=bot, issuer_id=config.ISSUER_ID, processor=Processor( parser=get_parser(config.DIR_PATTERN), db_man=DBManager[Cowboy]( path=get_data_folder_path(), object_type=Cowboy, create_if_missing=True, ), explorer_cls=get_explorer_cls(config.GITHUB_TOKEN), ), serializer=Serializer(), deserializer=Deserializer(), ) DEF_PORT = "8443" URL_BASE = f"https://{config.HOST}" URL_PATH = f"/{config.TELE_TOKEN}" cert = f"{get_data_folder_path()}/{config.CERT}" bot.remove_webhook() if config.DEBUG != "0": logger.info("Running in a DEBUG mode.") bot.polling(none_stop=True) else: logger.info("Running in a PRODUCTION mode.") flask_app = get_flask_app(bot) bot.set_webhook(url=URL_BASE + URL_PATH, certificate=open(cert, "rb")) flask_app.run(host=config.LISTEN, port=DEF_PORT)
async def adds_a_bot(bot: Bot, user: UserDB = Depends( fastapi_users.current_user(verified=True))): bot_list = user.bots if len(bot_list) < 5: if bot in bot_list: raise HTTPException(status_code=409, detail="The requested bot already exists") else: if os.getenv("HOST_IP") is not None: telegram_bot = TeleBot(bot.token) telegram_bot.remove_webhook() url = urllib.parse.urljoin( os.getenv("URL"), f"/bots/webhook/{user.id}/{bot.token}") telegram_bot.set_webhook(url) bot_list = list(map(lambda x: dict(x), bot_list)) bot_list.append(bot.dict()) await user_db.update_one({"id": user.id}, {"$set": { "bots": bot_list, }}) return bot_list else: raise HTTPException(status_code=403, detail="You cannot have more than 5 bots")
def set_bot_webhook(address): if address: from timespick.keys import TELEGRAM_TOKEN_dev webhook_address = f"{address}/bot/{TELEGRAM_TOKEN_dev}" bot = TeleBot(TELEGRAM_TOKEN_dev) bot.set_webhook(url=webhook_address) print(f'==> Successfully set Telegram bot webhook to {address}') print(f'CHANGE TELEGRAM BOT DOMAIN here: https://t.me/BotFather')
class SetWebHook(metaclass=MetaSingleton): def __init__(self): self.bot = TeleBot(settings.TOKEN) log.info('delete webhook') self.bot.delete_webhook() log.info('set webhook') self.bot.set_webhook(url=f"{settings.DOMAIN}/" f"{settings.TOKEN}") log.info('setup webhook complete')
def add_bot(message: types.Message): token = util.extract_arguments(message.text) tokens[token] = True new_bot = TeleBot(token) new_bot.delete_webhook() new_bot.set_webhook(f"{config.WEBHOOK_HOST}/{config.WEBHOOK_PATH}/{token}") new_bot.send_message(message.chat.id, "Webhook was set.")
def post_fork(server, worker): if forked == workers: from time import sleep from telebot import TeleBot from config import BOT_TOKEN from time import sleep from scheduler_controller import schedule_controller from logger_settings import hr_logger hr_logger.info('Сервіс запущено') bot = TeleBot(BOT_TOKEN, threaded=False) bot.remove_webhook() sleep(1) bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH, certificate=open(WEBHOOK_SSL_CERT, 'r')) schedule_controller()
json_string = request.get_data().decode('utf-8') update = types.Update.de_json(json_string) if token == main_bot.token: main_bot.process_new_updates([update]) return '' from_update_bot = TeleBot(token) register_handlers(from_update_bot) from_update_bot.process_new_updates([update]) return '' @main_bot.message_handler(commands=['add_bot']) def add_bot(message: types.Message): token = util.extract_arguments(message.text) tokens[token] = True new_bot = TeleBot(token) new_bot.delete_webhook() new_bot.set_webhook(f"{config.WEBHOOK_HOST}/{config.WEBHOOK_PATH}/{token}") new_bot.send_message(message.chat.id, "Webhook was set.") if __name__ == '__main__': main_bot.delete_webhook() main_bot.set_webhook( f"{config.WEBHOOK_HOST}/{config.WEBHOOK_PATH}/{config.MAIN_BOT_TOKEN}") app.run(host=config.WEBAPP_HOST, port=config.WEBAPP_PORT)
from telebot import TeleBot from config import TOKEN, WEBHOOK_HOST bot = TeleBot(TOKEN, parse_mode='HTML') bot.remove_webhook() bot.set_webhook(url=WEBHOOK_HOST.format(TOKEN))
new_link = SentLinks(user=user, link=link) new_link.save() # Send message to a user send_newsletter(user_id=user.user_id, text=text, link=link.link) # Stop choose = False except: pass # Start newsletter newsletter() # endregion NEWSLETTER # Not available in release mode. if settings.DEBUG: # Start polling in another thread # (allows not to freeze django admin) bot.remove_webhook() from threading import Thread t1 = Thread(target=bot.polling) t1.start() else: bot.remove_webhook() bot.set_webhook(url=f"{settings.DOMAIN}/{settings.TOKEN}")
from telebot import TeleBot, types from time import sleep from flask import request from loguru import logger from app import app TOKEN = app.config['TELEBOT_TOKEN'] PROXI_HOST = app.config['PROXI_HOST'] bot = TeleBot(TOKEN) bot.remove_webhook() sleep(1) bot.set_webhook(f'https://{PROXI_HOST}/telebot/{TOKEN}') from .handlers import * @app.route(f"/telebot/{app.config['TELEBOT_TOKEN']}", methods=['POST']) def handle_requests_to_bot(): bot.process_new_updates( [types.Update.de_json(request.stream.read().decode("utf-8"))]) return "ok", 200
class TelegramBot: def __init__(self): social_app = SocialApp.objects.last() TELEGRAM_TOKEN = social_app.secret TELEGRAM_WEBHOOK_HOST = social_app.sites.last().domain TELEGRAM_WEBHOOK_PATH = reverse("telegrambot:webhook") self.bot = TeleBot(TELEGRAM_TOKEN) self.WEBHOOK_URL = f"https://{TELEGRAM_WEBHOOK_HOST}{TELEGRAM_WEBHOOK_PATH}" logger.debug("%s: __init__()", self.__class__) def send_message(self, chat_id: int, text: str, reply_markup=None): try: self.bot.send_message(chat_id, text, reply_markup=reply_markup) except apihelper.ApiTelegramException as msg: logger.exception(msg) logger.debug(f"{self.__class__}: send_message({chat_id}, {text})") def send_photo(self, chat_id: str, photo_path: str, caption=None, reply_markup=None): with open(photo_path, "rb") as photo_file: photo = photo_file.read() try: self.bot.send_photo(chat_id, photo=photo, caption=caption, reply_markup=reply_markup) except apihelper.ApiTelegramException as msg: logger.exception(msg) logger.info( f"{self.__class__}: User {chat_id} baned your TelegramBot") else: logger.debug( f"{self.__class__}: send_photo({chat_id}, {photo_path})") def answer_callback_query(self, callback_id, text=None, show_alert=None, url=None, cache_time=None): self.bot.answer_callback_query( callback_id, text=text, show_alert=show_alert, url=url, cache_time=cache_time, ) def set_webhook(self): logger.debug("%s: set_hook() %s" % (self.__class__, self.WEBHOOK_URL)) return self.bot.set_webhook(url=self.WEBHOOK_URL) def remove_webhook(self): logger.debug("%s: remove_webhook()", self.__class__) return self.bot.remove_webhook() def get_kb_phone(self): keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True) button_phone = types.KeyboardButton(text="Отправить номер телефона", request_contact=True) button_geo = types.KeyboardButton(text="Отправить местоположение", request_location=True) keyboard.add(button_phone, button_geo) return keyboard def get_kb_catalog(self): keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True, one_time_keyboard=True) buttons = [ types.KeyboardButton(text=item.name) for item in models.Catalog.objects.all() ] keyboard.add(*buttons) return keyboard def get_kb_inline_buy(self, product): keyboard = types.InlineKeyboardMarkup() buy = _("Buy") text = f"{buy}: {product.name}" buy_btn = types.InlineKeyboardButton(text, callback_data=str(product.id)) keyboard.add(buy_btn) return keyboard
from flask import Flask, request from telebot import TeleBot, types from pymongo import MongoClient from config import * import threading import time bot = TeleBot(token=token) bot.remove_webhook() bot.set_webhook(url=WEBHOOK_URL) app = Flask(__name__) client = MongoClient(mongo) db = client.db games = db.games players = db.players game_types = db.game_types @bot.message_handler(commands=['newgame']) def start_game(msg): if msg.from_user.id in GLOBALADMINS: if msg.chat.type != 'supergroup': bot.send_message(msg.chat.id, 'Сделайте группу супергуппой') return 0 if not bot_have_all_rights(bot.get_chat_member(msg.chat.id, BOT)): bot.send_message( msg.chat.id, 'Для начала игры необходимо дать боту все права администратора'
@bot.message_handler(func=lambda message: True, content_types=['contact']) def user_contact(message): phone_usr = message.contact.phone_number User.upsert_user(telegram_id=message.from_user.id, phone_number=phone_usr) cart = Cart.get_cart(message.from_user.id) cart.confirmed_cart(is_archived=True, type_delivery='Адресная доставка', confirmed_date=datetime.datetime.now()) bot.send_message( message.from_user.id, text= f"В ближайшее время с Вами свяжется наш менеджер для принятия заказа", reply_markup=root_kb_mk) """ WEBHOOK_HOST = https://33.46.32.19:8443 ----https://serverdomain.com SELF_SIGNED = PKEM = '/home/sertifivcatewebhook_pkem.pem' PKEY = '/home/sertifivcatewebhook_pkey.pem' bot.set_webhook(WEBHOOK_HOST,open('r',PKEM)) """ bot.polling()
@bot.message_handler(regexp='\/leaderboard ([1-9][0-9]+|[1-9])') @bot.message_handler(regexp='\/leaderboard') def get_leaderboard(message: Message): length: int = 10 if len(message.text) <= 13 else int( message.text[13:].strip()) bot.send_message(message.chat.id, serializer.leaderboard( processor.get_leaderboard()[:length]), parse_mode='Markdown') @bot.message_handler(func=lambda message: True) def repeat_all_messages(message): bot.send_message(message.chat.id, 'I don\'t know how to react!') bot.remove_webhook() if config.DEBUG != '0': logger.info("Running in a DEBUG mode.") bot.polling(none_stop=True) else: logger.info("Running in a PRODUCTION mode.") flask_app = get_flask_app(bot) bot.set_webhook(url=URL_BASE + URL_PATH, certificate=open(cert, 'rb')) flask_app.run( host=config.LISTEN, port=DEF_PORT, )
from telebot import TeleBot, logger from django.conf import settings import logging from .logger import logger_djtbot bot = TeleBot(settings.TOKEN) bot.set_webhook(settings.DOMAIN) logger.setLevel(logging.DEBUG) logger_djtbot.setLevel(logging.DEBUG)
class TelegramBot: def __init__(self, work_dir: Path, token: str): self.last_requests = {} # type: Dict[int, List[datetime]] self.work_dir = work_dir self.work_dir.mkdir(0o755, parents=True, exist_ok=True) self.token = token self.bot = TeleBot(token) self.bot.add_message_handler({ 'function': self.process_link, 'filters': { 'regexp': r'https?:\/\/.+\..+' } }) self.bot.add_message_handler({ 'function': self.process_message, 'filters': { 'func': lambda _: True } }) def process_link(self, message: Message): user_id = message.from_user.id if user_id not in self.last_requests: self.last_requests[user_id] = [] limit_req, limit_min = get_rate_limit() now = datetime.now(tz=timezone.utc) last_requests = [] for dt in self.last_requests[user_id]: time_passed = now - dt if time_passed.min < timedelta(minutes=limit_min): last_requests.append(dt) self.last_requests[user_id] = last_requests if len(self.last_requests[user_id]) > limit_req: next_available = self.last_requests[user_id][0] + timedelta( minutes=limit_min) - now self.bot.reply_to( message, f'Rate limited. Try again in {next_available.seconds} seconds') return else: self.last_requests[user_id].append(now) msg = self.bot.reply_to(message, "Link detected, processing") # detach from telebot update thread def download(): try: with YoutubeDL({'noplaylist': True}) as ydl: info = ydl.extract_info(message.text, download=False) if info['duration'] > 900: self.bot.edit_message_text('Source too long', message_id=msg.id, chat_id=msg.chat.id) return with YoutubeDL(get_options_audio(self.work_dir)) as ydl: ydl.add_post_processor( UploadHandler(self.bot, msg.id, msg.chat.id)) self.bot.edit_message_text('Downloading', message_id=msg.id, chat_id=msg.chat.id) ydl.download([message.text]) except UnsupportedError: self.bot.edit_message_text('Unsupported URL', message_id=msg.id, chat_id=msg.chat.id) except DownloadError: self.bot.edit_message_text('Download error', message_id=msg.id, chat_id=msg.chat.id) except Exception as e: self.bot.edit_message_text('Unknown error', message_id=msg.id, chat_id=msg.chat.id) logger.error('Unknown error', exc_info=e) reactor.callInThread(lambda: download()) def process_message(self, message: Message): self.bot.reply_to(message, 'Send me a link') def polling(self): self.bot.delete_webhook() self.bot.polling(long_polling_timeout=5) def stop_polling(self): self.bot.stop_polling() def set_webhook(self, host: str, port: int): cert_path, pkey_path = get_or_create_root_cert(self.work_dir, host) self.bot.remove_webhook() self.bot.set_webhook(url=f'https://{host}:{port}/{self.token}/', certificate=open(cert_path, 'r')) bot = self.bot class WebhookHandler(Resource): isLeaf = True def render_POST(self, request): request_body_dict = json.load(request.content) update = Update.de_json(request_body_dict) reactor.callInThread(lambda: bot.process_new_updates([update])) return b'' root = ErrorPage(403, 'Forbidden', '') root.putChild(self.token.encode(), WebhookHandler()) site = Site(root) sslcontext = ssl.DefaultOpenSSLContextFactory(str(pkey_path), str(cert_path)) reactor.listenSSL(port, site, sslcontext)
queues[call.inline_message_id] = OrderedDict( [(str(call.from_user.id), (call.from_user.first_name, call.from_user.last_name))]) last_name = '' if call.from_user.last_name is None else call.from_user.last_name # не выводим фамилию если None text = 'Очередь {} *{}*\n1. {} {}'.format(prep, subj, call.from_user.first_name, last_name) write_json() bot.edit_message_text(text, inline_message_id=call.inline_message_id, reply_markup=key, parse_mode='Markdown') else: if str(call.from_user.id) not in queues[call.inline_message_id]: queues[call.inline_message_id].update({str(call.from_user.id): (call.from_user.first_name, call.from_user.last_name)}) queues[call.inline_message_id].move_to_end(str(call.from_user.id)) text = 'Очередь {} *{}*\n'.format(prep, subj) n = 1 for i in queues[call.inline_message_id]: first_name, last_name = queues[call.inline_message_id][i][0], queues[call.inline_message_id][i][1] last_name = '' if last_name is None else last_name text += '{}. {} {}\n'.format(n, first_name, last_name) n += 1 write_json() bot.edit_message_text(text, inline_message_id=call.inline_message_id, reply_markup=key, parse_mode='Markdown') else: bot.answer_callback_query(call.id, 'Ты уже в очереди', False) bot.remove_webhook() bot.set_webhook(url=config.WEBHOOK_URL_BASE + config.WEBHOOK_URL_PATH, certificate=open(config.WEBHOOK_SSL_CERT)) cherrypy.quickstart(Serv(bot), config.WEBHOOK_URL_PATH, {'/': {}})
@app.route(WEBHOOK_PATH, methods=['POST']) def webhook(): if request.headers.get('content-type') == 'application/json': json_string = request.get_data().decode('utf-8') update = Update.de_json(json_string) bot.process_new_updates([update]) return '' else: abort(403) if __name__ == '__main__': bot.remove_webhook() time.sleep(1) bot.set_webhook(WEBHOOK_URL, certificate=open(CERT_NAME, 'r')) app.run(debug=True) else: app.run() # bot.polling() while True: try: requests.get('http://127.0.0.1:5000/AlgTrdSignals_bot/send_signal') except requests.exceptions.RequestException: for user in USER_LIST: bot.send_message(user, 'SOS') time.sleep(60)
import os from telebot import TeleBot TOKEN = os.environ.get('BOT_TOKEN') WEBHOOK_URL = os.environ.get('WEBHOOK_URL') bot = TeleBot(TOKEN) bot.remove_webhook() resp = bot.set_webhook(url=WEBHOOK_URL, certificate=open('/ssl/ssl_cert.pem', 'r'))
def validation_username(text): from api.models import Account if isinstance(text, Account): return text result = re.match(r'^[a-zA-Z][a-zA-Z0-9_]*$', text) if result: username = result.group(0).lower() account = Account.get(username) return account return None # bot.set_webhook(url="https://47bb-176-193-135-241.ngrok.io/bot/" + TELEGRAM_TOKEN) bot.set_webhook(url="https://dayspick.ru/bot/" + TELEGRAM_TOKEN) class BotNotification: @classmethod def send_to_admins(cls, message): try: for i in admin_ids: bot.send_message(i, message) except: print("Can't connect to Bot") @classmethod def send(cls, profile, message, project): if profile and profile.account and profile.account.telegram_chat_id and profile.account.telegram_notifications: try:
def user_contact(message): phone_usr = message.contact.phone_number User.upsert_user(telegram_id=message.from_user.id, phone_number=phone_usr) cart = Cart.get_cart(message.from_user.id) cart.confirmed_cart(is_archived=True, type_delivery='Адресная доставка', confirmed_date=datetime.datetime.now()) bot.send_message( message.from_user.id, text= f"В ближайшее время с Вами свяжется наш менеджер для принятия заказа", reply_markup=root_kb_mk) """ WEBHOOK_HOST = https://33.46.32.19:8443 ----https://serverdomain.com SELF_SIGNED = PKEM = '/home/sertifivcatewebhook_pkem.pem' PKEY = '/home/sertifivcatewebhook_pkey.pem' bot.set_webhook(WEBHOOK_HOST,open('r',PKEM)) """ if __name__ == '__main__': import time print('Started!') bot.remove_webhook() time.sleep(2) bot.set_webhook(url=WEBHOOK_URL, certificate=open('nginx-selfsigned.crt', 'r')) app.run(host='127.0.0.1', port=5000, debug=True)
if config.FACEBOOK_BOT_ENABLED: facebook_service = fbmq.Page(config.FACEBOOK_BOT_KEY) try: facebook_service.show_starting_button("START_PAYLOAD") except Exception as e: logging.warning(e) else: facebook_service = None if config.TELEGRAM_BOT_ENABLED: telegram_service = TeleBot(config.TELEGRAM_BOT_KEY, threaded=False) try: telegram_service.set_webhook( url='https://%s%s' % (config.SERVER_NAME, config.TELEGRAM_BOT_WEBHOOK), max_connections=100) except Exception as e: logging.warning(e) else: telegram_service = None if config.TELEGRAM_STRANGERGEO_ENABLED: strangergeo_service = TeleBot(config.TELEGRAM_STRANGERGEO_KEY, threaded=False) try: strangergeo_service.set_webhook( url='https://%s%s' % (config.SERVER_NAME, config.TELEGRAM_STRANGERGEO_WEBHOOK), max_connections=100) except Exception as e:
import os from telebot import TeleBot TOKEN = os.getenv('TOKEN') bot = TeleBot(TOKEN) bot.remove_webhook() bot.set_webhook(f"{os.getenv('APP_URL')}/{TOKEN}") @bot.message_handler(commands=['help', 'start']) def send_welcome(message): bot.reply_to(message, "Hi, I am ready for work! I will echo any text you send me!") @bot.message_handler(func=lambda message: True) def echo_message(message): bot.reply_to(message, message.text)
content = telegram_data[str(lvl)]["content"] text = [] for option in content: if type(option) is int: option_text = telegram_data[str(option)]["name"] text.append("+ " + option_text) keyboard.add(types.KeyboardButton(text=option_text)) else: text.append(option) if lvl: keyboard.add(types.KeyboardButton(text="На главную")) text = "\n".join(text) bot.send_message(uid, text, parse_mode="HTML", reply_markup=keyboard) bot.remove_webhook() bot.set_webhook( url=f"https://{PYTHONANYWHERE_USERNAME}.pythonanywhere.com/{SECRET}") with open("static/telegram.json") as telegram_data: telegram_data = load(telegram_data) if __name__ == '__main__': generate_html() app.run()
def listener(messages): for m in messages: print(str(m)) log = { 'date': dt.datetime.fromtimestamp(m.date), 'text': m.json['text'], 'username': m.json['from']['username'], 'type': 'message' } db_collection.insert_one(log) print('inserted to mongo db') user = environ['MONGO_USERNAME'] password = environ['MONGO_PASSWORD'] database = environ['MONGO_DB_NAME'] connection_end = 'cluster0-shard-00-00-dbct0.mongodb.net:27017,cluster0-shard-00-01-dbct0.mongodb.net:27017,cluster0-shard-00-02-dbct0.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true' client = pymongo.MongoClient("mongodb://{0}:{1}@{2}".format( user, password, connection_end)) db = client[database] # change this to start another collection db_collection = db.testing pprint(client.list_database_names()) bot.set_update_listener(listener) bot.set_webhook("https://{0}.glitch.me/{1}".format(environ['PROJECT_NAME'], environ['TELEGRAM_TOKEN']))
return '' else: flask.abort(403) @webapp.route('/sendMessage/', methods=['GET']) def echo_message(): sid = flask.request.args.get('id') text = flask.request.args.get('text') return send_message(dict(sid=sid, text=text)) def send_message(data): userList = tdb.find_ship_user(dict(sid=data['sid'])) result_text = {} for i, cid in enumerate([x['uid'] for x in userList]): status = bot.send_message(chat_id=cid, text=data['text']) result_text[i] = status.json return result_text bot.remove_webhook() sleep(1) bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH, certificate=open(WEBHOOK_SSL_CERT, 'r')) webapp.run(host=WEBHOOK_LISTEN, port=WEBHOOK_PORT, ssl_context=(WEBHOOK_SSL_CERT, WEBHOOK_SSL_PRIV), debug=False)
elif msg.text.startswith("del"): if urlparse(splitted_text[1]).netloc: response = user.delete_link(splitted_text[1]) bot.send_message(user.chat_id, response) else: links = user.get_links_by_tags(splitted_text) if links.count(): response = "result: \n" for link in links: response += f"🍕 [{link['title']}]({link['url']})" \ f" tags: *{link['tags']}*\n" bot.send_message(user.user_id, response, disable_web_page_preview=True, parse_mode="MARKDOWN") else: bot.send_message(user.user_id, "not found") if __name__ == "__main__": bot.remove_webhook() bot.set_webhook(url=f"{APP_URL}/{TOKEN}", certificate=open(server.cert)) app.run(host=server.host, port=server.port, ssl_context=(server.cert, server.pkey), debug=True)