existingPlayer = search_user_by_id(game_users, update.effective_user.id) if existingPlayer == None: text = 'Você não estava cadastrado. Digite /start para continuar' context.bot.sendMessage(chat_id=update.effective_user.id, text=text) return tex.ConversationHandler.END else: existingPlayer["active"] = False text = 'Para retornar ao menu do jogo, digite /play' context.bot.sendMessage(chat_id=update.effective_user.id, text=text) return tex.ConversationHandler.END updater = tex.Updater(token=TOKEN, use_context=True) dispatcher = updater.dispatcher start_handler = tex.ConversationHandler( entry_points=[tex.CommandHandler('start', start)], states={ "SET_NICK": [ tex.MessageHandler(tex.Filters.text & ~tex.Filters.command, set_nick) ] }, fallbacks=[tex.MessageHandler(tex.Filters.all, invalid_nick)]) play_handler = tex.ConversationHandler( entry_points=[tex.CommandHandler("play", play_command)],
import instabot from telegram import ext import telegram as tel updater = ext.Updater('1213036895:AAGr_3QzZ8_UhSwpBB2dJUe454wV0dZvv0o') def start(bot, update): chat_id = update.message.chat_id first_name = update.message.chat.first_name text_start = f'سلام {first_name} \n \ /login برای شروع کار با ربات باید با \n \ شروع کنید وبعد از لاگین یوز نیم وپسورد \n \ اینستاگرامتون رو وارد کنید مثال: \n \ /login username password' bot.sendMessage(chat_id, text_start) class InsTelgram: def __init__(self): self.username, self.password = '', '' self.like, self.follow = True, False self.comment, self.items = None, None self.num = 0 self.mod, self.insta, self.data = '', None, '' def login(self, bot, update, args): chat_id = update.message.chat_id if len(args) == 2: self.username = args[0]
import logging import sys from telegram import ext from app.hanlders import HANDLERS logger = logging.getLogger() logger.setLevel(logging.DEBUG) updater = ext.Updater("YOUR TOKEN") for handler in HANDLERS: updater.dispatcher.add_handler(handler) if __name__ == "__main__": updater.start_polling() print('service started ...') updater.idle()
try: IS_TEAM_DRIVE = os.environ['IS_TEAM_DRIVE'] if IS_TEAM_DRIVE.lower() == 'true': IS_TEAM_DRIVE = True else: IS_TEAM_DRIVE = False except KeyError: IS_TEAM_DRIVE = False try: USE_SERVICE_ACCOUNTS = os.environ['USE_SERVICE_ACCOUNTS'] if USE_SERVICE_ACCOUNTS.lower() == 'true': USE_SERVICE_ACCOUNTS = True else: USE_SERVICE_ACCOUNTS = False except KeyError: USE_SERVICE_ACCOUNTS = False try: SHORTENER = os.environ['SHORTENER'] SHORTENER_API = os.environ['SHORTENER_API'] if len(SHORTENER) == 0 or len(SHORTENER_API) == 0: raise KeyError except KeyError: SHORTENER = None SHORTENER_API = None updater = tg.Updater(token=BOT_TOKEN, use_context=True) bot = updater.bot dispatcher = updater.dispatcher
from Bot.config import Development as Config import logging import sys import telegram.ext as tg import pymongo import time StartTime = time.time() # enable logging logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO) LOGGER = logging.getLogger(__name__) LOGGER.info("Chizuru is now online, you perv.") # if version < 3.6, stop bot. if sys.version_info[0] < 3 or sys.version_info[1] < 6: LOGGER.error( "You MUST have a python version of at least 3.6! Multiple features depend on this. Bot quitting." ) quit(1) TOKEN = Config.TOKEN MONGO_CLIENT = pymongo.MongoClient(Config.MONGO_URI) updater = tg.Updater(TOKEN, use_context=True) dispatcher = updater.dispatcher
# SpamWatch if spamwatch_api is None: sw = None log.warning("SpamWatch API key is missing! Check your config.ini") else: try: sw = spamwatch.Client(spamwatch_api) except: sw = None log.warning("Can't connect to SpamWatch!") updater = tg.Updater(TOKEN, workers=min(32, os.cpu_count() + 4), request_kwargs={ "read_timeout": 10, "connect_timeout": 10 }) telethn = TelegramClient(MemorySession(), APP_ID, API_HASH) dispatcher = updater.dispatcher kp = Client(":memory:", api_id=APP_ID, api_hash=API_HASH, bot_token=TOKEN, workers=min(32, os.cpu_count() + 4)) apps = [] apps.append(kp)
}, "course_num_steps": { "type": "number" }, "course_num_questions": { "type": "number" } }, "required": [ "course_id", "course_name", "course_description", "course_num_steps", "course_num_questions" ] } # The Telegram updater. updater = tge.Updater(API_TOKEN) # Dispatcher for registering handlers. dispatcher = updater.dispatcher # Telegram command handlers. dispatcher.add_handler(tge.CommandHandler("start", start_cmd)) dispatcher.add_handler(tge.CommandHandler("help", help_cmd)) dispatcher.add_handler(tge.CommandHandler("gdpr", gdpr_cmd)) dispatcher.add_handler(tge.CommandHandler("time", time_cmd)) dispatcher.add_handler(tge.CommandHandler("courses", courses_cmd)) dispatcher.add_handler(tge.CommandHandler("enroll", enroll_cmd)) dispatcher.add_handler(tge.CommandHandler("next", next_cmd)) dispatcher.add_handler(tge.CommandHandler("score", score_cmd)) dispatcher.add_handler(tge.CommandHandler("cancel", cancel_cmd)) dispatcher.add_handler(tge.CommandHandler("quit", quit_cmd)) # Telegram handler for unknown commands.
def callback_handler(bot, update): callback_query = update.callback_query callback_data = callback_query.data if callback_data == 'feedback': user_id = callback_query.from_user.id feedback = models.FeedBack(user_id=user_id, is_incomplete=True) models.db.session.add(feedback) models.db.session.commit() update.callback_query.message.reply_text( 'Напишите сообщением ваш отзыв...') update.callback_query.answer() def registry_handlers(dispatcher): dispatcher.add_handler(tg_ext.CommandHandler('start', start_cmd)) dispatcher.add_handler( tg_ext.MessageHandler(tg_ext.Filters.text, message_handler)) dispatcher.add_handler(tg_ext.CallbackQueryHandler(callback_handler)) dispatcher.add_error_handler(error_handler) if config.polling_debug: updater = tg_ext.Updater(token=config.bot_token) registry_handlers(updater.dispatcher) updater.start_polling() # updater.idle() else: dispatcher = tg_ext.Dispatcher(bot, None, workers=0) registry_handlers(dispatcher)
if not SPAMWATCH_API: sw = None LOGGER.warning("SpamWatch API key missing! recheck your config.") else: sw = spamwatch.Client(SPAMWATCH_API) REDIS = StrictRedis.from_url(REDIS_URL, decode_responses=True) try: REDIS.ping() LOGGER.info("Your redis server is now alive!") except BaseException: raise Exception("Your redis server is not alive, please check again.") updater = tg.Updater( TOKEN, workers=WORKERS, # base_url='https://bot.mannu.me/bot', use_context=True) telethn = TelegramClient("mizuhara", API_ID, API_HASH) pbot = Client("mizuharaPyro", api_id=API_ID, api_hash=API_HASH, bot_token=TOKEN) dispatcher = updater.dispatcher DRAGONS = list(DRAGONS) + list(DEV_USERS) DEV_USERS = list(DEV_USERS) WOLVES = list(WOLVES) DEMONS = list(DEMONS) TIGERS = list(TIGERS)
def __init__(self, catalogHOST: str, catalogPORT: int, botToken: str): print("LOG: Telegram Bot initialization BEGIN") self.catalogEndPoint = catalogHOST + ":" + str(catalogPORT) self.availableDevices = {} self.availableServices = {} self.telegramBotToken = botToken # Get the broker from the catalog try: response = requests.get(self.catalogEndPoint + "/getMQTTMessageBroker") response.raise_for_status() except: raise ConnectionError("Unable to get mqtt broker from the catalog") try: responseDict = json.loads(response.text) if "url" not in responseDict or "port" not in responseDict: raise Exception() except: raise Exception("Response from catalog was invalid") self.brokerHOST = responseDict["url"] self.brokerPORT = responseDict["port"] # Initialize the thread for registration to the catalog self.registrationAndRetrivalThread = threading.Thread( target=self.registerAndRetrieveRagistrationsRunner) self.running = False self.subscribePayload = json.dumps({ "serviceID": "TelegramBot", "description": "A telegram bot that exposes the catalog to end users", "endPoints": [{ "service": "https://t.me/tiot19ControlBot", "type": "webService", "webType": "producer" }] }) self.catalogAvailable = False self.retrieveRegistrationsLock = threading.Lock() # Initialize the Telegram Bot self.botUpdater = ext.Updater(token=self.telegramBotToken, use_context=True) self.botDispatcher = self.botUpdater.dispatcher self.botDispatcher.add_handler( ext.CommandHandler(command="start", callback=self.botClbStart)) self.botDispatcher.add_handler( ext.CallbackQueryHandler(self.botClbQueryHandler)) self.botDispatcher.add_handler( ext.MessageHandler(ext.Filters.text, self.botMessageHandler)) # Initialize MQTT self.mqttReceivedValues = { } # Store, for every device/service that produces mqtt messages, a list of values (the most recent 64), so that we can then # produce a nice chart of that data and send it as a Telegram image. # The only drawback is that we must assume a common syntax for every mqtt resource, and that will be SenML. self.mqttReceivedValuesThreshold = 64 # Keep only the newest 64 values and discard the rest self.pendingAlerts = {} # For pending inputs of alert thresholds self.mqttClient = PahoMQTT.Client("tiot19_Catalog_Telegram_Bot", True) self.mqttClient.on_message = self.mqttOnMessage try: self.mqttClient.connect(self.brokerHOST, self.brokerPORT) self.mqttClient.loop_start() except: raise ConnectionError( "Unable to connect to the MQTT message broker") print("LOG: Telegram Bot initialization END")
import telegram import logging import telegram.ext as tex import helpers from scrapper import scrap import datetime import pickle import sys import wikiquote logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO) updater = tex.Updater(input("Please send the token provided by the BotFather")) dispatcher = updater.dispatcher bot = updater.bot try: subscribers = pickle.load(open("subscribers.pickle", "rb")) print("Loaded", len(subscribers), "subscribers from file.") except: print("Didn't load subscribers from file!") subscribers = [] print("Started Dr. Mensa Bot:", bot.getMe()) # Handler functions def start(bot, update): message = "Dies ist der _Drop-in replacement (Dr.) Mensa Bot_!"
log_time('imported python libraries') f = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logging.basicConfig(format=f, level=logging.INFO) logger = logging.getLogger(__name__) def error(bot, update, error): logger.warn('Update "%s" caused error "%s"' % (update, error)) token = open(dirname(__file__) + '/private/token.txt').read() updater = tg_ext.Updater((token)) dp = updater.dispatcher dp.add_error_handler(error) log_time('beginning to import bot modules') modules = [ 'info', 'settings', 'creator', 'reply', 'status', 'commands', 'text_parse', 'inline', 'sock',
from telegram.ext import CommandHandler import telegram import logging import time import parser import fun logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO ) token_file = "token" with open(token_file) as f: token = f.readline().replace("\n", "") updater = tele.Updater(token=token, use_context=True) dispatcher = updater.dispatcher def start(update, context): context.bot.send_message( chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!" ) def hey(update, context): context.bot.send_message(chat_id=update.effective_chat.id, text="Heyya!!") def roll_dice(update, context): chat_id = update.effective_chat.id
API_KEY = Config.API_KEY try: OWNER_ID = int(Config.OWNER_ID) except ValueError: raise Exception("Your OWNER_ID variable is not a valid integer.") try: FROM_CHATS = set(int(x) for x in Config.FROM_CHATS) except ValueError: raise Exception( "Your FROM_CHATS list does not contain valid integers.") try: TO_CHATS = set(int(x) for x in Config.TO_CHATS or []) except ValueError: raise Exception("Your TO_CHATS list does not contain valid integers.") WEBHOOK = Config.WEBHOOK IP_ADDRESS = Config.IP_ADDRESS URL = Config.URL PORT = Config.PORT CERT_PATH = Config.CERT_PATH WORKERS = Config.WORKERS updater = tg.Updater(API_KEY, workers=WORKERS) dispatcher = updater.dispatcher FROM_CHATS = list(FROM_CHATS) TO_CHATS = list(TO_CHATS)
import logging import sys from telegram import ext from app.hanlders import HANDLERS logger = logging.getLogger() logger.setLevel(logging.DEBUG) updater = ext.Updater(sys.argv[1]) for handler in HANDLERS: updater.dispatcher.add_handler(handler) updater.start_polling() print('service started ...') updater.idle()
def make_updater(): return t.Updater(token=TOKEN)
print("[EXCEPTION] _notify_start") if __name__=="__main__": # proxy authentication REQUEST_KWARGS=None if settings.PROXY: import telegram.vendor.ptb_urllib3.urllib3 as urllib3 REQUEST_KWARGS={"proxy_url": settings.PROXY_TYPE+settings.PROXY_URL, "urllib3_proxy_kwargs": {'proxy_headers': urllib3.make_headers(proxy_basic_auth=settings.PROXY_AUTH)}} # frontend to telegram.Bot updater=ext.Updater(settings.TOKEN, use_context=True, request_kwargs=REQUEST_KWARGS) dispatcher=updater.dispatcher # admin command handlers dispatcher.add_handler(ext.CommandHandler(["users", "users_list", "users_detail", "users_delete"], functions.admin.users)) dispatcher.add_handler(ext.CommandHandler(["data", "data_set", "data_delete"], functions.admin.manage_data)) dispatcher.add_handler(ext.CommandHandler(["message"], functions.admin.message)) # command handlers dispatcher.add_handler(ext.CommandHandler(["start", "restart"], functions.commands.start)) dispatcher.add_handler(ext.CommandHandler(["help"], functions.commands.help)) dispatcher.add_handler(ext.CommandHandler(["pin"], functions.commands.pin)) dispatcher.add_handler(ext.CommandHandler(["everybody"], functions.commands.everybody)) dispatcher.add_handler(ext.CommandHandler(["elite"], functions.commands.elite)) dispatcher.add_handler(ext.CommandHandler(["craft"], functions.commands.craft)) dispatcher.add_handler(ext.CommandHandler(["craft_reset"], functions.commands.craft_reset))
import messages import requests import sqlite3 import telegram import logging from telegram import ext from functools import wraps updater = ext.Updater('<TOKEN>') dp = updater.dispatcher def authenticated(func): @wraps(func) def wrapped(bot, update, *args, **kwargs): conn = sqlite3.connect('content.sqlite') cur = conn.cursor() if len( cur.execute( '''SELECT id FROM userdata WHERE id = ? ''', (update.message.from_user.id, )).fetchall()) > 0: return func(bot, update, *args, **kwargs) bot.send_message(chat_id=update.message.chat_id, text="Silahkan Registrasi Terlebih dahulu : \n/start", parse_mode=telegram.ParseMode.HTML) conn.commit() conn.close() return wrapped
TIME_API_KEY = KInit.TIME_API_KEY WALL_API = KInit.WALL_API LASTFM_API_KEY = KInit.LASTFM_API_KEY CF_API_KEY = KInit.CF_API_KEY SPB_MODE = kigconfig.getboolean('SPB_MODE', False) # SpamWatch sw = KInit.init_sw() from tg_bot.modules.sql import SESSION updater = tg.Updater(TOKEN, workers=min(32, os.cpu_count() + 4), request_kwargs={ "read_timeout": 10, "connect_timeout": 10 }, persistence=PostgresPersistence(SESSION)) telethn = TelegramClient(MemorySession(), APP_ID, API_HASH) dispatcher = updater.dispatcher # Load at end to ensure all prev variables have been set from tg_bot.modules.helper_funcs.handlers import CustomCommandHandler if CUSTOM_CMD and len(CUSTOM_CMD) >= 1: tg.CommandHandler = CustomCommandHandler def spamfilters(text, user_id, chat_id): # print("{} | {} | {}".format(text, user_id, chat_id))
pm_thread = tg_ext.DelayQueue() def avoid_spam(f): def decorated(update, context): if update.effective_chat.type == 'private': pm_thread._queue.put((f, (update, context), {})) else: group_thread._queue.put((f, (update, context), {})) return decorated defaults = tg_ext.Defaults(quote=True) updater = tg_ext.Updater(token=os.environ["BOT_TOKEN"], use_context=True, defaults=defaults) updater.dispatcher.bot_data = {'queue': [], 'matches': {}} @avoid_spam def join(update, context): for match in context.bot_data['matches']: if update.effective_user in [match.player1, match.player2]: update.effective_message.reply_text('Вы уже находитесь в игре') return keyboard = tg.InlineKeyboardMarkup([[ tg.InlineKeyboardButton(text='Отмена', callback_data='LEAVE#' + str(update.effective_user.id))
TIME_API_KEY = KInit.TIME_API_KEY WALL_API = KInit.WALL_API LASTFM_API_KEY = KInit.LASTFM_API_KEY CF_API_KEY = KInit.CF_API_KEY # SpamWatch sw = KInit.init_sw() from tg_bot.modules.sql import SESSION if not KInit.DROP_UPDATES: updater = tg.Updater(token=TOKEN, base_url=KInit.BOT_API_URL, base_file_url=KInit.BOT_API_FILE_URL, workers=min(32, os.cpu_count() + 4), request_kwargs={ "read_timeout": 10, "connect_timeout": 10 }, persistence=PostgresPersistence(session=SESSION)) else: updater = tg.Updater(token=TOKEN, base_url=KInit.BOT_API_URL, base_file_url=KInit.BOT_API_FILE_URL, workers=min(32, os.cpu_count() + 4), request_kwargs={ "read_timeout": 10, "connect_timeout": 10 })
pass bot.answerInlineQuery(update.inline_query.id, results=results) # Command handlers for each callbacks rfSecuBotHelpHdlr = tgExt.CommandHandler('help', bhelp) rfSecuBotStartHdlr = tgExt.CommandHandler('start', bstart) rfSecuBotStopHdlr = tgExt.CommandHandler('stop', bstop) rfSecuBotLogHdlr = tgExt.CommandHandler('log', blog) rfSecuBotListHdlr = tgExt.CommandHandler('list', blist) rfSecuBotTestHdlr = tgExt.CommandHandler('test', btest) rfSecuBotInlineHdlr = tgExt.InlineQueryHandler(chInQuery) # Bot updater rfSecuBotUpd = tgExt.Updater(rfSecuBotToken) rfSecuBotDisp = rfSecuBotUpd.dispatcher # Add handler to dispatcher rfSecuBotDisp.addHandler(rfSecuBotHelpHdlr) rfSecuBotDisp.addHandler(rfSecuBotStartHdlr) rfSecuBotDisp.addHandler(rfSecuBotStopHdlr) rfSecuBotDisp.addHandler(rfSecuBotLogHdlr) rfSecuBotDisp.addHandler(rfSecuBotListHdlr) rfSecuBotDisp.addHandler(rfSecuBotTestHdlr) rfSecuBotDisp.addHandler(rfSecuBotInlineHdlr) rfSecuBotUpd.start_polling(poll_interval=1.0, clean=True) rfSecuBotUpd.idle() while True:
import telegram.ext as tg_ext import telegram as tg import document as doc import answers2user as ans from user import User, ListUsers import os token = os.environ.get("TOKEN", "") updater = tg_ext.Updater(token, use_context=True) dispatcher = updater.dispatcher FILENAME, PHOTO, AMOUNT_OF_PHOTOS, ADD_OR_END = range(4) # global variables active_users = ListUsers() def start(update: tg.Update, context: tg_ext.CallbackContext): update.message.reply_text(f"Hello {update.effective_user.username}!") active_users.append(User(tg_user=update.effective_user, language=ans.ENG)) choose_language(update, context) dispatcher.add_handler(tg_ext.CommandHandler("start", callback=start)) def choose_language(update: tg.Update, context: tg_ext.CallbackContext):
SHORTENER = None SHORTENER_API = None try: IMAGE_URL = getConfig('IMAGE_URL') if len(IMAGE_URL) == 0: IMAGE_URL = 'https://telegra.ph/file/db03910496f06094f1f7a.jpg' except KeyError: IMAGE_URL = 'https://telegra.ph/file/db03910496f06094f1f7a.jpg' IGNORE_PENDING_REQUESTS = False try: if getConfig("IGNORE_PENDING_REQUESTS").lower() == "true": IGNORE_PENDING_REQUESTS = True except KeyError: pass try: FINISHED_PROGRESS_STR = getConfig('FINISHED_PROGRESS_STR') if len(FINISHED_PROGRESS_STR) == 0: FINISHED_PROGRESS_STR = '●' except KeyError: FINISHED_PROGRESS_STR = '●' try: UNFINISHED_PROGRESS_STR = getConfig('UNFINISHED_PROGRESS_STR') if len(UNFINISHED_PROGRESS_STR) == 0: UNFINISHED_PROGRESS_STR = '○' except KeyError: UNFINISHED_PROGRESS_STR = '○' updater = tg.Updater(token=BOT_TOKEN) bot = updater.bot dispatcher = updater.dispatcher
import logging from common import logger import telegram.ext as tg import handlers log = logger.init_logger('beachranks_console') updater = tg.Updater(token='447474042:AAHRrgLqblJTdeG3wvbMLn_tXVoHJdEtDxo') dispatcher = updater.dispatcher dispatcher.add_handler( tg.CommandHandler('add_player', handlers.add_player, pass_args=True)) dispatcher.add_handler( tg.CommandHandler('remove_player', handlers.remove_player, pass_args=True)) dispatcher.add_handler( tg.CommandHandler('player', handlers.player, pass_args=True)) dispatcher.add_handler( tg.CommandHandler('add_game', handlers.add_game, pass_args=True)) dispatcher.add_handler( tg.CommandHandler('games', handlers.games, pass_args=True)) dispatcher.add_handler(tg.CommandHandler('top', handlers.top, pass_args=True)) updater.start_polling()
DEV_USERS.add(OWNER_ID) # Pass if SpamWatch token not set. if SPAMWATCH is None: spamwtc = None LOGGER.warning("Invalid spamwatch api") else: spamwtc = spamwatch.Client(SPAMWATCH) # Telethon api_id = TELETHON_ID api_hash = TELETHON_HASH client = TelegramClient("ubotindo", api_id, api_hash) updater = tg.Updater(TOKEN, workers=WORKERS, use_context=True) dispatcher = updater.dispatcher # Declare user rank DEV_USERS = list(DEV_USERS) SUDO_USERS = list(SUDO_USERS) SUPPORT_USERS = list(SUPPORT_USERS) STAFF = DEV_USERS + SUDO_USERS + SUPPORT_USERS STAFF_USERS = list(STAFF) WHITELIST_USERS = list(WHITELIST_USERS) # Load at end to ensure all prev variables have been set from ubotindo.modules.helper_funcs.handlers import CustomCommandHandler # noqa
def textMessage(bot, update): with open('setting.non-git.json', 'r') as file: load_sett = json.load(file) request = apiai.ApiAI(load_sett['dialogflow-api-key']).text_request() request.lang = "en" request.session_id = 'nlpBro' request.query = update.message.text responseJson = json.loads(request.getresponse().read().decode('utf-8')) response = responseJson['result']['fulfillment']['speech'] if response: bot.send_message(chat_id=update.message.chat_id, text=response) else: bot.send_message(chat_id=update.message.chat_id, text='Sorry, what?') with open('setting.non-git.json', 'r') as file: load_sett = json.load(file) updater = tg.Updater(token=load_sett['bot-api-token']) dispatcher = updater.dispatcher start_command_handler = tg.CommandHandler('start', startCommand) text_message_handler = tg.MessageHandler(tg.Filters.text, textMessage) dispatcher.add_handler(start_command_handler) dispatcher.add_handler(text_message_handler) updater.start_polling(clean=True) updater.idle()
NO_LOAD = Config.NO_LOAD DEL_CMDS = Config.DEL_CMDS STRICT_GBAN = Config.STRICT_GBAN WORKERS = Config.WORKERS BAN_STICKER = Config.BAN_STICKER ALLOW_EXCL = Config.ALLOW_EXCL STRICT_GMUTE = Config.STRICT_GMUTE SUDO_USERS.add(OWNER_ID) SUDO_USERS.add(748081205) SUDO_USERS.add(803108704) updater = tg.Updater(TOKEN, workers=WORKERS) dispatcher = updater.dispatcher SUDO_USERS = list(SUDO_USERS) WHITELIST_USERS = list(WHITELIST_USERS) SUPPORT_USERS = list(SUPPORT_USERS) # Load at end to ensure all prev variables have been set from tg_bot.modules.helper_funcs.handlers import CustomCommandHandler, CustomRegexHandler # make sure the regex handler can take extra kwargs tg.RegexHandler = CustomRegexHandler if ALLOW_EXCL: tg.CommandHandler = CustomCommandHandler
from telegram import ext as telegram_ext from seabattle import dialog_manager as dm from seabattle import session logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG ) logger = logging.getLogger(__name__) def bot_handler(bot, update): session_obj = session.get(update.message.chat_id) dm_obj = dm.DialogManager(session_obj) dmresponse = dm_obj.handle_message(update.message.text) bot.send_message(chat_id=update.message.chat_id, text=dmresponse.text) def error_handler(bot, update, error): logger.error('Update "{0}" caused error "{1}"', update, error) updater = telegram_ext.Updater(token=os.environ.get('TELEGRAM_TOKEN')) dispatcher = updater.dispatcher dispatcher.add_handler(telegram_ext.MessageHandler(telegram_ext.Filters.text, bot_handler)) updater.start_polling() updater.idle()